Saturday, 23 November 2013

Working with cURL on android

READ Daily HOROSCOPE on WWW.ZODIACPAGE.COM



Why is it necessary


We want to communicate with the server API to write C + +, and then use a library written in all our applications on different platforms. Of course we want to work under android. Libcurl - the API is a library for transmission, that developers can integrate into their programs; cURL acts as a wrapper for a standalone library libcurl. libcurl is used to provide the ability to transfer files (addressable via URL) multiple applications (both open and commercial). ( Wikipedia ) For iOS, you can download a ready example of connecting and using cURL from the developer. And with iOS simple. Under android google me in the vast could not find any source, wherever produced the successful treatment of this cross-platform library. (Maybe I'm bad looking). And generally forced to work under android cURL turned out a little harder than I would like.









What you will need:

  • Installed and configured to work with android Eclipse ;
  • ndk and the ability to work with him;
  • Skompilennaya under android library cURL .

Getting libraries cURL for android


If you go to a website cURL and go to the download, you can find there skompilenny binary (Android 7.31.0 binary SSL) which apparently can be run from the command-line utility for device. But it is useless if we want to work with the library from your application. 
Okay Googling can find a tutorial how to collect the necessary ndk *. a library, which can already run the application. there about porting cURL under android and Habre . As a result, we obtain the desired *. A library file. I myself was not collected. I downloaded it honestly.



Further


Next the resulting library can safely insert the project and using the full power ndk access it.
Java part part

Create MainActivity with one button and a field for entering URLs, from which we receive information. activity_main.xml :


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
        <EditText
           android:id="@+id/server_url"
           android:text="@string/default_url"
           android:hint="@string/server_url_hint"
           android:layout_width="match_parent"
            android:layout_height="wrap_content"
           android:singleLine="true"/>      
        <Button android:id="@+id/button_curl_call"
            android:layout_below="@+id/server_url"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
               android:layout_alignParentRight="true"
               android:text="@string/button_curl"
               android:layout_gravity="right"
               />    
        <TextView
            android:id="@+id/text"
            android:layout_below="@+id/button_curl_call"
            android:layout_weight="1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
        />
</RelativeLayout>


MainActivity.java
package com.ifree.ndkNative;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

Public  class  MainActivity  extends  Activity { 
    Private  static  final String INTENT_HTML_DATA = ". html_data" ;
     Public  static  final  int HANDLE_CALLBACK = 0 ;
     final  Private Handler handler = New Handler () {

        @ Override 
        Public  void handleMessage (Message msg) {
             Switch (msg.what) {
                 Case HANDLE_CALLBACK:
                 String html = msg.getData (). GetString (INTENT_HTML_DATA);
                 SetHtmlText (html);
                    Break ;
            }
        }
    };    
    
    Private  void SetHtmlText (HTML String) {
     TextView tv = (TextView) findViewById (R.id.text);
     tv.setText (html);
    }
    
    / ** Called when the activity is first created. * / 
        @ Override 
        Public  void onCreate (Bundle savedInstanceState) {
             super . onCreate (savedInstanceState);
            setContentView (R.layout.activity_main);
            
            final EditText serverUrl = (EditText) findViewById (R.id.server_url);
            
            Button btnCurl = (Button) findViewById (R.id.button_curl_call);
            btnCurl.setOnClickListener ( New OnClickListener () {
                 @ Override 
                Public  void onClick (View v) {
                    Native curl = New Native ();
                    curl.addCurlCallbackListener ( New ICurlCallbackListener () {
                         @ Override 
                        Public  void curlCallBack (String callback) {
                             / / in order to synchronize with the flow gui and display the resulting text in the TextView, use handler 
                            Bundle Bundle = New Bundle ();
                            bundle.putString (INTENT_HTML_DATA, callback);
                            Message message = handler.obtainMessage ();
                            message.setData (bundle);
                            handler.sendMessage (message);
                        }
                    });
                    String response = curl.get_text_from_cpp (String.valueOf (serverUrl.getText ())); / / Actually itself appeal to the C + + parts
                }
            });   
        }
}


Write a class Native.java , which will be an appeal to the C + + code.
package com.ifree.ndkNative;

import java.util.HashSet;

Public  class  Native { 
    Private HashSet <ICurlCallbackListener> callBackListeners = New <ICurlCallbackListener> HashSet ();
    
    Public  void addCurlCallbackListener (ICurlCallbackListener listener) {
        callBackListeners.add (listener);
    }
    
    Public  void removeCurlCallbackListener (ICurlCallbackListener listener) {
        callBackListeners.remove (listener);
    }
    
    static {
           System.loadLibrary ( "ndkNative" );
        } 
    / / (Keyword native says that the implementation will be in C + +): 
    Public  Native get_text_from_cpp String (String Data);
     Private  void callback (String Data) {  
         for (ICurlCallbackListener listener: callBackListeners) {
            listener.curlCallBack (data);
        }
    }
}


Must not forget to add to AndroidManifest permit Internet 
< uses-permission  android: name = "android.permission.INTERNET" />

C + + part

Created by the utility javah file com_ifree_ndkNative_Native.h
/ * DO NOT EDIT THIS FILE - it is generated Machine * / 
# include <jni.h> 
/ * Header for class com_ifree_ndkNative_Native * /

# Ifndef _Included_com_ifree_ndkNative_Native 
# define _Included_com_ifree_ndkNative_Native 
# ifdef __ cplusplus 
extern "C" {
 # endif 
/ *
 * Class: com_ifree_ndkNative_Native
 * Method: get_text_from_cpp
 * Signature: (Ljava / lang / String ;) Ljava / lang / String;
 * / 
JNIEXPORT jstring JNICALL Java_com_ifree_ndkNative_Native_get_1text_1from_1cpp
  (JNIEnv *, jobject, jstring);

# Ifdef __ cplusplus
}
# Endif 
# endif


We define a function to get data from the server (JNICALL Java_com_ifree_ndkNative_Native_get_1text_1from_1cpp) inndkNative.cpp
# Include <string.h> 
<stdio.h> # include 
# include "stddef.h" 
# include <jni.h> 
# include "com_ifree_ndkNative_Native.h" 
# include "curl / curl.h" 
# include "curl / Easy . h "

JNIEnv * gEnv;
jobject gObj;

void function_callback (jstring str) {
      jclass cls = gEnv-> GetObjectClass (gObj);
      jmethodID Mid-gEnv => GetMethodID (cls, "callback" , "(Ljava / lang / String ;) V" ); / / method call from java Native.callback (String data)
      gEnv-> CallVoidMethod (gObj, mid, str);
}

size_t function_pt (void * ptr , size_t Size, nmemb size_t, void * Stream ) {
    function_callback (gEnv-> NewStringUTF ((char *) ptr));
    Written = size_t fwrite (ptr, Size, nmemb, (FILE *) Stream);
       if (Written <= 0 )
       return Written * Size;
}

JNIEXPORT jstring JNICALL Java_com_ifree_ndkNative_Native_get_1text_1from_1cpp
  (JNIEnv * env, jobject obj, jstring str)
{
    gEnv = env;
    gObj = obj;

    CURL * curl ;
    CURLcode res;
    curl = curl_easy_init ();
    if (curl) {
        curl_easy_setopt (curl, CURLOPT_URL, env-> GetStringUTFChars (str, 0 ));
        curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, function_pt);
        res = curl_easy_perform (curl);
        curl_easy_cleanup (curl);
        / * Check for errors * / 
        if (res! = CURLE_OK)
            function_callback (gEnv-> NewStringUTF (curl_easy_strerror (res)));
      } else {
          function_callback (gEnv-> NewStringUTF ( "error" ));
      }
      return env-> NewStringUTF ( "ok" );
}


