How to get *root* access in Android Emulator

***This article is current as of Sept 2013***

I read many articles and forums for getting the root access on Android Emulator or phone but none of them worked for me *as is*, so I thought of putting together a series of instructions that worked for me and hopefully will work for you as well.

  1. Here is what you need to download
    1. su
    2. Superuser.apk
  2. Did you set Android SDK path in your environment variables or in short can you open a command or terminal window and type adb and see if the path is set?
    1. if yes then you can copy the above two files anywhere you want and just move to that directory
    2. If no then just copy the above two files to your <YOUR_SDK_INSTALL_DIR_PATH>/platform-tools/
  3. Make sure to start your emulator now and wait until it is all good or basically it shows up when you execute “adb devices” command. Also make sure only one emulator is running and no other devices are connected.
  4. In your terminal/command window go to the following location <YOUR_SDK_INSTALL_DIR_PATH>/platform-tools/ and get ready to execute few commands.
    1. adb remount
    2. adb push su /system/xbin/su
    3. adb shell chmod 06755 /system
    4. adb shell chmod 06755 /system/xbin/su
    5. adb install Superuser.apk

If all goes well so far then you have root access now. You can check that by following commands
adb shell
su
You should now get su access!

Note: Any time you restart the emulator then you have to repeat step 4.C and 4.D

JQuery Ajax auto-complete with Spring MVC and REST

Objective

Implement auto complete feature such that when we enter two characters in a text field a drop-down should appear with the remaining content which starts with those characters.

Purpose

Learn how auto complete work with stand alone data or with remote data coming from a distant server in conjunction with Spring MVC framework or a REST call.

Things Needed

Jquery and knowledge of Spring Controllers along with basic understanding of Spring MVC.

Approach

To achieve this we implement city auto complete feature meaning when we enter two characters then all the cities starting with those two characters will appear and so on.

1.  Auto complete with Local Data

Most simple form of Auto complete example with stand alone data meaning the data is within the local javascript function. If you copy this code and save it as an html file then you can see it working. Notice that we are using a little older version of JQuery jquery-1.6.2.js The reason is that JQuery-UI must be following up with the changes in latest revisions etc. See the workable demo in cloud foundry http://autocomplete.cloudfoundry.com/ajaxLocal.html

Another point to note is the ajax call

 $(function() {$( "#city" )

.autocomplete({source: ["Minneapolis", "Minnehaha"]});

}); 

we are binding the input text field “city” with the ajax call. The $ here says that its a callback function.


<html>

<head>

<link rel="stylesheet" href="js/jquery-ui-1.8.16/themes/base/jquery-ui.css" type="text/css" />

<link rel="stylesheet" href="js/jquery-ui-1.8.16/themes/base/jquery.ui.autocomplete.css" type="text/css" />

<script src="js/jquery-ui-1.8.16/jquery-1.6.2.js"></script>

<script type="text/javascript" src="js/jquery-ui-1.8.16/ui/jquery-ui.js"></script>

<script type="text/javascript" src="js/jquery-ui-1.8.16/ui/jquery.ui.core.js"></script>

<script type="text/javascript" src="js/jquery-ui-1.8.16/ui/jquery.ui.position.js"></script>

<script type="text/javascript" src="js/jquery-ui-1.8.16/ui/jquery.ui.widget.js"></script></head>

<script>

$(function() {$( "#city" )

.autocomplete({source: ["Minneapolis", "Minnehaha"]});

});

</script>

<input id="city" />

</html>

2.  Auto complete with Data from Local Spring controller

Next form of Auto complete example is with calling a spring controller to provide you dynamic result sets. We created a Spring MVC controller called ZipcodeController.java with request mapping url “/ajaxcitySearchGeneral” here is how the code look. see the workable demo in cloud foundry http://autocomplete.cloudfoundry.com/ajaxToLocalController.html

@Controller

public class ZipcodeController

