Indian Dahihandi game clinches seventh spot on Google Play!

Hello everyone!

It’s yet another proud moment for Indian Android developer Manas Gajare as his new Dahihandi Knock Down game now holds the seventh spot under Top Free in Casual games category on the Google Play Store. The game as it’s name suggests is based on the Indian festival Gokulashtami (popularly known as Dahi Handi) and includes knocking down Dahihandi’s using a slingshot and a few rocks!

top_free_in_casual

Here is a short description along with the features of the game,

To complete a level you have to knock down all dahihandis using your precision skills and logic.

Features

1. 30 engaging levels. (More to come in the next update)
2. Accurate physics
3. Energizing and very apt music.

dahihandi_knock_down_game

The game levels keep getting increasingly difficult. One of the tricks involve throwing the rock on the ground so that it will bounce back. On the whole, the game is a complete entertainer and keeps you hooked on every time you start playing. Here’s wishing the entire Zabuza Labs team success in future, hoping they continue to bring us many more such games!

If you haven’t yet downloaded the game, please do so from over here. Enjoy!

An event to remember!

On a lazy Sunday morning most of us would just wake up, have a cup of coffee and read the newspaper to see what’s new. How many of you would be ready to face a quiz? A quiz that would test your skills in Engineering across all it’s disciplines. An inter-corporate event that would involve participants from all across India competing in a battle of wits. It’s hard to believe right? Well, not really! All thanks to the Times Ascent group for making this possible.

The grand finale of the second edition of the Ascent Engineering Mastermind kicked off today at St. Andrews College (Bandra,Mumbai). It was the first time I was attending an inter corporate event. Unfortunately, I could not participate since the registration process was closed. I decided to wait back as an audience and watch the quiz unfold and luckily that turned out to be a blessing in disguise. After a delay of around 25 minutes or so, the preliminary rounds began and participants were given a set of 20 questions whose answers needed to be written on the sheet provided.

I could orally answer 11 out of those but then the questions were really good with a handful based on core engineering disciplines. The preliminary rounds were over in no time and only the top 4 teams would qualify for the next round as far as the Mumbai zone was concerned. The other zonal finalists from Pune, Delhi and Bangalore were also present and would join in the action once the finalist of the Mumbai zone was decided.

TCS Mumbai was named the finalist of the Mumbai zone after a gruelling four rounds and now the grand finale would begin! To add to the fun there were spot prizes too with a few questions being thrown to the audience. I won a goodie for answering one of them and that certainly made by day! 🙂

On the whole, the event was a true learning extravaganza. From Physics and Mathematics to Civil and Electrical, the event covered all facets of Engineering. GenPact Ltd won the coveted Ascent Engineering Mastermind prize with TCS Mumbai being declared as runners up. It was one of the most memorable events I had attended. Looking forward to participate next year! 🙂

Here are a few moments of the event that I captured!

IMG040

IMG041

IMG043

IMG044

IMG045

IMG046

Convert Java jar file to exe using JSmooth

Hi everyone!

JSmooth is a popular executable wrapper for Java that helps to create native Windows launchers (.exe) for our Java applications. The latest version of JSmooth can be downloaded from over here.

In this post, we will learn how to convert our existing Java console application to an .exe file. First, you need to export the Java application as a .jar file. If your using Eclipse, right click your Java Project –> Export –> Jar file.

export_to_jar

Once you have downloaded JSmooth, open the application.

jsmooth_1

Specify the skeleton of the executable application. In my case I want to create a Console wrapper that will run on the command prompt console.

jsmooth_skeleton

Give the full path to the .jar file by selecting the option “Use an embedded jar”. Go to Application tab and set the Main Class file. Put the same name which you had used in Eclipse project as Main Class.

jsmooth_2

Go to the Executable tab and set Executable Binary file path. Mention the full path with name of the .exe file that you want to be created. One can also provide an icon for the executable file.

jsmooth_3

Now, go to the JVM Selection tab. Specify the minimum and maximum JVM versions required to run your application.

jsmooth_4

Finally, go to the Project menu and compile the file. If there are no compilation errors then you should see the .exe file generated in the specified directory.

jsmooth_5

jsmooth_6

output

This completes this simple and effective Java tip. Hope it helps! 🙂

Happy birthday Threads Of Life!

Yesterday, Threads Of Life turned 1 and I would like to thank all the visitors, subscribers and Facebook followers for their continued support right from the beginning of this year long journey.

