Detect Internet Connection in Android

Hello everyone!

Android applications that require Internet connection need to check the connectivity status before making any HTTP requests. Using the ConnectivityManager class, developers can now determine the state of network connectivity and accordingly notify when the status changes.

For checking Internet connection status a simple code can be used. Create a new Android project with Activity class named CheckInternetConnection.

CheckInternetConnection.java

package com.example;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class CheckInternetConnection extends Activity
{

    boolean status = false;
	 	
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.check_internet);
 
        Button btnStatus = (Button) findViewById(R.id.btn_check);
        btnStatus.setOnClickListener(new View.OnClickListener() 
        {
            @Override
            public void onClick(View v) 
            {     
                status = checkInternetConnection();
 
                if (status)
                {
                  Toast.makeText(getApplicationContext(), "You have Internet connection", Toast.LENGTH_LONG).show();      	
                } 
                else 
                {
                  Toast.makeText(getApplicationContext(), "You don't have Internet connection", Toast.LENGTH_LONG).show();
                }
            }
        });
    }
    
    
    public boolean checkInternetConnection()
    {

    	  ConnectivityManager connectivity = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);

          if (connectivity != null) 
          {
              NetworkInfo[] inf = connectivity.getAllNetworkInfo();
              if (inf != null) 
                  for (int i = 0; i < inf.length; i++) 
                      if (inf[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }
 
          }
          return false;
      }	
}

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">

    <!-- Internet Permission -->
    <uses-permission android:name="android.permission.INTERNET" />
 
    <!-- Network State Permission -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_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.CheckInternetConnection"
            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>

check_internet.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Detect Internet Connection in Android " />
     
    <Button android:id="@+id/btn_check"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Check Internet Status"
        android:layout_centerInParent="true"/>
 
</RelativeLayout>

Try running the above code on a real Android device. You should see the following output!

Output

Tutorial #37: Getting started with ODI SDK

Hello everyone!

The Oracle Data Integrator platform includes an SDK that allows developers to write codes that perform tasks similar to the ones done using ODI Studio. The SDK helps in rapid application development and is usually located in the [ODI_HOME]\oracledi.sdk directory. In this tutorial, we would be using the .jar files present in that directory to build a Java application that creates a new Data Server, Physical, Logical schema and a Project.

Pre-requisites: Eclipse IDE (preferably the latest version), Oracle Data Integrator 11g (build version 11.1.1.7.0)

Launch Eclipse and create a new Java application project named MyOdiSDK. Once the project is created, go to Package Explorer, right click your project and select Properties. Configure the Java Build Path and add the external jar files as shown below!

adding jar files

Now, right click the src folder inside your project and create a new Java class named MyOdiSample.

Write the following code. Information about methods and classes used below can be obtained from over here.


package com.example;

import oracle.odi.core.OdiInstance;
import oracle.odi.core.persistence.transaction.ITransactionStatus;
import oracle.odi.core.persistence.transaction.support.TransactionCallbackWithoutResult;
import oracle.odi.core.persistence.transaction.support.TransactionTemplate;
import oracle.odi.domain.project.OdiFolder;
import oracle.odi.domain.project.OdiProject;
import oracle.odi.domain.topology.OdiContext;
import oracle.odi.domain.topology.OdiContextualSchemaMapping;
import oracle.odi.domain.topology.OdiDataServer;
import oracle.odi.domain.topology.OdiLogicalSchema;
import oracle.odi.domain.topology.OdiPhysicalSchema;
import oracle.odi.domain.topology.OdiTechnology;
import oracle.odi.domain.topology.finder.IOdiTechnologyFinder;
import oracle.odi.domain.util.ObfuscatedString;
import oracle.odi.publicapi.samples.SimpleOdiInstanceHandle;