Android.mf
LOCAL_PATH  : = $ ( call my-dir)

include  $ ( CLEAR_VARS )

include  $ ( CLEAR_VARS )
 LOCAL_MODULE : = libcurl
 LOCAL_SRC_FILES  : = libcurl.a
 include  $ ( PREBUILT_STATIC_LIBRARY )

include  $ ( CLEAR_VARS )
 LOCAL_MODULE     : = ndkNative
 LOCAL_SRC_FILES  : = ndkNative.cpp
 LOCAL_STATIC_LIBRARIES  : = libcurl
 include  $ ( BUILD_SHARED_LIBRARY )


Source

https://dl.dropboxusercontent.com/u/38942741/ndkNative.zip

Disclaim template template parameters

Use template template parameters C + + is difficult. I want to demonstrate the power and boost :: mpl show trick to describe patterns, completely abandoning the template template parameters. 
Demonstrate problem. There is a class that takes an object type and the type of container for this object.
template < typename T, typename Container>
 struct A
{
  typedef Container <T> type;
};

So you can not write, you should use the template template parameters, to indicate that the Container itself is structured.

Correctly write:
template < typename T, template < typename > class Container>
 struct A
{
  typedef Container <T> type;
};

Use this:
typedef A < int , STD :: vector > :: type type;