As they say, “It’s easier said than done!”. The website wouldn’t have been possible without the encouragement of my friends and well-wishers. A big thank you to my parents for always believing in me. Love you Mom and Dad! 🙂

There were times when I was not able to post the topics that some of the readers had sent a request for. Henceforth, I will try my best to include them and provide the readers with quality content. Once again, thank you all and here’s wishing the blog a very happy birthday! 🙂

threads_of_life_birthday

Demystifying agents in Oracle Data Integrator!

Hello folks!

A little background

Agents are basically services written in Java running on a specific TCP/IP port that carry out the execution of Interfaces, Packages etc. In previous versions of ODI namely ODI 10g one only had the standalone agents at his disposal. Ever since ODI 11g was introduced, the concept of Java EE agents came into the picture. Overall, both these agents are (almost) the same piece of code. The differences in them is what we will learn ahead!

The tale of two Agents

A Standalone agent will run on top of a Java machine or any machine with a JVM implementation. It is easier to deploy and we can create multiple such agents. The question that arises is how many would you keep on creating? In an environment that demands scalability, standalone agents would eventually fail. In such situations we use Java EE agents. Java EE agents are deployed as a Weblogic server application. Unlike standalone agents, they utilize the clustering and connection pooling features of the Weblogic server. They are a bit complex to deploy but promise to offer enterprise wide scalability. Standalone agents use the built-in ODI load balancing feature and do not support clustering and connection pooling.

Scenario

Let’s say you want to run an ODI Scenario that populates hundreds of records from the source table to the target table. You create two or three Standalone agents running on different ports (load balanced) that carry out the execution of the scenario. Now, the agent always first connects to the master repository, obtains the connection information to the work repository, connects to the work repository and then finally executes the Scenario. Each time the standalone agent tries to connect, it creates a new connection request to the database. As opening/closing of database is an expensive process, at some point in time there might exist a connection overhead resulting in slow down of the operation. A better option then would be to use a Java EE agent that is by default highly scalable, available and supports connection pooling.

odi_agents

What can we conclude?

Finally, it is the user that has to decide which type of Agent is required. It is quite possible for both the agents to exist simultaneously in the same ODI architecture. The main difference is how you install them, in WLS or on top of JVM.

Source: What’s new in ODI 11g – Part 1

Getting Started with Cognos!

Hello!

Cognos is IBM’s very own BI, strategy development software used for better decision making. It now also includes interesting features such as Mobile BI for people on the go, Scorecards (metrics for monitoring performance), statistics, real time monitoring etc.

The latest version 10.2 of Cognos Insight which is a rather Personal solution aims to improve usability. flexibility and robustness. It showcases significant changes in graphics and visual appeal. This blog post provides more information.

Through this post, we will see how to work on an Excel spreadsheet in Cognos!

Pre-requisites: Cognos Insight 10.2, Windows 7 (64 bit OS)

Launch the Cognos application from (Start –> Programs –> IBM Cognos Insight) and you should see the following window!

home_screen

Now, drag an Excel spreadsheet into the workspace.

dragging_excel_sheet

Import another Excel sheet and then view the charts for the same. One can modify values for the columns as well as change the design type (bar graphs, pie charts etc) for better decision making.

importing_data

design_type

Excel based reporting is used when you have the data stored in files. One can also add a relational database source containing structured data for reporting purposes. We will cover about the same in the upcoming tutorials!

Tutorial #57: Connect to LinkedIn using Java and OAuth

Hello everyone!

Today, LinkedIn has become a very popular social networking website among professional people. The LinkedIn API’s can be used to connect and retreive the necessary user information. For this purpose, we have an existing Java wrapper called LinkedIn-J that helps us to post updates to the website. Along with that, we would be using the signpost-core API to sign HTTP requests using a given OAuth token and secret.

Using both these API’s we would be creating a Java application that would help us connect to LinkedIn!

Pre-requisites: Eclipse IDE

Step 1: Obtain LinkedIn API key

Before you start creating the Java application, you need to obtain the API key. Go to the LinkedIn developer’s page and add a new Application. Once you have added it, you will get an API key for the same that will be used in the Java application. Follow this link for more information.

Step 2: Create Java Project

Create a new Console application in Java named ConnectToLinked. Create a new class as follows!