public class MyOdiSample 
   {

	private static OdiDataServer myDataServer;
	protected static OdiContext myContext;

	  public static void main(String[] args) 
	  {

		final SimpleOdiInstanceHandle MyOdiInstanceHandle = SimpleOdiInstanceHandle
		.create("jdbc:oracle:thin:@localhost:1521:orcl",  //JDBC driver URL
		"oracle.jdbc.OracleDriver",  //Driver
		"ODIMR", //Your Master repository username should come here
		"password", //Your Master repository password should come here
		"WORKREP121", //Work repository name should come here
		"SUPERVISOR",  //ODI login username
		"password");   //ODI login password

         final OdiInstance MyOdiInstance = MyOdiInstanceHandle.getOdiInstance();
	        try 
                   {
		         TransactionTemplate tx = new TransactionTemplate(MyOdiInstance.getTransactionManager());
		         tx.execute(new TransactionCallbackWithoutResult()
		           {
                   protected void doInTransactionWithoutResult(ITransactionStatus pStatus)
		            {
		                 //Start writing your SDK code from here
										
		                 //Create a new Project							
 			         OdiProject proj = new OdiProject("MY_SDK_PROJECT", "MY_SDK_PROJECT");

  		             OdiContext myContext = new OdiContext("SDK_CONTEXT"); 
		             myContext.setDefaultContext(true);

                       // Creating a new Folder
                     OdiFolder fold = new OdiFolder(proj, "MY_SDK_FOLDER");
										
		                 // Save Project and myContext 
			         MyOdiInstance.getTransactionalEntityManager().persist(proj);
			         MyOdiInstance.getTransactionalEntityManager().persist(myContext);

		                 // creating a new Data Server , Physical Schema, Logical Schema
			         // Find the Oracle Technology
			         OdiTechnology oracleTechnology = ((IOdiTechnologyFinder) MyOdiInstance
			        .getTransactionalEntityManager().getFinder(
			         OdiTechnology.class)).findByCode("ORACLE");

											
			    if (oracleTechnology != null) 
			        {
			         myDataServer = new OdiDataServer(oracleTechnology,"MY_SDK_DATA_SERVER");

			         // connection settings
			         myDataServer.setConnectionSettings(new OdiDataServer.JdbcSettings(
			         "jdbc:oracle:thin:@localhost:1521:orcl","oracle.jdbc.driver.OracleDriver"));

			         // Provide database schema username and password
			         myDataServer.setUsername("system");
			         myDataServer.setPassword(ObfuscatedString.obfuscate("tiger"));

			        }

			// Creating a New Physical Schema
			OdiPhysicalSchema MyOraclePhysicalSchema = new OdiPhysicalSchema(myDataServer);
											
			// Provide information on the schema
			MyOraclePhysicalSchema.setSchemaName("MY_SDK_PHYSICAL");
			MyOraclePhysicalSchema.setWorkSchemaName("MY_SDK_WORK");

			// Create the logical schema and the map it to the context myContext
			OdiLogicalSchema MyOracleLogicalSchema = new OdiLogicalSchema(oracleTechnology, "MY_SDK_LOGICAL");
			new OdiContextualSchemaMapping(myContext,MyOracleLogicalSchema, MyOraclePhysicalSchema);


			// save the Data Server , Physical and Logical Schema
		    MyOdiInstance.getTransactionalEntityManager().persist(oracleTechnology);
											
			System.out.println("Process successfully completed........");

		           }
	          });
         }  
	       finally 
			{
				MyOdiInstanceHandle.release();
			}

    }

}


Finally, run the Java application. Open ODI Studio and you should see your Project, Data Server, Physical and Logical schema created.

java_console_output

data_server

physical_schema

logical_schema

context

projects

Source: ODI SDK Setup and Config in Eclipse

Oracle Data Integrator Tools: OdiFileWait and OdiBeep

Oracle Data Integrator contains tools (also called as commands) that are used for performing specific tasks at run-time. Some of the tasks would include sending emails, waiting for a particular file or producing a sound.

ODI tools are mainly used in packages. One can also develop his/her own tool using the Open Tool feature. Open tools are written in Java and help to extend the built in ODI features. For more information on Oracle Data Integrator tools please refer this link.