{

/**

* This method will return same set of zipcodes all the time.

*

* @return Map<String, List<ZipcodeDetails>> represents a JSON name value pair

*/

@RequestMapping(value="/ajaxcitySearchGeneral", method = RequestMethod.GET)

@ResponseBody

public Map<String, List<ZipcodeDetails>> getZipcodes()

{

List<ZipcodeDetails> zipcodes = new ArrayList<ZipcodeDetails>(Arrays.asList(new ZipcodeDetails("55401", "Minneapolis", "MN"), new ZipcodeDetails("1949", "Middleton", "MA"), new ZipcodeDetails("2055", "MINOT", "MA")));

Map<String, List<ZipcodeDetails>> zipMap = new HashMap<String, List<ZipcodeDetails>>();

zipMap.put("zipcodes", zipcodes);

return zipMap;

}

}

Here we are hard coding the data in the spring controller but as you can see we can make a call to persistence layer and get dynamic data. The java script and html for this will look like below code.


<!--

! Spinach Software & Consulting LLC

! Copyright 2011 by Spinach Software & Consulting LLC. All rights reserved.

-->

<html>

<head>

<link rel="stylesheet" href="js/jquery-ui-1.8.16/themes/base/jquery-ui.css" type="text/css" />

<script src="js/jquery-ui-1.8.16/jquery-1.6.2.js"></script>

<script type="text/javascript" src="js/jquery-ui-1.8.16/ui/jquery-ui.js"></script>

<script type="text/javascript" src="js/jquery-ui-1.8.16/ui/jquery.ui.core.js"></script>

<script type="text/javascript" src="js/jquery-ui-1.8.16/ui/jquery.ui.position.js"></script>

<script type="text/javascript" src="js/jquery-ui-1.8.16/ui/jquery.ui.widget.js"></script>

</head>

<script>

$(function() {

$( "#city" ).autocomplete({

source: function( request, response ) {

$.ajax({

url: "/ajaxcitySearchGeneral",

dataType: "json",

data: {

maxRows: 6,

startsWith: request.term

},

success: function( data ) {

response( $.map( data.zipcodes, function( item ) {

return {

label: item.cityName + ", " +item.zipcodeId + ", " + item.state,

value: item.cityName

}

}));

}

});

},

minLength: 1,

open: function() {

$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );

},

close: function() {

$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );

}

});

});

</script>

 

<div class="demo">

<div class="ui-widget">

<label for="city">Search City: </label>

<input id="city" />

</div>

</div>

</html>

3.  Auto complete with Data from Remote REST service

This is by far the most useful one since most of the time the REST service will be on a separate server e.g. in this one we will use a REST service located at http://ziplocator.cloudfoundry.com/rest/startsWithCity/ with two query parameters “startsWith” and “maxRows”  so lets say if we are looking for a city that starts with letter “min” then here is the url http://ziplocator.cloudfoundry.com/rest/startsWithCity/?startsWith=min&maxRows=5

Now all we have to do is consume this json result in our html. This is how it looks


<!--

! Spinach Software & Consulting LLC

! Copyright 2011 by Spinach Software & Consulting LLC. All rights reserved.

-->

<html>

<head>

<link rel="stylesheet" href="js/jquery-ui-1.8.16/themes/base/jquery-ui.css" type="text/css" />

<script src="js/jquery-ui-1.8.16/jquery-1.6.2.js"></script>

<script type="text/javascript" src="js/jquery-ui-1.8.16/ui/jquery-ui.js"></script>

<script type="text/javascript" src="js/jquery-ui-1.8.16/ui/jquery.ui.core.js"></script>

<script type="text/javascript" src="js/jquery-ui-1.8.16/ui/jquery.ui.position.js"></script>

<script type="text/javascript" src="js/jquery-ui-1.8.16/ui/jquery.ui.widget.js"></script>

</head>

 

<script>