Make sure you add the LinkedIn-J and signpost-core jar files. LinkedIn-J can be downloaded from over here and signpost-core can be downloaded from this location.

TestLink.java

package com.example;

import java.util.Scanner;
import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInAccessToken;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;

public class TestLink 
{

	private static Scanner s;

	public static void main(String[] args) 
	{

		String linkedinKey = "";    //add your LinkedIn key
		String linkedinSecret = ""; //add your LinkedIn Secret
		
		LinkedInOAuthService oauthService;
		LinkedInRequestToken requestToken;
		  
		System.out.println("Fetching request token from LinkedIn...");  
		String authUrl = null;
		String authToken,authTokenSecret;
		
		oauthService= LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(linkedinKey,linkedinSecret); 
		requestToken= oauthService.getOAuthRequestToken();
	    authToken= requestToken.getToken();  
	    authTokenSecret = requestToken.getTokenSecret();  
	   
	    System.out.println("Request token " +requestToken);
	    System.out.println("Auth token" +authToken);
	    System.out.println("Auth token secret" +authTokenSecret);
	    
		authUrl = requestToken.getAuthorizationUrl();

		System.out.println("Copy below link in web browser to authorize. Copy the PIN obtained\n" + authUrl);
		System.out.println("Enter the PIN code:");
		
		String pin;
		
		try 
		    {
		
                s = new Scanner(System.in);
		        pin = s.next();  
		        System.out.println("Fetching access token from LinkedIn...");
		
		        LinkedInAccessToken accessToken =  oauthService.getOAuthAccessToken(requestToken, pin);
	            System.out.println("Access token : " +  accessToken.getToken());
	            System.out.println("Token secret : " +  accessToken.getTokenSecret());
	            final LinkedInApiClientFactory factory =  LinkedInApiClientFactory.newInstance(linkedinKey,linkedinSecret);
	            final LinkedInApiClient client =  factory.createLinkedInApiClient(accessToken);
	   
                //posting status to profile
	            client.updateCurrentStatus("LinkedIN API is cool!");
			
            }

		finally
		{
			System.out.println("Updated status!");
		}
	}
}

Save and run the Java application. If everything runs fine, you should see the new status on your LinkedIn profile page! 🙂

linkedIn_status

Understanding execution plan and cost in Oracle

Hello everyone!

In Oracle an execution plan is created internally every time we fire an SQL query on the database. The plan thus created depends upon the type of query optimizer used in your Oracle database. For example, Oracle 10g by default uses the CBO (cost based optimizer) that generated the plan by computing the table statistics. On the other hand we have the RBO (rule based optimizer) that uses a set of pre-defined rules to create the plan.

How do I get the execution plan?

In Oracle it is possible to generate the execution plan for any SQL query. Using *SQL Plus, one can run the set autotrace command and then execute your SQL statement to see the execution plan as follows!

SQL> set autotrace traceonly explain;

SQL> select EmpName from Employee where EmpId=103;

Execution Plan
----------------------------------------------------------
Plan hash value: 3075387830

--------------------------------------------------------------------------------

------------

| Id  | Operation                   | Name         | Rows  | Bytes | Cost (%CPU)

| Time     |

--------------------------------------------------------------------------------

------------

|   0 | SELECT STATEMENT            |              |     1 |     9 |     1   (0)

| 00:00:01 |

|   1 |  TABLE ACCESS BY INDEX ROWID| EMPLOYEE     |     1 |     9 |     1   (0)

| 00:00:01 |

|*  2 |   INDEX UNIQUE SCAN         | SYS_C0013049 |     1 |       |     0   (0)

| 00:00:01 |

--------------------------------------------------------------------------------

------------


Predicate Information (identified by operation id):
---------------------------------------------------

   2 - access("EMPID"=103)

As seen above the execution plan is obtained for the query. Another way to obtain the execution plan is by using the EXPLAIN PLAN statement as follows!

SQL> analyze table Employee compute statistics;

Table analyzed.

SQL> explain plan for select EmpName from Employee where EmpId=103;

Explained.

SQL> select * from table(dbms_xplan.display);

PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------------

Plan hash value: 3075387830

--------------------------------------------------------------------------------

------------

| Id  | Operation                   | Name         | Rows  | Bytes | Cost (%CPU)

| Time     |

--------------------------------------------------------------------------------

------------


PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------------

|   0 | SELECT STATEMENT            |              |     1 |     9 |     1   (0)