In this post, I will explain how to use the built in OdiFileWait and OdiBeep tool.

Pre-requisites: Oracle Data Integrator 11g (build version 11.1.1.7.0)

Open ODI Studio and in any of your existing Projects, create a new Package named test_1.

From the toolbox on the left pane, drag the OdiFileWait and the OdiBeep tool and connect them.

odi_tool_1

Now, click the OdiFileWait tool. Select the General tab and configure it as follows!

Configuring OdiFileWait tool

Command

OdiFileWait "-ACTION=NONE" "-DIR=D:\programs" "-PATTERN=test1.txt" "-CASESENS=NO" "-OVERWRITE=YES" "-FILECOUNT=1" "-TIMEOUT=0" "-POLLINT=1000" "-HEADER=0" "-KEEP_FIRST_HEADER=YES" "-NOFILE_ERROR=NO"

This command will tell ODI to wait for the text1.txt file present in directory D:\programs and proceed when this file is detected.

Similarly, configure the OdiBeep command and provide the input sound file to be played. The file formats supported are WAV, AIF and AU.

Configuring OdiBeep tool

Configuring OdiBeep tool

Command

OdiBeep "-FILE=D:\downloads\sample.wav"

Finally, run the package. Check the status of the operation under the Operator tab. If you have the file already present in the directory (D:\programs) mentioned above, you should hear the sound being played as soon as the Session gets started. If not, ODI will wait till you create the file and play the sound once the file is created.

Output

Output

Reference: OdiFileWait and OdiBeep

Send e-mail using Jython in Oracle Data Integrator

Hello friends!

Oracle Data Integrator includes a built-in tool called OdiSendMail which is used to send an email through a SMTP server. However, OdiSendMail will work only if the mail server does not require authentication.

In this post, I will demonstrate how to send an e-mail with the help of Gmail’s SMTP server. Instead of going for the OdiSendMail tool, I will be using the Jython technology in order to implement the same functionality.

Pre-requisites: Oracle Data Integrator 11g (build version 11.1.1.7.0)

Open ODI Studio and follow the below steps!

Step 1: Create a new Procedure

Create a new Procedure under any of your existing Projects in the Designer tab. Name the procedure SendEmail. Switch to Details and add a new entry.

create new procedure

procedure_1

Now, under Command on Target, you need to write the Jython code. Please make sure you have selected Technology as Jython.

procedure_3

Jython code

import smtplib
import string
BODY = string.join((
"From: %s" % 'senderemailaddress@gmail.com',
"To: %s" % 'recipientemailaddress@gmail.com',
"Subject: %s" % 'Test Mail',
"",'This is a test email from ODI'
), "\r\n")
sender = smtplib.SMTP('smtp.gmail.com',587)
sender.set_debuglevel(1)
sender.ehlo()
sender.starttls()
sender.ehlo()
sender.login('senderusername', 'senderpassword')
sender.sendmail('senderemailaddress',['recipientemailaddress'],BODY)
sender.close()

Note: You need to enter your valid Gmail credentials and replace sender and recipient address with valid email addresses in the above code.

Finally, run this procedure. Check the status of the operation under the Operator tab.

Output

Output

output_2

Source: Send mail in ODI using Gmail Credentials

Tutorial #36: Implement Daydream feature in Android

Hi everyone!

Android 4.2 (Jellybean) introduced a new feature called DayDream. The Daydream is basically an interactive screensaver mode that gets activated automatically when an Android device is left idle while charging or when it is inserted into a dock.

Daydream is similar to an Activity and a user can enable Daydream by selecting the Settings –> Display –> DayDream option and then choosing the daydream to display.

In this tutorial, we will create a simple Daydream application!

Pre-requisites: Eclipse IDE (preferably latest version), Android SDK with Android 4.2 (API level 17)

Open Eclipse IDE and create a new Android application project named AndroidDayDreamDemo with Target SDK Android 4.2. Let the package name be com.example. Choose to create MainActivity although we would not be using it in this tutorial.

