Create new maven project from scratch

1. Create a new project
$ mvn archetype:generate -DgroupId=com.xyz.myapp -DartifactId=MyApp -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
$ cd MyApp

2. To Build Package:
$ mvn package
//this will create target/MyApp-1.0-SNAPSHOT.jar

3. To Execute
$ java -cp target/MyApp-1.0-SNAPSHOT.jar com.xyz.myapp

# Adding dependency to your project
Let say you wanted to add “json-simple” to your project:
add inside in the pom.xml file:

<dependency>
 <groupId>com.googlecode.json-simple</groupId>
 <artifactId>json-simple</artifactId>
 <version>1.1</version>
</dependency>

– Now to execute a package with dependency you will have to include the path to the jar (I think there is a way to do it with pom.xml, but I don’t know this yet)
– This could complicated if you have multiple dependencies
– And also need to make sure you have the pkgs in the system where you want to deploy your code
– Solution: Create fat jar (a jar that includes all dependent jars, side effect: output file is bigger and takes longer to run ‘mvn package’ command)
– To create fat jar add this to your pom.xml inside :

<build>
 <plugins>
  <plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-assembly-plugin</artifactId>
   <version>2.2.1</version>
   <configuration>
    <descriptorRefs>
     <descriptorRef>jar-with-dependencies</descriptorRef>
    </descriptorRefs>
   </configuration>
   <executions>
    <execution>
     <id>assemble-all</id>
     <phase>package</phase>
     <goals>
      <goal>single</goal>
     </goals>
    </execution>
   </executions>
  </plugin>
 </plugins>
</build>

Loop through dictionary/map/array

#PHP
foreach($map as $k => $v){
echo “key: {$k}, value:{$v}”;
}

#objective-c
for(id key in myDict){
NSLog(@”key:%@, value:%@”, key, [myDict objectForKey:key]);
}

#python
for key in myDict.iterkeys():
print (“key:{0}, value:{0}”.format(key, myDict[key])

#java
for (String key : map.keySet()) {
System.out.println(“key: ” + key + “, value:” + map.get(key));
}

iPhone – Protocol & Delegate Implementation

CustomHttpRequest.h

@protocol CustomHTTPRequestDelegate

@required
-(void) receivedDataForURL : (NSString *) reqUrl resultData: (NSDictionary *) result_;

@end
@property (retain) id delegate;

CustomHttpRequest.m
[[self delegate] receivedDataForURL:urlStr resultData:dic];

—–

.h
@interface VCAtm : UIViewController {
}

.m
CustomHttpRequest *httpReq = [[CustomHttpRequest alloc] initWithURL:url];
httpReq.delegate = self;

#pragma mark –
#pragma mark CustomHttpRequest Delegate

-(void) receivedDataForURL : (NSString *) reqUrl resultData:(NSDictionary *) result_{
NSLog(@”reqURL %@”, reqUrl);
NSLog(@”result data %@”, result_);

//show all values
for (id key in result_) {
id value = [result_ objectForKey:key];
NSString *keyAsString = (NSString *)key;
NSString *valueAsString = (NSString *)value;

NSLog(@”key: %@”, keyAsString);
NSLog(@”value: %@”, valueAsString);
}

NSArray *results = [result_ objectForKey:@”results”];
for (NSDictionary *result in results) {
NSString *name = [result objectForKey:@”name”];
[nameList addObject:name];
NSLog(@”Name : %@”, name);
}

atmTableView.delegate = self;
atmTableView.dataSource = self;
[atmTableView reloadData];

}

iPhone – Convert NSMutableData to ios JSON object and parse the data

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[self.responseData length];
//convert to json
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:nil];

//show all values
for (id key in dic) {
id value = [dic objectForKey:key];
NSString *keyAsString = (NSString *)key;
NSString *valueAsString = (NSString *)value;

NSLog(@"key: %@", keyAsString);
NSLog(@"value: %@", valueAsString);
}

NSArray *results = [dic objectForKey:@"results"];
for (NSDictionary *result in results) {
NSString *name = [result objectForKey:@"name"];

[nameList addObject:name];
NSLog(@"Name : %@", name);
}