| 00:00:01 |

|   1 |  TABLE ACCESS BY INDEX ROWID| EMPLOYEE     |     1 |     9 |     1   (0)

| 00:00:01 |

|*  2 |   INDEX UNIQUE SCAN         | SYS_C0013049 |     1 |       |     0   (0)

| 00:00:01 |

--------------------------------------------------------------------------------

------------

PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------------



Predicate Information (identified by operation id):
---------------------------------------------------

   2 - access("EMPID"=103)

14 rows selected.

How do I determine the execution cost?

If you observe closely, the plan generated includes a COST column. The COST column cannot be used to compare execution plans. Many people have the misconception that if a plan has a higher cost than another plan, it is worse. This isn’t true at all. This has been explained in detail over here.

The COST column is comparable provided you are evaluating two plans for the same SQL at the same time on the same database with the same parameter settings. It is possible to even write your own SQL script to generate execution plans. This post by Jonathan Lewis gives you a head start.

SQL> select cost from plan_table;

Execution Plan
----------------------------------------------------------
Plan hash value: 103984305

--------------------------------------------------------------------------------

-

| Id  | Operation         | Name        | Rows  | Bytes | Cost (%CPU)| Time
|

--------------------------------------------------------------------------------

-

|   0 | SELECT STATEMENT  |             |     3 |    39 |     2   (0)| 00:00:01
|

|   1 |  TABLE ACCESS FULL| PLAN_TABLE$ |     3 |    39 |     2   (0)| 00:00:01
|

--------------------------------------------------------------------------------

-

Note
-----
   - dynamic sampling used for this statement (level=2)

Hope this Oracle database tip helps you in some way! Stay tuned for more! 🙂

Tutorial #56: Beauty and the beast!

In the past, I have written tutorials on Oracle Data Integrator as well as Android. Today, I thought let’s bring these two technologies together to create a mobile application that will perform the same functions that are done normally through ODI Studio.

How about executing a Scenario from your mobile? or creating a Project, Model by entering it’s name and clicking on a Submit button. Sounds cool right? 🙂

Pre-requisites: Eclipse IDE, Android SDK , Oracle Data Integrator (build version 11.1.1.7.0), RESTEasy API

To start off, lets create our client (Android) application that will be displaying the user interface and handling the various event actions!

Open Eclipse IDE and create a new Android application project named AndroidRestEasyClient with package name com.example.

OdiActivity.java