$(function() {

$( "#city" ).autocomplete({

source: function( request, response ) {

$.ajax({

url: "http://ziplocator.cloudfoundry.com/rest/startsWithCity/",

dataType: "json",

 

data: {

maxRows: 10,

startsWith: request.term

},

success: function( data ) {

response( $.map( data.zipcodes, function( item ) {

 

return {

label: item.cityName + ", " +item.zipcodeId + ", " + item.state,

value: item.cityName

}

}));

}

});

},

minLength: 1,

open: function() {

$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );

},

close: function() {

$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );

}

});

});

</script>

 

<div class="demo">

<div class="ui-widget">

<label for="city">Search City: </label>

<input id="city" />

</div>

</div>

</html>

See the  complete end to end demo of this in cloud foundry here http://autocomplete.cloudfoundry.com/ajaxToRemoteREST.html 

Conculsion

Most important concept is to see that JQuery library and JQuery-UI are two separate things. JQuery-UI is specifically made for user interface related stuff and is built on top of JQuery. Latest version of JQuery-UI can be downloaded from http://jqueryui.com/

Also see a complete demo of this functionality at cloud foundry http://autocomplete.cloudfoundry.com/

Note: For the purpose of auto complete we do not need all the libraries that came by default with JQery-UI, so I trimmed it down to what is needed. Please see the complete source code in the end.

Download all code

Get on the cloud!

Cloud computing is becoming popular and a lot of companies already started deploying their applications on cloud or have plans on doing so in near future. Having your services on cloud allows for greater scalability, improved performance and ease of development. In this article we will introduce some of the basic concepts.

You can have your own private cloud or can use a public one by many of the vendors such as Amazon, Eucalyptus etc. The one we use in this article is from VMware called Cloudfoundry and is a beta product so is free to try on. This cloud supports Java, Grails and .NET based frameworks. For more reference look at blog.cloudfoundry.com 

We will start with creating an account and deploying a sample java based application on it.

  1. Signup yourself at cloud foundry signup (EDIT: This process is much faster in 2013 as earlier it used to take 2-3 weeks)
  2. Download Spring based IDE (STS) or Eclipse for development and connecting to Cloud.
  3. Integrate STS with Cloud Foundry Extension by opening up STS–>Help–>Dashboard and then going to Extensions tab. Search for Cloud Foundry and install it
  4. Add a New Server in STS and select VMware–> Cloud Foundry
  5. Now supply your login credentials here which you received from step 1 and validate account.
  6. Almost done! This is how your server will look like. Now just add any web project to it and enjoy the benefits of cloud.

Here is a sample web project that you can push to the cloud https://github.com/spinachsoftware/HelloCloudWebApp.

Here is the URL to check for an already deployed web app http://hellocloudwebapp.cloudfoundry.com

Stay with us to see more advance versions for web apps deployed on cloud which will use resources such as messaging, database and so on. More is coming….

Introduction to RESTful services in few simple steps