Android Maps

The Location-based services in android offers two APIs
1. Mapping
2. Location-based

Here we’ll talk about the first API i.e mapping
– The mapping package is com.google.android.maps

Things needed for android map
1. Internet connectivity – Since mapping APIs often reach across the internet to invoke services from Google servers.
– In manifest file add following line outside the application

<uses-permission android:name=”android.permission.INTERNET” />

2. To use google maps APIs services, you must agree Google Terms and condition, the terms will be presented to you when you sign up for a Map API Key.

Steps:
1. First Obtain a Maps API key from Google
– Find where your keychain is
* Go to Eclipse -> Preference -> Android -> Build
* see Defalt debug keystone – Here you see the keystore path
e.g: /Users/tech/.android/debug.keystore
* Go to the keystore location
* now run below command
$ keytool -list -keystore debug.keystore

* Now, paste your certificate’s MD5 fingerprint in the appropriate field on this Google site:
http://code.google.com/android/maps-api-signup.html

3. Add the following lines in manifest file within the application tag

<application>

<uses-library android:name=”com.google.android.maps”/>

</application>

4. extends MapActivity class

e.g

public class ActivityMap extends MapActivity

– MapActivity implements the following method.

@Override
protected boolean isRouteDisplayed() {
return false;
}

5. Understanding MapView and MapActivity
* Mapping technology in Android relies on the MapView UI control and an extension of android.app.Activity called MapActivity.
* The MapView and MapActivity classes take care of the heavy lifting when it comes to displaying and manipulation a map in Android.
* MapView need to instantiate it within a MapActivity, when instantiation a MapView, we need to supply the Maps API key
E.g:
If we instantiate a MapView using an XML layout, we need to set the android:apiKey property

<?xml version=”1.0″ encoding=”utf-8″?>

<com.google.android.maps.MapView

xmlns:android=”http://schemas.android.com/apk/res/android&#8221;

android:id=”@+id/mapview”

android:layout_width=”fill_parent”

android:layout_height=”fill_parent”

android:clickable=”true”

android:apiKey=”Your Map Key”

/>

Android – Location Manger

The LocationManager Service is offered by the android.location package. There are three types of location providers:
1. GPS
2. Network – Use cell-phone towers or Wi-Fi networks
3. The Passive provider and it is like a location update sniffer

Here is the example:

public class MyApplication extends Application implements LocationListener {

private static MyApplication instance;

public void onCreate() {
  super.onCreate();
  instance = this;
  LocationManager locMgr = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
  locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, this);

}

public static Context getContext() {
  return instance;
}

public void onLocationChanged(Location location) {
   Log.i("Debug"," OnLocation Changed"+ location.getLatitude() + " " + location.getLongitude());

}

public void onProviderDisabled(String provider) {

}

public void onProviderEnabled(String provider) {

}

public void onStatusChanged(String provider, int status, Bundle extras) {

}

Singleton Design Pattern in Java

Singleton in Java

Singleton is the design pattern that instantiate the class to one object.

Here is the example in java

public class JavaProject {

	public static void main(String args[]){

		System.out.println("IN main class");

		MYClass a = MYClass.mySingleFactory();
		MYClass b = MYClass.mySingleFactory();

		MYClass c = new MYClass(); //Avoid doing this if the class is to be used as Singleton, because this operation returns a new instance of MyClass

		a.setI(1);
		b.setI(2);
		c.setI(3);

		a.printI();
		b.printI();
		c.printI();
		a.printI();
		MYClass.mySingleFactory().printI(); //another way to call the singleton obj
	}
}

public class MYClass {

	private int i;
	static MYClass inst;

	public static MYClass mySingleFactory(){
		if (inst == null){
			inst = new MYClass();
		}
		return inst;
	}

	public void SingletonTest() {

		System.out.println("SingletonTest constructor called");

	}

	public void printI(){
		System.out.println("Value of I is: " + i);
	}

	public void setI(int i_){
		i = i_;
	}
}

Output:
IN main class
Value of I is: 2
Value of I is: 2
Value of I is: 2
Value of I is: 3
Value of I is: 2