package com.example;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class OdiActivity extends Activity
{

	private String connectUrl = "http://10.0.2.2:8081/RestEasyServices/connect";
	private String projectUrl= "http://10.0.2.2:8081/RestEasyServices/project/";
	private String scenarioUrl= "http://10.0.2.2:8081/RestEasyServices/scenario/";
	
	private String projname;
	private String result;
	private Spinner s;
	private String scenname;
	
	private EditText projectName;
	private Button sendMail,odiConnect,createProject,executeScen;
	private TextView tv;
	
	    @Override
        protected void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_odi);
     
            projectName= (EditText)findViewById(R.id.txtProject);
            tv= (TextView)findViewById(R.id.textView1);
        
            sendMail= (Button)findViewById(R.id.btn1);
            createProject=(Button)findViewById(R.id.createProject);
            executeScen=(Button)findViewById(R.id.executeScenario);
        
            s = (Spinner)findViewById(R.id.spinner1);
        
            odiConnect= (Button)findViewById(R.id.connect);
         
        
            odiConnect.setOnClickListener(new View.OnClickListener() 
            {
		       @Override
		         public void onClick(View v) 
		         {
			     // TODO Auto-generated method stub		
			     new connectODI().execute(connectUrl);
		         }
	        });
        
        
            sendMail.setOnClickListener(new View.OnClickListener() 
            {
	 	     @Override
		     public void onClick(View v) 
		     {
			  // TODO Auto-generated method stub 
			  Intent email = new Intent(Intent.ACTION_SEND);
			  email.putExtra(Intent.EXTRA_EMAIL, new String[]{"yourusername@gmail.com"});		  
		      email.putExtra(Intent.EXTRA_SUBJECT, "Test ODI using Android");
			  email.putExtra(Intent.EXTRA_TEXT, "A new project was created through Android. Please check ODI Studio");
			  email.setType("message/rfc822");
			  startActivity(Intent.createChooser(email, "Choose an Email client :"));		   
		     }
	        });
        
            createProject.setOnClickListener(new View.OnClickListener() 
              {	 		
		      @Override
		       public void onClick(View v) 
			     {
				   //TODO Auto-generated method stub
				   projname= projectName.getText().toString().trim();
				   
				   if(projname!=null)
				   {
					   
					   new projectODI().execute(projectUrl);
					   Toast.makeText(getApplicationContext(), "Done...........", Toast.LENGTH_LONG).show();
				  
				   }
				   
				   else
					   Toast.makeText(getApplicationContext(), "Please enter a Project name...!", Toast.LENGTH_LONG).show();		   
			    }
		     });
        
        
            executeScen.setOnClickListener(new View.OnClickListener() 
              {
		      @Override
			  public void onClick(View v) 
			    {
				// TODO Auto-generated method stub
				scenname= s.getSelectedItem().toString().trim();
				
				if(scenname!=null)
				   {
					   
					   new scenarioODI().execute(scenarioUrl);
					   Toast.makeText(getApplicationContext(), "Done...........", Toast.LENGTH_LONG).show();
				  
				   }
				   
			    }
		    });
                
    }// end Oncreate()
        

	 private class connectODI extends AsyncTask<String, Void, Void>
	    {
		 
	    	protected void onPreExecute() 
	    	{
                     Toast.makeText(getApplicationContext(), "Executing...", Toast.LENGTH_LONG).show();

	    	}

	    	
	    	protected void onPostExecute(Void unused)
	    	{

	    	Toast.makeText(getApplicationContext(), "Done...........", Toast.LENGTH_LONG).show();
	    	tv.setText("Status :" +result);
	    		
	    	}

			@Override
			protected Void doInBackground(String... params)
			{
				try
				{

			    	HttpClient httpclient = new DefaultHttpClient();		    	    	
         		    HttpPost httppost = new HttpPost(connectUrl);
			    	HttpResponse response =httpclient.execute(httppost);	    	
			    	HttpEntity resp_entity =response.getEntity();
			    	
			    	System.out.println("RESPONE : " +response.toString());
			    	
			    	result = EntityUtils.toString(resp_entity);
			    	
			    	System.out.println("RESULT : " +result);
	    	
			   }
			   catch(Exception e)
			   {
				Log.e("ERROR_OCCURRED", "Error in http connection "+e.toString());

			   }

			    	return null;
			}

			
	   }//end class
	
	
	 private class projectODI extends AsyncTask<String, Void, Void>
	    {
		 
	    	protected void onPreExecute() 
	    	{  
                      Toast.makeText(getApplicationContext(), "Executing...", Toast.LENGTH_LONG).show();
	    	}

	    	
	    	protected void onPostExecute(Void result)
	    	{
	    		System.out.println("Done.........");
	  
	    	}

			@Override
			protected Void doInBackground(String... params)
			{
				try
				{

			    	HttpClient httpclient = new DefaultHttpClient();    	
			    	System.out.println("Sending project name : "+projname);
				    
			    	projectUrl = "http://10.0.2.2:8081/RestEasyServices/project/" + projname;
			    	    
			    	HttpGet request = new HttpGet(projectUrl);
			    	
			    	List<NameValuePair> params2 = new ArrayList<NameValuePair>();
			    	params2.add(new BasicNameValuePair("param", projname));
			    	    	
			    	HttpResponse response =httpclient.execute(request); 	
			    	HttpEntity resp_entity =response.getEntity();
			    	
			    	System.out.println("RESPONSE : " +response.toString());
			    	
			    	String result = EntityUtils.toString(resp_entity);
			    	
			    	System.out.println("RESULT : " +result);

			    	if(result!=null)
			    		System.out.println("Project created succesfully...");
			    	
			    }
				catch(Exception e)
				{

			    	Log.e("ERROR_OCCURRED", "Error in http connection "+e.toString());

			    }

			    	return null;
			}

			
	  }//end class	 
	 
	 private class scenarioODI extends AsyncTask<String, Void, Void>
	    {
		 
	    	protected void onPreExecute() 
	    	{       
                   Toast.makeText(getApplicationContext(), "Executing...", Toast.LENGTH_LONG).show();
	    	}

	    	
	    	protected void onPostExecute(Void result)
	    	{
	    			System.out.println("Done.........");
	    
	    	}

			@Override
			protected Void doInBackground(String... params)
			{
				try
				{

			    	HttpClient httpclient = new DefaultHttpClient();
		    
			    	scenarioUrl = "http://10.0.2.2:8081/RestEasyServices/scenario/" + scenname;
			    				    
			    	HttpGet request = new HttpGet(scenarioUrl);
			    	
			    	List<NameValuePair> params2 = new ArrayList<NameValuePair>();
			    	params2.add(new BasicNameValuePair("param", scenname));
			    		    	
			    	HttpResponse response =httpclient.execute(request);		    	
			    	HttpEntity resp_entity =response.getEntity();
			    	
			    	System.out.println("RESPONSE : " +response.toString());
			    	
			    	String result = EntityUtils.toString(resp_entity);
			    	
			    	System.out.println("RESULT : " +result);

			    	if(result!=null)
			    		System.out.println("Scenario executed succesfully...");
			    	
			    }
				catch(Exception e)
				{

			    	Log.e("ERROR_OCCURRED", "Error in http connection "+e.toString());

			    }

			    	return null;
			}

	  }//end class
	
} //end Activity class