At the first use we get a compilation error. We have forgotten that std :: vector takes two parameters, one of which is usually the default. Well, we can rewrite:
template < typename T, template < typename , typename > class Container>
 struct A
{
  typedef Container <T, STD :: allocator <T>> type;
};

There are two obvious problems:
  1. We must look into the implementation of std :: vector, find out what type allocator used by default, and then use it.
  2. We wrote a template will not work if the container is more than one template parameter default.

I would like to avoid explicit default type and complex syntax template template parameters. Comes to the aid technique based on the use of placeholders boost :: mpl, are used to create a lambda metafunctions. Externally, the only difference is that you need to pass to our template is not the template container and container instantiated template placeholders, ie instead


typedef A < int , STD :: vector > :: type type;
write
typedef A < int , STD :: vector <boost::mpl::_1> > :: type type;

To instantiate instantiated placeholder container necessary type using boost :: mpl :: apply:
# Include <boost/mpl/apply.hpp> 
template < typename T, typename Container>
 struct A
{
  typedef  typename :: boost :: MPL apply <Container, T> :: type type;
};

Using this trick in real programming help simplify some of your intricate patterns.

Fresh impressions of BlackBerry 10 NDK

The last two weeks I have again delved into the BlackBerry 10 NDK, as one of my clients asked me to help him. I suggested to adapt their course "Introduction to Qt» under the platform BlackBerry, and also recommended to follow the advice of my series of instructional videos about BB10 and Cascades , published earlier this year on YouTube. Now I want to share with you my impressions of the fresh BlackBerry 10 NDK. By the way, I wrote about my first experiments with BB10 NDK this spring. Attention.This is a free translation notes Yensa Weller. Translation made ​​for an overall picture of the current state of the world [BB10 + Qt]. Happy reading.



Applications and C + +

Before we start, a little introduction about applications and C + +. People migrating from other languages, such as Java or. NET, often do not understand the need for writing applications is C + +. Especially migrating from languages ​​forcibly tied to the PLO and the garbage collector - it is not easy to understand all the concepts used in C + +. I think, in fact, there are many reasons to use C + + application development, especially in conjunction with such a powerful framework Qt. One of the reasons - performance, because C + + is really closer to the hardware, your application will eat at least battery. Not to mention that there is a ceiling of growth performance of the devices in the future, this Herb Sutter mentioned in his article "free soldering ended" (there is a translation HabrĂ© from Webmascon - approx. translator ). Qt Framework is now available for Android and iOS, so that C + + and Qt / QML become really powerful combination for creating mobile applications.

NDK and Cascades

Therefore, when you are developing applications for BlackBerry 10, you must begin with BlackBerry NDK . I did not have enough time to play with svezhevyshedshey 1.2 version, but the IDE at first sight has become much better and more stable. 1.2 but has not yet received a "gold" status (fixing API, has already received - approx. translator ), so I recommend to write under 1.1, except that you need anything from 1.2. BlackBerry NDK comes with Cascades Framework, API which you will use to develop applications for BB10. Cascades is made ​​over and uses Qt QML, while there have Qt5 QtQuick 2 because its implementation BlackBerry QML, working in UI-thread. So QML, created under QtQuick1 or 2 will not work under Cascades. And Qt5 not fully supported Cascades - the current version is based on Qt 4.8. Since 2010 I'm interested in mobile development on Qt and QML, was formerly occupied by MeeGo, and now I'm with BlackBerry. QML BB10 in slightly different, it uses special elements such as: Container, Pages and Controls, whereas in QtQuick1 / 2 provides a very basic elements or the like Item Rectangle. So for QML and its API in BlackBerry has its own little world. Meanwhile Qt5-application can build and run on BB10, though it will not be accompanied by a degree of integration that offers Cascades.



QML and C + +

