Https and Android:

Https and Android:

We all know that we have to secure our web service calls and its very easy to intercept these calls if they are not properly secured. But getting this to work on Android is not that straightforward. After some substantial amount of research I found the easy way to get it working and decided to save some time for my co android developers.


private static int NET_TIMEOUT = 30000;
private static int NETWORK_POOL = 4;
DefaultHttpClient client = getClient(ctx);
HttpGet getRequest = new HttpGet(url);

Instead of instantiating the DefaultHttpClient  I implemented my own getClient  which would return the custom HttpClient with the SocketFactory enabled.

private static DefaultHttpClient getClient(Context ctx) {
DefaultHttpClient client;
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, NET_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, NET_TIMEOUT);
ConnManagerParams.setMaxConnectionsPerRoute(httpParams,new ConnPerRouteBean(NETWORK_POOL));
HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", newSSLSocketFactory(ctx), 443));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, registry);
client = new DefaultHttpClient(cm, httpParams);
return client;
}

registry.register(new Scheme(“https”, newSSLSocketFactory(ctx), 443)); is key here .

private static SSLSocketFactory newSSLSocketFactory(Context ctx)
{
try{
KeyStore trusted = KeyStore.getInstance("BKS");
InputStream in = ctx.getResources().openRawResource(R.raw.zynglstore);
try{
trusted.load(in,"changeme".toCharArray());
}finally{
in.close();
}
SSLSocketFactory mySslFactory = new SSLSocketFactory(trusted);
return mySslFactory;
}catch(Exception e){
throw new AssertionError(e);
}
}

Then coming back to the original code .

HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();

Http Post also should work the similar way.

Hope this helps.

I have created the keystore using http://portecle.sourceforge.net/ ..Portcele. This is a very handy tool

Concurrency in Flash ..

Over the weekend i came across a great blog post on Threads and ActionScript and some great info on Threading…Here is the link

http://wrongnotes.blogspot.com/2009/02/actionscript-and-concurrency-iii-of-iii.html

Android Location Based Services

Most of the android apps use the location-based services for geo coding to display things on Map. The three main classes that are used are

1.Location — This class represents a geographic location at a particular time

2.Location Manager – This class provides access to Android System Location services (Entry point)

3.LocationListener – This is an interface for receiving notifications from the Location Manager when ever the

location is changed.

The LocationManager needs to be initialized and its done the following way

locationmanager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

After the LocationManager is initialized the LocationProvider needs to be selected.The general way to find the proper location provider is to define the accuracy and the power requirement . This can be done as follows

android.location.Criteria --class is used for that

Criteria criteria = new Criteria();

criteria.setAccuracy(Criteria.ACCURACY_FINE);

criteria.setPowerRequirement(Criteria.POWER_LOW);

String locationProvider = locationmanager.getBestProvider(criteria,true);

so, then how do we retrieve the last Location ,,its simple ..the API provides us with a method called

getLastKnownLocation()

Location location = locationmanager.getLastKnownLocation(locationprovider);

and the latitude and the longitude can be retrieved by using

location.getLatitude() and location.getLongitude()

location.getExtras() can be used to retrieve the satellite information

2. How does the location get updated when ever the location is changed ..

Answer : The LocationListener interface is used to receive notifications when the location is changed.The locationManagers requestLocationUpdates() method needs to be called after the locationprovider is initialized to specify when the current activity is to be notified of changes.

the method requestLocationUpdates() takes the following parameters

1. provider — locationProvider

2. minTIme – The minimum time between updates in milliseconds

3. minDistance – The minimum distance change before updates in meters

4. listener  – the location listener that receive updates

This is called in the onCreateMethod

locationmanager.requestLocationUpdates(locationprovider,3000,3.0,this)

parameters explained :

1.locationprovider — the same locationprovider that’s initialized for the locationmanager

2. 3000 – this is the minimum time in milliseconds that’s required before the location is updated

3. 3.0 – this is the minimum distance in meters

4. the same class that’s calling the method is listening for the LocationChange event

Here is the snippet for the Listener

@Override

public void onLocationChanged(Location newlocation)

{

oldlocation = newlocation;

// logic goes here

}

The LocationListener can be implemented at an Activity Level or it can be implemented as a separate inner  class.

like