Let’s begin by creating a new Java class inside the src folder named MyDayDreamService.java containing the following code!

MyDayDreamService.java


package com.example;


import android.service.dreams.DreamService;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
 
public class MyDayDreamService extends DreamService {
    @Override
   public void onAttachedToWindow() {
       super.onAttachedToWindow();

       //allow user touch
       setInteractive(true);
 
       //allow full screen
       setFullscreen(true);
 
       //Add text and image to dream layout
       RelativeLayout r1 = new RelativeLayout(this);
      
       RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(300, 250);
       params.addRule(RelativeLayout.CENTER_HORIZONTAL);
      
       TextView textView = new TextView(this);
       textView.setId(1);
       textView.setText("This is a demo of the DayDream service");
       textView.setTextSize(15);
       textView.setLayoutParams(params);
       
       r1.addView(textView,params);

       RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(300, 250);
       params2.addRule(RelativeLayout.BELOW,1); 
       params2.addRule(RelativeLayout.CENTER_HORIZONTAL);
       
       ImageView iv = new ImageView(this);
       iv.setImageResource(R.drawable.android);
       iv.setLayoutParams(params2);
       
       
       r1.addView(iv,params2);
      
       setContentView(r1);
          
   }
}

Open your AndroidManifest.xml file and add the Daydream Service as follows!

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-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.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>
        
         <service
    		 android:name=".MyDayDreamService"
     	     android:exported="true"
     		 android:label="AndroidDayDreamDemo" >
     			
                <intent-filter>
    	    	 <action android:name="android.service.dreams.DreamService" />
     		   	 <category android:name="android.intent.category.DEFAULT" />
    		   </intent-filter>
 	    
        </service>
        
    </application>
</manifest>

Finally, run the project on the emulator and you should see the following output!

Output

Output

Source code for this tutorial can be found over here

Justify text inside WebView in Android

Hey everyone!

In Android, at present there is no such built in property for justifying the text inside a WebView. Developers can use a simple trick in order to implement text justification.

The trick is to use HTML tags with justify alignment so that the text gets aligned properly. In your Activity class, add a WebView as follows!

MainActivity.java

package com.example;

import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebView;

public class MainActivity extends Activity 
{
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
	    
       super.onCreate(savedInstanceState);
	   setContentView(R.layout.main);
		
	   String text = "<html><body style=\"text-align:justify\"> %s </body></Html>";

	   String data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas ac quam risus, at tempus justo. Sed dictum rutrum massa eu volutpat. Quisque vitae hendrerit sem.";
	 
	   WebView webView = (WebView) findViewById(R.id.WebView);
	   webView.loadData(String.format(text, data), "text/html", "utf-8");
				
	}

}

main.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"
    tools:context=".MainActivity">
 
    <WebView
        android:id="@+id/WebView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
 
</RelativeLayout>

Output

Output

Note: You cannot apply the same trick for TextView since Android does not support full justification at present. For more information refer this link.

Upload file using Servlets/JSP in Java

Hello friends!

In many web applications, the user needs to upload a file on the web so that it can be used later on. Java EE allows developers to create dynamic web applications using Servlets or JSP (Java Server Pages). A Servlet is like any other Java class. You insert your HTML code into print statements like you use System.out. On the other hand, a JSP gets converted to a Servlet and embeds the Java code into HTML. Servlets and JSP are functionally equivalent.

In this post I will demonstrate how to upload a file using the Servlets/JSP technology.

Pre-requisites: Eclipse IDE for Java EE developers, Apache Tomcat 7

Open Eclipse. Create a new Dynamic web project. Name the project as FileUploadExample. Select Target Runtime environment as Apache Tomcat 7.0. If you are unable to get this option, you need to configure and install Apache Tomcat 7 by following this link.

file_upload_1

Create new dynamic web project

Create new dynamic web project

Step 1: Add .jar files

Before you start implementing your Servlet code, you need to add two .jar files namely commons-fileupload-1.3.jar and commons-io-2.4.jar to the lib folder present under WEB-INF.