activity_odi.xml

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".OdiActivity">
 
    <TextView 
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    
    <Button 
        android:id="@+id/connect"
        android:layout_below="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/connect"/>
 
    <EditText 
        android:id="@+id/txtProject"
        android:layout_below="@+id/connect"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/createProject"/>
    
     <Button 
        android:id="@+id/createProject"
        android:layout_toRightOf="@+id/txtProject"
        android:layout_below="@+id/connect"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/project"/>
	    
    
     <EditText 
        android:id="@+id/txtModel"
        android:layout_below="@+id/txtProject"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/createModel"/>  
        
    <!--  Select Scenario -->    
    <Spinner 
        android:id="@+id/spinner1"
        android:layout_below="@+id/createModel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:entries="@array/scenario_list"
        android:prompt="@string/scenario"/>
    
     <Button 
        android:id="@+id/executeScenario"
        android:layout_below="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/execute"/>
	
     <Button 
        android:id="@+id/btn1"
        android:layout_below="@+id/executeScenario"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/mail"/>
   
</RelativeLayout>

AndroidManifest.xml

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

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
  
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="10"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name="com.example.OdiActivity"
            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>

Here we are done with the client side code. Don’t run the Android application yet! Let’s begin the server side implementation by creating a new Dynamic Web Project named RestEasyServices. Follow this tutorial for more information.

To connect to ODI, let’s create the ConnectService as follows!

ConnectService.java

package com.example;

import java.sql.SQLException;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import oracle.odi.core.OdiInstance;
import oracle.odi.core.config.MasterRepositoryDbInfo;
import oracle.odi.core.config.OdiInstanceConfig;
import oracle.odi.core.config.PoolingAttributes;
import oracle.odi.core.config.WorkRepositoryDbInfo;
import oracle.odi.core.persistence.transaction.ITransactionStatus;
import oracle.odi.core.persistence.transaction.support.DefaultTransactionDefinition;
import oracle.odi.core.security.Authentication;


@Path("connect")
public class ConnectService 
{
	
	private OdiInstance odiInstance;
	@SuppressWarnings("unused")
	private ITransactionStatus trans;
	

		@GET
		@POST
		@Produces(MediaType.TEXT_HTML)
				public Response connect() throws SQLException 
				{

				
					String result=null;
					
					try
					{
						
						
						MasterRepositoryDbInfo masterInfo = new MasterRepositoryDbInfo("jdbc:oracle:thin:@localhost:1522:orcl", 
									"oracle.jdbc.OracleDriver",	"ODIMR", "password".toCharArray(), new PoolingAttributes());
						WorkRepositoryDbInfo workInfo = new WorkRepositoryDbInfo("WORKREP121", new PoolingAttributes());
							
						odiInstance = OdiInstance.createInstance(new OdiInstanceConfig(masterInfo, workInfo));
						 
						Authentication auth = odiInstance.getSecurityManager().createAuthentication("SUPERVISOR", "password".toCharArray());
					    odiInstance.getSecurityManager().setCurrentThreadAuthentication(auth);
					    trans = odiInstance.getTransactionManager().getTransaction(new DefaultTransactionDefinition());
					
					    
					    if(odiInstance!=null)
					    	result = "Connected to ODI";
					    
					    return Response.status(200).entity(result).build();
					}
					catch(Exception e)
					{
						e.printStackTrace();
					}

					result = "Not Connected to ODI";
				    return Response.status(200).entity(result).build();
									
				}
	}
		