According to the documentation and discussions, the basic approach involves the use of QML for most tasks and bridges in C + + only when necessary. For example, when writing models in C + + and declaring class methods using Q_PROPERTY to access their QML. Then most of the work takes place on the side of QML. In QML few ways of verification and error checking, such console.assert, but since QML trasliruetsya in JavaScript and has no storogoy typed, therefore, can not verify compliance types.Typo in a variable name will lead to the fact that QML may not notice this error, and to calculate the variable declared new. A simple example:

Container {
    layout: DockLayout {
    }
    Label {
        text: ListItemData.titel
    }
}

This simple item to display in the container ListView , through ListItemData we get access to the data to display. I've made ​​a small mistake, in fact an element called title , and titel - it's in German. Especially, the German is not immediately notice. A QML not notice the more. You can insert any word here, QML does not check such errors at compile time or at runtime. Nothing will be displayed, you may be lucky to find a warning in the console. By the way, if properly configure IDE, then the message should appear exactly, even when debugging on the device. How to fight it? Cascades hiding behind C + + application framework built on Qt, so that at least in C + + we have a chance to detect it and record the error. Unfortunately, it is impossible to detect at compile time, but I'm working in this direction. So Q_ASSERT makes checks during application. For all elements of the Cascades, involved in QML, a class in C + +, dynamically instantiated for each element at runtime. Cascades API lets you search for objects of these classes, and provides a way to control whether certain things. For ListView as a class, delivering items to ListView in C + +: ListItemProvider . This class has its own interface:



virtual cascades bb :: * :: VisualNode createItem (bb :: cascades :: ListView ListView *, const QString & type);
 virtual  void updateItem (bb :: cascades :: * ListView ListView, bb :: :: cascades VisualNode * node, const QString & type, const QVariantList & indexPath, const QVariant & Data);

Its implementation of these methods allows you to create virtual items for display in ListView and also fill them with actual values.BlackBerry provides examples of implementation. Unfortunately, these examples are not using QML, and written entirely in C + +.But I personally like to use QML for UI. And this OOP-style like in the example of the BlackBerry, implies inheritance fromListItemProvider for each individual ListView , and I would like to solve this problem once and for all, so I have my own generalized ListItemProvider . Since all checks occur at runtime, templates C + + - is not an option, let's look at the following implementation. Before I move on to crateItem, brief otsanovka on addType, helper method for declaring handlers for each type:

void ListViewItemProvider :: addType ( const QString & type, const QString & qmlasset, const listitem_callback & callback)
{
    bb :: cascades :: QmlDocument * doc = bb :: cascades :: QmlDocument :: create (qmlasset);
    if (! doc-> hasErrors ())
    {
        doc-> setParent ( this );
        type_map.insert (type, doc);
        callback_map.insert (type, callback);
    } / / TODO Add additional error checking & Handling
}

This method adds different for different types of processors. Types are described in QML using objects QString , so QMap <QString, QmlDocument*> be enough to keep the supported types. This method converts qml-resource (for example, file :/ / / partial.qml - approx. translator ) in QmlDocument using QmlDocument :: create . Incidentally, QmlDocument :: create not actually returns QmlDocument * , as it is written in the above example. It returns a reference to a utility class Builder to createQmlDocument 's, then, it seems, produces an implicit conversion in QmlDocument * . In principle, there is nothing interesting going on, method createItem :

bb :: cascades VisualNode :: * :: ListViewItemProvider createItem (bb :: cascades :: ListView ListView *, const QString & type)
{
     if (type_map.find (type)! type_map.end = ())
     {
          bb :: cascades :: Container * node = type_map [type] -> createRootObject <bb::cascades::Container> ();
          return node;
     }
     Q_ASSERT_X ( false , __FUNCTION__, type + "TYPE not handled" );
     bb :: cascades :: Container * con = New bb :: cascades :: Container ( 0 );
     bb :: cascades :: Label * label = New bb :: cascades :: Label (con);
     label-> setText ( "ERROR" );
      return con;
}