Step 2: Create JSP page

Now create a new JSP page named index.jsp inside your WebContent folder.

index.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>File Upload</title>
</head>
 
<body>

    <hr/>
 
    <fieldset>
        <legend>Upload File</legend>
        <form action="fileuploadservlet" method="post" enctype="multipart/form-data">
            <label for="filename_1">File: </label>
            <input id="filename_1" type="file" name="filename_1" size="50"/><br/>
            <br/>
            <input type="submit" value="Upload File"/>
        </form>
    </fieldset>
   
</body>
</html>

Step 3: Create Servlet and modify web.xml

Right click the src folder, and select New –> Servlet. Name the Servlet FileUploadDemoServlet and give the package name as com.example

FileUploadDemoServlet.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 org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.File;
import java.util.List;
import java.util.Iterator;
 
public class FileUploadDemoServlet extends HttpServlet {
    private static final long serialVersionUID = -3208409086358916855L;
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
            {

    	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
 
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
 
            try {
                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();
                while (iterator.hasNext())
                 {
                    FileItem item = (FileItem) iterator.next();
 
                    if (!item.isFormField()) 
                     {
                       
                        String fileName = item.getName();
                        String root = getServletContext().getRealPath("/");
                        
                        //path where the file will be stored
                        File path = new File("C:\\programs\\java_documents" + "/uploads");
                        if (!path.exists())
                        {
                            boolean status = path.mkdirs();
                        }
 
                        File uploadedFile = new File(path + "/" + fileName);
                        System.out.println(uploadedFile.getAbsolutePath());
                        item.write(uploadedFile);
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Modify your web.xml file as follows!

<?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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>FileUploadExample2</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>
        <servlet-name>FileUploadDemoServlet</servlet-name>
        <servlet-class>com.example.FileUploadDemoServlet</servlet-class>
  </servlet>
    
  <servlet-mapping>
        <servlet-name>FileUploadDemoServlet</servlet-name>
        <url-pattern>/fileuploadservlet</url-pattern>
  </servlet-mapping>
   
</web-app>

Finally, run the project on the Apache Tomcat server. Make sure no errors are present. You should see the following output on your console and browser respectively!

Output on browser and console

file_upload_output_1

Tutorial #35: Load CSV file data in Oracle table using ODI

Hello everyone!

In today’s tutorial I will show you how to transfer your CSV file data in an Oracle database table. A CSV (Comma-separated value) file basically stores tabular data (numbers and text) in plain-text form. It is a common and simple file format used by many applications.

Pre-requisites: Oracle database 10g Express Edition with *SQLPlus, Oracle Data Integrator (build version 11.1.1.0.7)

First, you need to create your .csv file. Open notepad and write the following!

EMPLOYEE_ID,FIRSTNAME,LASTNAME
1,Dean,Winchester
2,John,Winchester
3,Sam,Winchester

Save the file with filename as employee.csv

Next we need to create a corresponding table in Oracle to store this information. Open *SQLPlus and login with your credentials. Create table using following command!

create table csv_test(empid int primary key, firstname varchar(30), lastname varchar(30));

The data in this table will come from the .csv file that we will load using Oracle Data Integrator.

Now, open ODI Studio and follow the below steps!

Step 1: Create new data server, physical schema for CSV file

Under Topology navigator, go to Physical Architecture, expand Technologies, right click the File technology and select new Data Server.

Create new data server and physical schema

Create new data server and physical schema

data_server_2

physical_schema

While creating your Physical Schema, you need to specify the location where your .csv file exists. In my case the file is located at C:\programs\java_documents\uploads

Step 2: Create logical schema for CSV file

create logical schema

create logical schema

Step 3: Create data model for CSV file

Under Designer tab, go to Models and create a new Model folder. Then create two models, one for the CSV file and the other for the Oracle table.

Create new data model

model1_2

Right click the created csv data model and select New DataStore

data_store_1

data_store_2

Create datastore

Create datastore

Note: The comma in Field Separator is added because it is a CSV file, and the double quotation mark in Text Delimiter is required because the contents have comma (example: 1, Dean, Winchester).

In a similar manner, create model for the Oracle table by the usual reverse engineering method!

create model for table

create model for table

Step 4: Create new interface

Finally, create a new interface named csv_test. LKM used is File to Oracle (SQLLDR) and IKM Oracle Incremental Update.

interface_1

interface_2

interface_3

Create new interface

Create new interface

Run the interface. Check the status of the operation under the Operator tab. If everything works fine you should now see the data inserted successfully in your Oracle table.

Output

Output

output_2

That completes another ODI tutorial. Stay tuned for more! 🙂

Tutorial #34: Using Google Maps Android API v2

Starting from December 3rd, 2012 Google had officially deprecated the use of the Google Maps Android API version 1. The new version 2 of the API automatically handles access to Google map servers, downloading of data etc. Using this version you can also add markers, polygons and overlays to a basic map and allow user interaction with the map.

Some key features provided by Google Maps Android API v2 are:

    1) Icons anchored to specific positions on the map (Markers)

    2) Sets of line segments (Polylines)

    3) Enclosed segments (Polygons)

    4) Bitmap graphics anchored to specific positions on the map (Ground Overlays)

