Saturday, February 18, 2012

Android Framework: Application Development

Android development framework is relatively easier.The development is realy faster here.
Problem here is that developing UI  and it's layouts are a bit painful and it really consume most of our efforts. For GUI we
  •  Write xml by hand, very tedious and time consuming even with good text editor
  •  Use Eclipse and android plugin's layout editor. Very cumbersome, crappy user interface on the editor. 
What I feel is is that development of GUI for Android should be  done by UI expert specific to android specially  layout xml from some tools.

DroidDraw actually is currently the best tool for UI that can be used to build GUIs for Android.

Android Application :
Android application package file (APK) is the file format used to distribute and install application software and middleware onto  Android operating system.
 
Here we are going to look through samples for some common requirements.

How to configure the development set-up:
•    Install SDK starter package http://developer.android.com/sdk/index.html
•    Download ADT plug-in from the repository : https://dl-ssl.google.com/android/eclipse/
•    Configure ADT plug-in:: eclipse >window>preferences>     links to SDK to downloaded SDK directory.
•    Installing available packages for SDK
Eclipse, >Window > Android SDK and AVD Manager>Download at least one Platform SDK (>2.2)

How to set-up layout  view:
    setContentView(R.layout.YourApplicationLayout1.xml);
    setContentView(R.layout.main);

How to set access View componnets :
        Button buttonView = (Button) findViewById(R.id.viewButton);
        inputValue = (EditText) findViewById(R.id.inputText);

How to call activity on Button Press:
Button postBtn = (Button) findViewById(R.id.button1);
        moodMessageText = (EditText) findViewById(R.id.moodMessageText);
        mDate = (TextView) findViewById(R.id.datefield);
        postBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0);      
            //start calling activities 
            }
            }
        });

How to call Multiple Activities on some event:
   It's so  simple:
public class SourceActivity extends Activity {
            startActivity1(intent);
            startActivity2(arg0);
            }
               
How to pass parameters across Activities: 
Using Intent.
Intent intent = new Intent(SourceActivity.this,DestinationActivity.class);
        Bundle b = new Bundle();
        b.putString("paramater1", parameter1Value);                           
                intent.putExtras(b);
            startActivity(intent);:

public class DestinationActivity extends Activity {
        Bundle b = getIntent().getExtras();
        String moodMessageTextVal = b.getString("moodMessageText");
        String dateVal = b.getString("date");

How to create List View:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
  <ListView android:id="@android:id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
  <TextView android:id="@android:id/empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/no_notes"/>
</LinearLayout>


How to show  message  pops up on the surface of the window:
Toast toast = Toast.makeText(getApplicationContext(), yourMessages, duration);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
How to populate List View from SQLite DB:
public class RenderListViewActivity extends ListActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.RenderListViewPage);
               DBHelper dbHelper = new DBHelper(this);
              Cursor c = dbHelper.getAllListRecords();       
        fillListViewData(c);       
     }   
    private void fillListViewData(Cursor c) {
           startManagingCursor(c);
        String[] from = new String[] { "headerCol1","headerCol2", "headerCol3"};
        int[] to = new int[] { R.id.headerCol1,R.id.headerCol2,R.id.headerCol3 };    
         SimpleCursorAdapter listBeanData =
            new SimpleCursorAdapter(this, R.layout.listitem, c, from, to);
         setListAdapter(listBeanData);
    }