This code first checks the registration type, and then creates an object through a method QmlDocument :: createRootObject , which returns a pointer to the created object. This is a template, so we need to know in advance the type of object to create.Until I decided for myself that for all UI elements I will use Container as the root object. Perhaps there is also suitable typeVisualNode * , which is the return value of the createItem . Here the most interesting - error handling, how should we do it? But here enters Q_ASSERT_X and notifies an error. But in the case of assembly without debugging it will not complain, but nevertheless the method should return a value. About 0 nothing is said in the documentation, so there is no reason to think that this is the correct return value for this method. But the documentation clearly indicates that the returned pointer will belong ListView Even if we return 0 (fortunately, the developers have provided it BB10), it conceals a mistake from the tester. So I decided to return a small Container with Label text with error. Maybe I could formulate a better message, but in this embodiment, the tester will soon notice this error. Alternatively, you could throw an exception, but then control is passed back to the Cascades API and Qt, but it is not the best option, as Qt and Cascades do not use exceptions, even though they are supported in BB10. last thing you want to realize - method updateItem . Again, do not get easier, because we write code generalizations. In the end, downloadable QML file must be loaded with the correct values, which is also one of the reasons why I decided to write a bike implement generalized approach. But there is an option to borrowing for the implementation of this right from our Klas - we registered callback to create the right types of objects, is now simply call the corresponding callback method in updateItem :



if (callback_map.find (type)! callback_map.end = ())
{
# Ifndef USE_BOOST
        (* Callback_map [type]) (node, indexPath, data);
# Else
        callback_map [type] (node, indexPath, data);
# Endif
}

Up to this point I could not use / hide defayn USE_BOOST , but for such callbacks C + + programmer should first consider boost :: function . And as BlackBerry argues that boost support, I certainly use it. And then it turns out that it's not easy, at least my tulchayn falls to a bug in boost / type_traits / Detail / cv_trait_impl.hpp . I know that boost is used by many, so it's probably my fault due to the setting tulchayna distribution or Linux. Error apparently comes from the preprocessor on version GCC 4.6.3, the text said about the mismatch error brackets. I prefer my version patch boost the local machine and reported it to the community and boost BlackBerry. If you use a boost under BB10, you'd better use the version with boost GitHub'a BlackBerry .Since not everyone needs a boost, I also made ​​a version without it, in case you break a boost again. And last but not least, the implementation callback'a:



void ApplicationUI :: callbackMyListItem (bb :: cascades VisualNode :: node *, const QVariantList & indexPath, const QVariant & Data)
{
    bb :: cascades ImageView * Image :: = node-> findChild <bb::cascades::ImageView*> ( "imageview" );
    Q_ASSERT (image);
    if (Image)
    {
        QString name_image = "Image" ; / / this must be correct! 
        QVariantMap map data.toMap = ();
         bool = hasdata map . contains (name_image);
        Q_ASSERT (hasdata);
        if (hasdata)
            Image-> setImageSource ( map [name_image]. tourl ());
    }
}

In this case, the path to the image set. Pointer to VisualNode inherits QObject , so that the child objects can be obtained through findChild , which returns 0 if nothing is found. It is therefore appropriate to use here Q_ASSERT to verify this case. Then the search data QVariantMap . Since we are in any case need any image, checks element in the container QVariantMap. If not, then Q_ASSERT again comes to the rescue. This callback just registered using boost :: bind . Finds values ​​can also be implemented through the model, but BB10 not support conventional models of Qt, instead BlackBerry implemented their model classes. In general, it is good, but I personally prefer the model of Qt, the more it is allowed to use them when porting Qt-applications for Android, iOS, PC / Mac or even Jolla. KDAB - one of our "gold" sponsors - published decision that eliminates this misunderstanding and makes Qt-model suitable for use in the Cascades .



IDE

Now, a few words about the IDE. As I said earlier, IDE has improved with the release of version 1.2. Wednesday is improving, but in some cases is still far from sovershentsva. Editor for QML prezhdnemu not good enough, but now in the fall do not drop the entire IDE. An alternative could be the Qt Creator, it also improved support for QML. At this point, it seems to me Momentics IDE (based on Eslipse - approx. interpreter ) from BlackBerry better than QtCreator, if it developed under the Cascades. First, there is no integration with QtCreator Cascades at all, so autocompletion QML will not work, because in NDK otsustvtuet required for this file.For the same reason will not work visual editor QML. Qt, of course, a little better supported in QtCreator, but in version 1.2 NDK really a lot of improvement in this direction. Project templates offered QtCreator, not as good as in Momentics, for example, they lack the integration of localization code. I like the fact that templates include Momentics QTranslator in main.cpp . Momentics QtCreator and deception can create a working application under my DevAlpha device, so that the development of a BB10 in QtCreator possible, but has room to grow. I downloaded the source code ListViewItemProvider , if you need ...