    5) Sets of images which are displayed on top of the base map tiles (Tile Overlays)

In this tutorial I will explain how to get a Google Map API key followed by a demo of Google Maps in action on Android!

Pre-requisites: Windows 7 (64 bit OS), Eclipse IDE, Android SDK

Step 1: Obtaining the Google Map API key

To use google maps you need to get a map key. However, even before that you need to get a SHA-1 fingerprint from your jdk installation. Open command prompt, navigate to your jdk directory and use the keytool executable to generate your key.

Generate MD5 key

Generate SHA-1 fingerprint


Syntax for using keytool

C:\<path-to-jdk-dir>\bin\keytool.exe -list -alias androiddebugkey -keystore "C:\users\<user-name>\.android\debug.keystore" -storepass android -keypass android

Now, you need to sign up for the Android Maps API by logging in with your Gmail account from over here.

Create a new Android key and paste your above generated SHA-1 fingerprint along with your project package name in the box provided.

android_google_maps_2

android_google_maps_3

Step 2: Download Google play services

In order to use Google maps in your Android projects you would need to download and install the Google play services from your Android SDK manager. As you can see in the below screenshot I have already installed the play services. You would need to check the same and then install it.

Installing Google play services

Step 3: Import Google Play services library project

Once you have installed the google play services successfully, you will find a library project at location C:\path-to-adt-bundle\sdk\extras\google\google_play_services. Open Eclipse IDE and import this existing project by using File –> Import –> Existing Android Projects into workspace.

Step 4: Create new Android project

Create a new Android project named AndroidGoogleMapsDemo with package name com.example. The package name should be same as that mentioned while creating SHA-1 fingerprint in step 1. Select Target SDK as Android 4.2 and create activity named MainActivity. Also, add reference to google-play-services_lib project as follows!

android_google_maps_5

To add reference to library project, right click your Project –> Properties –> Android. Click on Add and select project.

android_google_maps_6

Make changes to AndroidManifest.xml file as follows!

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-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <permission android:name="com.example.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="com.mapexplore.permission.MAPS_RECEIVE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
     
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.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>
        
         <!-- Your API key needs to be added over here -->
         <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyAJ90gij_G7VaGy9w8L6EvO-zu8CHtTLRI" />
         
    </application>
</manifest>

MainActivity.java

package com.example;

import android.os.Build;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.view.Menu;


@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MainActivity extends Activity 
 {

	  static final LatLng MUMBAI = new LatLng(19.0144100, 72.8479400);
	  private GoogleMap map;

	  @Override
	  protected void onCreate(Bundle savedInstanceState) 
          {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_main);
	    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
	    map.moveCamera(CameraUpdateFactory.newLatLngZoom(MUMBAI, 15));

	    // Zoom in, animating the camera.
	    map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
	  }
}