Similarly, one can create Service classes for Project and Scenario. Once this is done, run the client side Android application. Connect to ODI and then try creating a new Project as follows!

android_app_1

odi_1

Also, try executing a Scenario as follows!

android_app_2

odi_2

Finally, this completes the tutorial. Hope it helps! 🙂 Happy programming!

Save Excel sheet from browser using Apache POI

Hey everyone!

Apache POI is a useful Java API for Microsoft documents. It is a project run by the Apache Software Foundation providing Java libraries for both reading and writing files in MS Word, MS Excel, and Powerpoint. Many a times web application developers use the API to display an Excel sheet in the browser. For this purpose, we first need to populate the Excel sheet, read it using Apache POI and then display it using Servlets/JSP.

In this post, we will read a pre-populated Excel sheet and display the same using Servlets.

Pre-requisites: Eclipse IDE for Java EE developers, Apache Tomcat Server 6.0, Apache POI (download the binaries from over here)

Step 1: Create a new Dynamic Web project

Open Eclipse IDE and create a new Dynamic web project named DisplayExcelWeb. Create a new Servlet class with package name com.example as follows!

ExcelServlet.java

package com.example;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File; 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


/**
 * Servlet implementation class ExcelServlet
 */
public class ExcelServlet extends HttpServlet 
{
  
  private static final long serialVersionUID = 1L;     
	
  XSSFWorkbook workbook; 
	
    public ExcelServlet() 
    {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
     {	 
         try 
          {		     
	       
            FileInputStream file = new FileInputStream(new File("C:\\programs\\excel\\source.xlsx"));
		     
	        //Get the xlsx workbook
	        workbook = new XSSFWorkbook (file);
		    
		    //Get first sheet from the workbook
		    XSSFSheet sheet = workbook.getSheetAt(0);
		   
		   
		    //Get iterator to all cells of current row
		    Iterator<Row> rowIterator = sheet.rowIterator();
	  
		 while(rowIterator .hasNext())
		 {
		     
             Row row = rowIterator.next();
         
		    //For each row, iterate through each columns
		    Iterator<org.apache.poi.ss.usermodel.Cell> cellIterator = row.cellIterator();

		    while(cellIterator.hasNext()) 
		        {
		             
		            Cell cell = cellIterator.next();
		            
		            switch(cell.getCellType())
		            {
	                         
                          case Cell.CELL_TYPE_BOOLEAN:
	                      System.out.print(cell.getBooleanCellValue() + "\t\t");
	                      break;
	                         
                          case Cell.CELL_TYPE_NUMERIC:
	                      System.out.print(cell.getNumericCellValue() + "\t\t");
	                      break;
	                
                          case Cell.CELL_TYPE_STRING:
	                      System.out.print(cell.getStringCellValue() + "\t\t");
	                      break;
		            }	  
          
		        }		        
                          System.out.println("");
	           }    
		         file.close();
           } 
           catch (FileNotFoundException e) 
           {
		     e.printStackTrace();
           } 
           catch (IOException e) 
           {
		     e.printStackTrace();
           }
			
	   response.setContentType("application/vnd.ms-excel");
	   workbook.write(response.getOutputStream());
	   response.getOutputStream().close();
			
	}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>DisplayExcelWeb</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>ExcelServlet</display-name>
    <servlet-name>ExcelServlet</servlet-name>
    <servlet-class>com.example.ExcelServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ExcelServlet</servlet-name>
    <url-pattern>/ExcelServlet</url-pattern>
  </servlet-mapping>
</web-app>

Step 2: Add the following jar files inside the WEB-INF/lib folder

    poi-3.9
    poi-examples-3.9
    poi-excelant-3.9
    poi-ooxml-3.9
    poi-ooxml-schemas-3.9
    poi-scratchpad-3.9
    xmlbeans-2.3.0
    stax-api-1.0.1
    dom4j-1.6.1

Step 3: Create JSP page

Add a new JSP page called index.jsp that will call the Servlet!

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Display Excel</title>
</head>
<body>
<a href="ExcelServlet">Show Excel</a>
</body>
</html>

Finally, run the project on the Server. Once you click on the link, you should be able to save and view the Excel file.

display_excel_1

display_excel_2