REST (Representational state transferhas become very popular and in fact it was always there but we just didn’t see it until Roy Fielding presented his doctoral dissertation. It gives us the power of distributed computing without the hassle of redefining the protocol to access those distributed objects.

The current peers of REST can be EJB and the so called Service oriented architectures which again requires their own custom protocols such as RMI or SOAP. Unlike REST works with HTTP protocol and hence leverage whats already there. We can define distributed objects using REST and access those object using simple HTTP protocols such as GET, PUT, DELETE etc.

Furthermore, the REST based server side object can be deployed in a simple web container which makes it easy enough to use with Spring and a no EJB approach. Think about this that if you develop a RESTful service then it will be useful for a mobile view as well as a desktop because the protocol to access it is light-weight HTTP

Enough of theory… now lets just build something which will be useful in daily life. An example of a very common service is address validation. We all need to verify whether the zipcode entered by the user is valid. I understand that google or some other vendor will already have such a service but for now lets just build that on a smaller scale.

Simple Zip Locator REST App

To build a REST app we need a provider that can run the distributed object in the Servlet container. For that we are using Apache CXF. This will be a no database and in-memory example for simplicity.

  1. First we need something to hold zip code information. Lets name it ZipcodeDetails 
@XmlRootElement
public class ZipcodeDetails implements Serializable
{
private String zipcodeId;
private String cityName;
private String state;
}

2.  The service name will be FindZipcodeService. Please note that we are defining that the results can be consumed as XML or JSON using @Produces annotation. We can define more Media types if needed. Also the @Path annotation is what leads us to these methods. Again if you are familiar with Spring MVC then it should be straight forward.

@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public class FindZipcodeService
{
@GET
@Path("findbyzipcode/{zipcode}")
public ZipcodeDetails findzipcodeDetails(@PathParam("zipcode") String zipcode) {..}
}

3.  This is how we can define the REST service using Apache CXF in applicationContext,.xml

<bean class="org.apache.cxf.jaxrs.provider.XMLBeansElementProvider" id="xmlBeanProvider">
<bean class="org.apache.cxf.jaxrs.provider.XMLBeansJSONProvider" id="jsonProvider">       <jaxrs:server address="/" id="zipcodeService">
<jaxrs:servicebeans>
<ref bean="findZipcodeService">
</ref></jaxrs:servicebeans>
<jaxrs:providers>
<ref bean="xmlBeanProvider">
<ref bean="jsonProvider">
</ref></ref></jaxrs:providers>
</jaxrs:server>
</bean>
</bean>

4.  Main project dependencies are Apache CXF and JaxRS

<dependency>
<groupid>org.apache.cxf</groupid>
<artifactid>cxf-rt-transports-http</artifactid>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupid>org.apache.cxf</groupid>
<artifactid>cxf-rt-frontend-jaxrs</artifactid>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupid>javax.ws.rs</groupid>
<artifactid>jsr311-api</artifactid>
<version>1.1</version>
</dependency>

5.  Finally your Web XML needs to define the Dispatcher servlet to handle REST related request as shown.

<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

6.  When you deploy this on Jetty/Tomcat or any Server give the context path to “/”. This way the URL will be formed as http://localhost:8080/rest/findbyzipcode/55401

Conclusion

This application can be deployed on cloud. see instructions here. For demo purpose we have deployed a full blown ziplocator service to cloud foundry with all US based zip codes. http://ziplocator.cloudfoundry.com e.g. http://ziplocator.cloudfoundry.com/rest/findbyzipcode/55426 as you can see that we can embed this URL in a jQuery to do validation or may be do auto-complete for city and state.

Downloads (complete source code)

How to mock static and final methods while writing JUnit?

Many people will point out that if you are mocking static or final method in your Junit that means something is not correct with the way source code is written and I totally concur with that. However sometimes you may end up in a situation where you have to mock static or final methods e.g. most of the vendor specific framework methods are declared as final.

The solution comes with PowerMock which is an extension to Mockito. PowerMock is the elixir for most of your advanced mocking/Junit needs. It comes with a cost of additional setting overhead though and can be intimidating at first. Please see the example below.

Problem Scenario:
Here is how the source code look:

public class MyClassA
{
public static long timeTaken(long starTime)
{
// want to mock this currentTime() method call.
return currentTime()+days;
}
public static long currentTime()
{
return System.currentTimeMillis();
}
}

Solution:
Lets say we are testing timeTaken() method and would like to mock currentTime()method then here is how you could do that using PowerMock

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClassA.class)
public class MyClassATest
{
@Test
public void timeTaken()
{
long whateveryouwant = 1L;
PowerMockito.spy(MyClassA.class);
PowerMockito.when(MyClassA.currentTime()).thenReturn(whateveryouwant);
long xxx = MyClassA.timeTaken(..);
assertEquals(...);
}

Here is what you need to have in your Pom if using Maven. (Please look the latest revision in http://repo2.maven.org/ )

    <dependency>
      <groupid>org.powermock</groupid>
      <artifactid>powermock-module-junit4</artifactid>
      <version>1.4.6</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupid>org.powermock</groupid>
      <artifactid>powermock-api-mockito</artifactid>
      <version>1.4.6</version>
      <scope>test</scope>
    </dependency>