How to open a URL in Webview:
layout configuration
<WebView android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/myWebview"/>"
 code:
    WebView webview = (WebView)findViewById(R.id.myWebview);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setInitialScale(100);      
        webview.setWebViewClient(new WebViewClient()
        webview.loadUrl(yourWebUrl);

How to show process dialog:
 ProgressDialog  progressdialog = ProgressDialog.show(this, "",
                "Loading. Please wait...", true);
    webview.setWebViewClient(new WebViewClient() {          
          public void onPageFinished(WebView view, String url) {
                if (progressdialog.isShowing()) {
                    progressdialog.dismiss();
                }
            }
        });

Emulator:
The Android SDK includes a mobile device emulator — a virtual mobile device that runs on your computer. which can be used for developing and testing Android applications without using a physical device.

Android Pencil utility tool is  available here android-ui-utils .
Google has started a project called App Inventor to give non-programmers a relatively easy way to build their own applications for the Android.

I feel that Android UI tools always have a BIG BIG scope of improvement. Otherwise It would be really difficult for Android to chase with IPhone.
How is your experience with Android?


Friday, February 10, 2012

State management in Restful Application



                                   First of all, let’s discuss about why should we prefer to use REST Services: 
       
            Advantages:
  • Simple.
  •  You can make good use of HTTP cache and proxy server to help you handle high load.
  • It helps you organize even a very complex application into simple resources.
  • It makes it easy for new clients to use your application
  •  It makes it easy for new clients to use your application, even if you haven't designed it specifically for them  probably, because they weren't around when you created your app.
  • Also, because REST relies on the semantics of HTTP, requests for data (GET requests) can be cached.


A REST web application requires a different design approach than an RPC application. In RPC, the emphasis is on the diversity of protocol operations, or verbs; for example, an RPC application might define operations such as the following:
With REST, on the other hand, the emphasis is on the diversity of resources, or nouns; for example, a REST application might define the following two resource types

The problem is that although it is easy to model resources as services as shown in the example in many cases it is quite difficult to model a service as a resource.

RESTful services are stateless. Each request from client to server must contain all the information necessary to understand the request, and cannot take advantage of any stored context on the server.”

Use Case:
Consider a scenario where a user logs in to an ecommerce site. He adds few items into his basket. Then he will proceed for buying the product followed by transaction.

Problem:
If the e-commerce web site runs on restful services running somewhere on Himalayas. The server running at the top hill needs to know about all the requests which are coming by the same user.Right?.

Dialogue:

Client: Hey, I want to buy few Reebok shoes. Please proceed.
Services: Sorry, I could not identify you? Give me few more details.
Client: I have already logged in to your application!
Server: I do not remember any things. Sorry.

Solution:

Server should know the state of the client call .We need to provide some hook to track the requests.

What we need to do:
  • Verify if all the requests coming to the server are authenticated.
  • If no, then send authentication error in the response code.
  • In case of request for authentication request generate Session , you are free to use any authentication Mechanism say Oauth 2.0,/ Basic Authentication/ Digest Authentication.
  • If yes, verify the rest call has have some token through which the server will identify the User.
  • Update the profile of the user say if the user has added items into his basket then the basket Items need to be updated in his profile.
  • For any request, you validate the session by inspecting the information stored inside the session.
  • Persist the profile somewhere in Memory or Cache.
  • When the user’s log’s out take appropriate action whether the state needs to be persisted somewhere into the data base or simply clean the session. 
  Client side Implementation: Use Cookie for Browser, Application memory for Smart Phone.
  Server side Implementation: Use Request and Response Handler or In/Out Interceptor, Security      Interceptors

Conclusion:
Conforming to REST constraints is definitely not simple. Squeezing complex business operations into four standard verbs is actually really hard sometimes.Also, REST has no support for distributed transactions.
So design your application client adaptable enough to rely on both rest and SOAP based Services.

Friday, February 3, 2012

Cross Domain Solution with Ajax

                      

Let us discuss about the 'Root cause' of the problem:

Same origin policy:
The same-origin policy prevents a script loaded from one domain from getting or manipulating properties of a document from another domain. That is, the domain of the requested URL must be the same as the domain of the current Web page. This basically means that the browser isolates content from different origins to guard them against manipulation

Wep applications extensively depend on HTTP cookies to maintain authenticated user sessions, as servers act based on the HTTP cookie information to reveal sensitive information or take state-changing actions. A strict separation between content provided by unrelated sites must be maintained on client side to prevent the loss of data confidentiality or integrity.

Hence the 'Problem' is :

Ajax does not allow cross-domain communication because of restrictions imposed by the browser. If you try to request data from a different domain, you will get a security error/405 error.

Use Case:
Single Page Application, Restful Application

And here are the Solution:
This problem can be bypass in several ways,

Solution I : Create a proxy files at the server side located in same domain.
We can create a proxy files which will bypass the cross domain request. The proxy page will receive a request, and then make a server side requested and response the output. Below I give a PHP solution of the proxy files,
File name: geoproxy.php
   <?php
    $url=$_GET["url"];
    $res = file_get_contents($url);
    echo $res;
    ?>
This page receives the request and echoes the response. So, now we do not make ajax call the different port service directly, instead call the proxy page by “geoproxy.php?url=http://somedomain:port/ geoserver/wms?service=WMS&request=GetFeatureInfo”.

In a similar way for java based application we can use Servlet or JSP tp redirect to some other page with the request data.

This solution has some security risk, because external user can use your bandwith for bypass their route. So, restrict the requester server by checking page referrer. To do that there needs small modification of existing code.

Solution II: Use Reverse proxies web server
Requests can be bypass using apache mod_proxy.so module. It needs some configuration change in httpd.conf file. Uncomment below module in apache httpd.conf file,
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
Now add proxy bypass code below of the file,
ProxyPass /geotest http://localhost:8080/page.html
ProxyPassReverse /geotest http://localhost:8080/ page.html
Restart the apache. Now /geotest requeste are redirected.

Note that in Apache RewriteEngine is On by default so no need to specify  rewrite rule there.

Solution III: Use JSONP (Only 'Get' operation is supported.)
One such mechanism which can request content cross-domain is the <script> tag. JSONP can be used as a way to leverage this property of <script> tags to be able to request data in the JSON format across domains. JSON-P works by making a <script> element (either in HTML markup or inserted into the DOM via JavaScript), which requests to a remote data service location
Sample url:
http://otherdomain.com:/getUserData/111?callback=?'
And the ajax call looks like
'url: url,
success: success,
 type: "GET",
dataType: "jsonp",
//contentType: "application/json;
 charset=utf-8",           
Note that type is ‘get’ and data type is ‘jsonp’

The best solution I think is, using Reverse proxies (Solution II ) where NginX is the best choice for us.