Thursday, 12 December 2013

Multiple exception handling in a single catch block

The earlier versions of java had multiple catch block one after the other where we can handle several exceptions in one try and multiple catch block as follows:

try
{
//do someting;
}
catch(Exception1 e)
{
handleException(e)
}
catch(SQLException e)
{
handleException(e)
}

Java 7 has introduced the new feature of adding multiple exception objects in one catch block as below.

try
{
//do someting;
}
catch(Exception1, Exception2 e)
{
handleException(e)
}

This feature thereby reduces the overhead on the developer .

Tuesday, 10 December 2013

"String" datatypes in SWITCH : .

Switch statements are commonly applied in most of the programming languages and in java too . Switch statement accepts two datatypes , char and int till java 6. But now java 7 has added a feature where switch statement can accept string values too . It matches the string with the cases and executes the code. Please see the following program for more understanding .

String s = ….;
switch(s)
{
case "subbu": 
System.err.println("It is subbu man!");
break;
case "ryan": 
System.err.println("It is ryan man!");
 break;
case "john":
default: 
System.err.println("Default");
break;
}

Sunday, 8 December 2013

Infinity Logic in java Without Exception.

It is normal when we divide a integer number by 0 we get arithmetic exception in java . But you will be surprised to see that the following program does not throw exception rather prints Infinity .

Please have a look at the following code and the corresponding output.

public class TestInfinity {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
float f = 10.0f;
float g = 0.0f;
float z = f/g;
System.out.println(z);
}

}


Saturday, 7 December 2013

Location finder in Android

This article deals with accessing the location of the user using location providers, we need to set permissions in the android manifest file.
<manifest ... >
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
   <uses-permission android:name="android.permission. ACCESS_COARSE_LOCATION" />
   <uses-permission android:name="android.permission.INTERNET" />
</manifest>

ACCESS_COARSE_LOCATION is used when we use network location provider for our Android app. But, ACCESS_FINE_LOCATION is providing permission for both providers. INTERNET permission is must for the use of network provider.

package com;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;

import android.util.Log;

public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
@Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}

@Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}

@Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}

XML files for layout and android manifest are as shown below

<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"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.javapapers.android.geolocationfinder"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17"        />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppBaseTheme" >
        <activity
            android:name="com.javapapers.android.geolocationfinder.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Friday, 6 December 2013

Sample piece of code to handle connections in thread .

A Runnable class can be created to house the procedure for polling the database and creating the alerts. The following PGM1 shows that Runnable that will be used to create the managed thread. In this example, a class named ReservationAlerter. That class can then be made into a thread by calling a ManagedThreadFactory’s newThread() method, as shown in PGM2.
PGM1:
public class ReservationAlerter implements Runnable {

    @Override
    public void run() {

        while (!Thread.interrupted()) {
            reviewReservations();
            try {
                Thread.sleep(100000);
            } catch (InterruptedException ex) {
                // Log error
            }
        }
    }

    public Collection reviewReservations() {

        Connection conn = null;
        Properties connectionProps = new Properties();
        connectionProps.put("user", "user");
        connectionProps.put("password", "password");
        Collection reservations = null;
        try {
            // Obtain connection and retrieve reservations
            conn = DriverManager.getConnection(
                "jdbc:derby:acme;create=false",
                connectionProps);
            // Use the connection to query the database for reservations
        } catch (SQLException ex){
            System.out.println("Exception: " + ex);
        } finally {
            if (conn != null){
                try {
                    conn.close();
                } catch (SQLException ex) {
                    // Log error
                }
            }
        }
        return reservations;
    }

}

PGM2:
ReservationAlerter alerter = new ReservationAlerter();

alerterThread = threadFactory.newThread(alerter);
alerterThread.start();

PGM3 shows the complete code for obtaining a reference to the ManagedThreadFactory via @Resource injection, creating the new Thread instance, and then starting it.

PGM3:

public class AcmeAlerterContextListener implements ServletContextListener {
    Thread alerterThread = null;
    @Resource(name="concurrent/__defaultManagedThreadFactory")
    ManagedThreadFactory threadFactory;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ReservationAlerter alerter = new ReservationAlerter();
        alerterThread = threadFactory.newThread(alerter);
        alerterThread.start();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        if(alerterThread!=null){
            alerterThread.interrupt();
        }
    }
   
   
}

l y a g �� ะด 0pt;margin-right:.5in;margin-bottom: 6.0pt;margin-left:0in;line-height:normal;mso-pagination:none;mso-layout-grid-align: none;text-autospace:none'>        Properties connectionProps = new Properties();

        connectionProps.put("user", "user");
        connectionProps.put("password", "password");
        Collection reservations = null;
        try {
            // Obtain connection and retrieve reservations
            conn = DriverManager.getConnection(
                "jdbc:derby:acme;create=false",
                connectionProps);
            // Use the connection to query the database for reservations
        } catch (SQLException ex){
            System.out.println("Exception: " + ex);
        } finally {
            if (conn != null){
                try {
                    conn.close();
                } catch (SQLException ex) {
                    // Log error
                }
            }
        }
        return reservations;
    }
}

Function as Argument in Lambda


package com;

The following is an example of how method is implemented by passing the functionitself as an argument.
We have got couple of implementations for the circle interface and they two different operations with respect to context. Those anonymous class implementations itself are passed as argument to another generic method, thus achieving a level of generic function.
public class LambdaFunctionArgument {

  interface Circle {
    double get(double radius);
  }

  public double circleOperation(double radius, Circle c) {
    return c.get(radius);
  }

  public static void main(String args[]){
    LambdaFunctionArgument reference = new LambdaFunctionArgument();
    Circle circleArea = (r) -> Math.PI * r * r;
    Circle circleCircumference = (r) -> 2 * Math.PI * r;
    
    double area = reference.circleOperation(10, circleArea);
    double circumference = reference.circleOperation(10, circleCircumference);
  
    System.out.println("Area: "+area+" . Circumference: "+circumference);
  }
}

Sunday, 1 December 2013

Crack your JVM

Wanna crash you JVM ? Just try the following code but only at your own risk . Ensure that you have tools.jar in your classpath both at compile time and run time . This not only crashes the   just the JVM it was deployed to, but also the virtual and/or physical machine underneath.

public class Crash {
  public static void main(String... args) throws Exception {
    com.sun.tools.attach.VirtualMachine.attach("-1");
  }

}

We are trying to attach ourselves to an already existing Java process specifying -1 as the process id. Instead of failing nicely you get something similar to the blue screen of death.