activity_main.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=".MainActivity" >

     <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment" />

</RelativeLayout>

Finally, run the project and you should see the following output! Thanks and happy coding! 🙂

Output

Tutorial #33: Using Custom Java code in ODI

Hello everyone!

It’s time for another cool tutorial on Oracle Data Integrator. This one will guide you in using your custom Java code and help call .jar files from within ODI.

Pre-requisites: Oracle Data Integrator 11g (build version 11.1.1.0.7)

Step 1: Write Java code to perform Addition of two numbers

Open notepad and start coding. Here is what my Java class looks like:

Addition.java


import java.util.Scanner;

public class Addition 
{
	
	public int number1, number2;
	

	public int add(int num1, int num2)
	{
		return (num1+ num2);
	}
	
	public static void main(String args[]) throws Exception
	{
		
		int num1,num2;
		
		Addition addobject = new Addition();
		System.out.println("--------------Program to add two numbers---------------");
		Scanner s = new Scanner(System.in);
		System.out.println("Enter 1st number");
		num1= s.nextInt();
		System.out.println("Enter 2nd number");
		num2=s.nextInt();
		
		System.out.println("result of addition is :" + " " +addobject.add(num1, num2) );	
	}

}

Step 2: Compile and create .jar file

Compile the .java class from the command line

C:\programs\javac Addition.java

Create .jar file from the class

C:\programs\jar cf Addition.jar Addition.class

Copy the newly created Addition.jar file and paste it at the following locations!

1st location

C:\oracle\product\11.1.1\Oracle_ODI_1\oracledi\agent\drivers

2nd location

C:\Users\<user-name>\AppData\Roaming\odi\oracledi\userlib

At the second location, you will find the additional_path.txt file. Open it and add the path to your .jar file.

; Additional paths file
; You can add here paths to additional libraries
; Examples:
;	C:\ java\libs\myjar.jar
;	C:\ java\libs\myzip.zip
;            C:\oracle\product\11.1.1\Oracle_ODI_1\oracledi\agent\drivers\
;	C:\java\libs\*.jar will add all jars contained in the C:\java\libs\ directory
;	C:\java\libs\**\*.jar will add all jars contained in the C:\java\libs\ directory and subdirectories

C:\Users\karan\AppData\Roaming\odi\oracledi\userlib\*.jar

Workaround

After you have copied the .jar file you now need to do a workaround. Copy the Lib folder from C:\oracle\product\11.1.1\Oracle_ODI_1\oracledi.sdk\lib and paste it inside C:\oracle\product\11.1.1\Oracle_ODI_1\oracledi\agent\lib. This makes sure that ODI reads the python files when we try to import them in our procedure code.

Step 3: Create new procedure

Launch ODI Studio and connect to your work repository. Create new procedure named AddTwoNumbers in any of your existing Projects.

Create new procedure

create_procedure_2

Now, write the command for the procedure in Jython

import os
import sys

jars = [
"C:\oracle\product\11.1.1\Oracle_ODI_1\oracledi\agent\drivers\Addition.jar"
]

for jar in jars:
      sys.path.append(jar)

import Addition

num1 = <%=odiRef.getOption("number1")%>
num2 = <%=odiRef.getOption("number2")%>

print  "1st number: %d" % num1
print  "2nd number: %d" % num2

addobj= Addition()

result= addobj.add(num1,num2)

print "Sum is : %d" % result

Note: Make sure the above code is well indented or else it will result in errors when executed.

Before you run this procedure you need to create two Options that will act as input parameters for the procedure.

option_1

option_2

Step 4: Create new package

Create new package named Addition of Two Numbers. Add the procedure to the package with the correct options and run the package. Check the status of the operation under the Operator navigator.

Create new package

create_package_2

create_package_3

Output

Output

Note: In order to view the output on the command line window, one can Create a new Agent and run the above package by selecting your agent.