private final LocationListener mylocation = new LocationListener() {

@Override

public void onLocationChanged(Location newLocation)

{

oldlocation = newLocation;

//logic goes here

}

GEO CODING: Translating the Address into longitude and latitude .GeoCoder class is used to do this

example :

Method name used ..getFromLocationname()
 String address = "Dallas,Tx"
 GeoCoder geocoder = new GeoCoder(this);
try{
address1 = geocoder.getFromLocationname(address,1);
 if(address1 != null)
{
//create an object in the model called Address
 Address x = address1.get(0);
//logic continues
 }
}Catch(){
}

Reverse GeoCoding: This is quite obvious ..Translating a Location to Address

example:

location = locationManager.getLastKnownLocation(locationprovider);
List<Address> address;
 try
{
// the locale has to be set to english
GeoCoder geocoder = new GeoCoder(this,Locale.ENGLISH);
address = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);

and this returns a list of addresses.

//

Threads and Android

Have you ever seen this .Force shut down message on android ..

Every application by default runs a single process on creation and this process contains all the tasks. These kind of problems occur when there is no back ground thread running for time consuming tasks such as network downloads or computationally intensive tasks. Such heavy time consuming tasks interfere with the main application thread and cause issues like this.
lets take a look at few examples
Button musicplay_button = (Button) findViewById(R.id.music_play);
musicplay_button.setOnclickListener(new View.onClickListener(){

public void onClick(View view){
musicplay();
}
});
The musicplay() method might take a long time and it might block the application during if the user tries to  interact with the application as the application thread is still trying to resolve the musicplay().. so in cases like that when the user tries to navigate back to home screen or push the screen for some other activities ..we see error messages like these.
Thread backgroundThread = new Thread(
new Runnable() {
play void run () {
musicplay();
}
}

backgroundThread.start()
);
This peace of code should be put inside the onClick() method ..
There could be one more problem with this kind of code ..what happens when the user pauses the activity like navigating back to he home page . the music still continues.this is an undesired behavior.
In that case the musicplay() can be constrained with a boolean variable ..ismusicpaused or some thing like this
public void musicplay()
{

if (!ismusicpaused)
{
// continue with the logic

}

}
and this variable can be set to true in
// this method is called when the activity is paused
protected void onPause() {
ismusicpaused = true;
super.onPause();
}
Thread.sleep() can also be used if the music has to stop for some amount of specified time.

JVM Internals –Part 1

Programming languages have always fascinated me .I still wonder how a computer understands a bunch of english and math statements. Thats when i started learning and reading about Virtual Machines and Compilers. So I have decided to understand Java Virtual Machine as Java provides me bread and bed.I will be doing this in parts as JVM Internals is huge to cover in one single post.

Java Virtual Machine — Internals

Virtual machines are commonly used to distribute programs irrespective of architecture which can easily be compiled and interpreted. There has been a long running debate on the design on the VM’s on whether stack architecture or register architecture can be implemented more efficiently.

JVM(Java Virtual Machine) is a stack based virtual machine .. DVM (Dalvik Virtual Machine ) used for android is a register based virtual machine (i will discuss about this in another blog for now lets see how JVM works)..

JVM contains the following structures

  1. Heap store which is also  called the main store
  2. The Stack
  3. The Method Area
  4. Runtime Constant Pools
  5. The PC register

The JVM specification in fact talks about 2 stacks

1.The native stack or the C stack which is used to implement the JVM itself .This stack will be used by the C runtime system

2.The other stack is the JVM stack

This stack frame is allocated when control enters the method . It is deallocated when control returns from the method that caused allocation

There are 2 types of returns

  1. Normal return :  performed by executing “return” statement
  2. Abnormal return : some kind of exception occurred

All these stack frames are allocated in the heap. Each stack frame contains the following structures

Structures with in the stack frame description
Operand stack this is for the storage of temporary and intermediate results .
a set of local variables variables local to the method whose activation caused the stack frame to be created
A reference to the code associated with the method being executed These are the parameters passed from the calling method or the invoking method
PC Register A variable that always points to the instance up on which method operates

When a method is invoked, a stack frame is created for it. The parameters to be passed to it are evaluated and the results stored in the new stack frame.The code of the method is then executed using the newly created stack frame as its context.

If the method is a static method or also some times called a class level method then the parameters passed to it begin at the first element of the local variable array.

else if the method is an instance method the first element of the local variable array is reserved for self (also called “this” pointer in java language)

so a method call can be visualized as stacks being created and stacks being destroyed .

Return Control

Normal return : (with out errors)

when the “return” statement is executed the result is passed to the calling method, the called method’s stack frame is removed from the global JVM stack and is garbage collected.The PC(counter) in the existing stack frame is put in the JVM’s PC register as a return point

Abnormal return (Exception)

if the method makes an abnormal return by throwing out an exception and if that exception is not handled in the method body a search is performed along the call chain.The stack frame at which the exception is thrown and at which the exception is handled is removed from the JVM stack and garbage collected.

if the exception is thrown by a method called in one thread and is handled by a handler in other thread then the stack associated with the thread is terminated.

 

Part 2 to be continued ..

 

References : Virtual Machines by Ian D Craig ..

WebServices and SOAP UI

Soap UI has been a great tool to test web services(REST and SOAP) …Its one of the productive tools that i have come across recently. It can be downloaded for www.soapui.org .It also is available as a plugin for both Eclipse and Intelli J.lets see how it works for a simple REST ebay deals service.This is extremely useful when writing client side applications (web , desktop or even Mobile) especially if we are consuming some foreign services like (facebook,twitter,google base… etc etc)  and if we  need to know how they look before we parse the xml or json .and display ..

1.Click File –> New SOAP UI project

2. Click “OK” and then Enter the URL for the Service .. Here it is http://deals.ebay.com/feeds/xml and check the 2 check boxes.

3.Click “OK”

4. Click “OK”  and on the new screen ..Change the Method Name to “GetDetails”

5.Click “OK” .. click on the little green play button on the top and thats it — we can see a bunch of results

6 . The out put can be viewed in various formats like “xml” or “json” or “raw”

The below one is the raw format..

It not only makes it possible to test the deployed web services but it also offers the possibility to mock any external services.we can even write unit tests and automated test suite for various request types

In my next blog i will show on how to consume a SOAP webservice and write a test suite on them

Follow

Get every new post delivered to your Inbox.