24 December 2014

Data Mining Classification with weka

My final year project based on data mining and data classification.So i spent lot of time to find how data classification done by using weka. So In this article i will show how data classification/prediction using weka API.In This tutorial i will show how to predict data using weka API.First you need data set.For that i will suggest it is better to install weka (http://www.cs.waikato.ac.nz/ml/weka/downloading.html )software in your computer. After installing you can see in the installed location data folder.For this tutorial i will use iris.ARFF to predict result.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@RELATION iris

@ATTRIBUTE sepallength REAL

@ATTRIBUTE sepalwidth  REAL

@ATTRIBUTE petallength  REAL

@ATTRIBUTE petalwidth REAL

@ATTRIBUTE class  {Iris-setosa,Iris-versicolor,Iris-virginica}

@DATA

5.1,3.5,1.4,0.2,Iris-setosa

4.9,3.0,1.4,0.2,Iris-setosa

4.7,3.2,1.3,0.2,Iris-setosa

4.6,3.1,1.5,0.2,Iris-setosa

5.0,3.6,1.4,0.2,Iris-setosa

5.4,3.9,1.7,0.4,Iris-setosa

4.6,3.4,1.4,0.3,Iris-setosa

5.0,3.4,1.5,0.2,Iris-setosa

4.4,2.9,1.4,0.2,Iris-setosa

4.9,3.1,1.5,0.1,Iris-setosa

5.4,3.7,1.5,0.2,Iris-setosa

4.8,3.4,1.6,0.2,Iris-setosa

4.8,3.0,1.4,0.1,Iris-setosa

This is the sample data set.Here you can see data set realation name is iris and there are four Attribute to predict class.For predict the class there are several classification algorithm available in  weka API.In here i have used decision tree classification.

First you need to open weka and select iris.arff file and then go to classification tab and select J48 algorithm.Then start classification process.Then you can see this result.


Then you can see the decision tree generated in weka.For the write click the j48 panel (blue color) and visualize.



 Then we have to predict the class value based on our four attributes.In this example i will predict the  class value for this attribute data.     
 4.8,2.1,3.7,1.4,?

1 Step :

Need to build model file for using data set.As a first step you have to add weka jar file to your project and import necessary classes. For building model file we need the data set and using the data set based on the classification algorithm we build model here.I have used cross validation as evaluation technique.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public void buildIrisModel() {

        try {

            ConverterUtils.DataSource source = new ConverterUtils.DataSource("C://Users//Sajith//Desktop//iris.arff");

            Instances train = source.getDataSet();

            train.setClassIndex(train.numAttributes() - 1);

            J48 j48 = new J48();

            j48.setUnpruned(true);

            Evaluation eval = new Evaluation(train);

            eval.crossValidateModel(j48, train, 10, new Random(1));

            System.out.println("Percent correct: " + Double.toString(eval.pctCorrect()));

            System.out.println("Correct : " + Double.toString(eval.correct()));

            System.out.println("Incorrect : " + Double.toString(eval.incorrect()));

            System.out.println("Error Rate : " + Double.toString(eval.errorRate()));

            System.out.println("Mean Absolute Error  : " + Double.toString(eval.meanAbsoluteError()));


            j48.buildClassifier(train);

            ObjectOutputStream oos = new ObjectOutputStream(

                    new FileOutputStream("C://Users//Sajith//Desktop//iris.model"));

            oos.writeObject(j48);

            oos.flush();

            oos.close();

            System.out.println("Graph   : " + j48.graph());

        } catch (Exception e) {

            e.printStackTrace();

        }

    }
2 Step :
This method used to generate Instance of Arff data set.It means we create instance of data set and using that Instance predict class value. This CreateInstance method get the four attributes and returns the Instance.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
private Instances data;

    public Instances CreateInstance(double sepallength,double sepalwidth,double petallength,double petalwidth){

        double result = -1;

        String prediction=null;

        try {

          ArrayList<Attribute> attributeList = new ArrayList<Attribute>(2);

          Attribute attribute_sepallength = new Attribute("sepallength");

          Attribute attribute_sepalwidth = new Attribute("sepalwidth");

          Attribute attribute_petallength = new Attribute("petallength");

          Attribute attribute_petalwidth = new Attribute("petalwidth");

            ArrayList<String> classVal = new ArrayList<String>();

            classVal.add("Iris-setosa");

            classVal.add("Iris-versicolor");

            classVal.add("Iris-virginica"); 

            attributeList.add(attribute_sepallength);

            attributeList.add(attribute_sepalwidth);

            attributeList.add(attribute_petallength);

            attributeList.add(attribute_petalwidth);

            attributeList.add(new Attribute("class",classVal));


            data = new Instances("Iris",attributeList,0);

            data.setClassIndex(data.numAttributes() - 1);


            Instance inst_co = new DenseInstance(data.numAttributes());


            inst_co.setValue(attribute_sepallength, sepallength);

            inst_co.setValue(attribute_sepalwidth, sepalwidth);

            inst_co.setValue(attribute_petallength, petallength);

            inst_co.setValue(attribute_petalwidth, petalwidth);

            data.add(inst_co);

            System.out.println(data);

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

        return data;

    }

3  Step:
This is the last step.In this step we parse the data and create Instance and then predict class value based on Instance.

1
2
3
4
5
// parse sepallength,sepalwidth,petallength,petalwidth  values
Instances inst = new wekaWriteArfFile().CreateInstance(4.8,2.1,3.7,1.4);
Classifier j48_classifier = (Classifier)weka.core.SerializationHelper.read("C://Users//Sajith//Desktop//ModelFiles//j48_iris_model.model");
 value = j48_classifier.classifyInstance(inst.instance(linereadFromfile));
 prediction = inst.classAttribute().value((int) value);

And now you got the result.Later i will upload source code in to github..Thanks

05 December 2014

Java swing chart library

First You need to download library.(http://www.jfree.org/jfreechart/download.html).Then it supports different type of chart types and it is easy to implement.Here i will describe how to implement PieChart and save chart as Image.Before You start you have to import jcommon and jfreechart to your project.

public class PieChartExampleDemo extends JFrame {

    public PieChartExampleDemo(String applicationTitle, String chartTitle) {

        super(applicationTitle);

        PieDataset dataset = createDataset();

        JFreeChart chart = createChart(dataset, chartTitle);

        String filename = "F:\\pichartImage.jpg";

        try {

            ChartUtilities.saveChartAsJPEG(new File(filename), chart, 600, 400);

        } catch (IOException e) {

            e.printStackTrace();

        }

        ChartPanel chartPanel = new ChartPanel(chart);

        chartPanel.setPreferredSize(new java.awt.Dimension(600, 400));

        setContentPane(chartPanel);


    }


    private  PieDataset createDataset() {

        DefaultPieDataset result = new DefaultPieDataset();

        result.setValue("Blackberry", 24);

        result.setValue("Apple", 22);

        result.setValue("Windows", 44);

        result.setValue("Android", 35);

        result.setValue("Symbian", 5);

        result.setValue("Other", 4);

        return result;


    }


    private JFreeChart createChart(PieDataset dataset, String title) {

        JFreeChart chart = ChartFactory.createPieChart3D(title, dataset,

                true,

                true,

                false);

        PiePlot3D plot = (PiePlot3D) chart.getPlot();

        plot.setStartAngle(290);

        plot.setDirection(Rotation.CLOCKWISE);

        plot.setForegroundAlpha(0.5f);

        return chart;

    }

}

From main class you can call to this class.You can save chart as jpg image.

PieChartExampleDemo pieChartExampleDemo = new PieChartExampleDemo("Mobile OS", "Mobile operating System Usage 2014");
        pieChartExampleDemo.pack();
        pieChartExampleDemo.setVisible(true);


And This is the result.



22 November 2014

Generate webapp using maven archetype plugin

In this example describes how to create web app using maven archetype plugin.And here i used jetty server. First You have to install maven in your computer. http://mavenforu.blogspot.com/2013/09/maven-installation-guide.html in here i have explain how to install maven in windows.So then go to your workspace and type this command.

mvn archetype:generate -DgroupId=com.sajith.maven -DartifactId=MyFirstWebApp -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
GroupId and DartifactId can be change to your package name and project name.

Then Change the POM file and add the jetty maven plugin.Inside the Plugins notation add these plugin.
<plugin>
     <groupId>org.mortbay.jetty</groupId>
     <artifactId>maven-jetty-plugin</artifactId>
     <version>6.1.10</version>
     <configuration>
     <scanIntervalSeconds>10</scanIntervalSeconds>
     <connectors>
     <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
          <port>8080</port>
          <maxIdleTime>60000</maxIdleTime>
     </connector>
     </connectors>
     </configuration>
 </plugin>
Then Enter this command
mvn clean install
mvn jetty:run

How to use maven for Android


If you are Android developer you must used some development IDE(eclipse, idea) for developingandroid application.

But when you want to build the APK file you no need to use IDE. So Maven introduce the maven build plugin for android.

Here i have describe how to install maven(http://sajithforu.blogspot.com/2014/10/maven-installation-guide.html).

First you need android keystore for verify the apk file.So this will help you to how to create keystore in android.(http://developer.android.com/tools/publishing/app-signing.html).

First you have to install android sdk development kit in your machine.Then First set ANDROID_HOME path variable in your machine.



Second step genarate the keystore set KEYSTORE_HOME path variable in your PC.




Third create your android application using any IDE.

Inside the project create pom.xml file and put this code. and change the  App_name and relevant changes.

Make sure you have correct platform version



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>App</groupId>
        <artifactId>modules</artifactId>
        <version>1.0.8</version>
    </parent>
 
    <groupId>App</groupId>
    <artifactId>App</artifactId>
    <version>1.0.8</version>
    <packaging>apk</packaging>
    <name>App-name</name>
 
    <dependencies>
        <dependency>
            <groupId>com.google.android</groupId>
            <artifactId>android</artifactId>
            <version>${platform.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.2.4</version>
        </dependency>

        <dependency>
            <groupId>org.roboguice</groupId>
            <artifactId>roboguice</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <finalName>App</finalName>
        <sourceDirectory>src/main/java</sourceDirectory>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jarsigner-plugin</artifactId>
                <version>1.2</version>
                <executions>
                    <execution>
                        <id>signing</id>
                        <goals>
                            <goal>sign</goal>
                        </goals>
                        <phase>package</phase>
                        <inherited>true</inherited>
                        <configuration>
                            <includes>
                                <include>target/*.apk</include>
                            </includes>
                            <keystore>${env.KEYSTORE_HOME}/android-pos.keystore</keystore>
                            <storepass>keystorepassword</storepass>
                            <keypass>keypass</keypass>
                            <alias>your_alias</alias>
                            <verbose>true</verbose>
                            <arguments>
                                <argument>-sigalg</argument>
                                <argument>MD5withRSA</argument>
                                <argument>-digestalg</argument>
                                <argument>SHA1</argument>
                            </arguments>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>com.jayway.maven.plugins.android.generation2</groupId>
                <artifactId>android-maven-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <release>true</release>
                    <sdk>
                        <platform>17</platform>
                        <path>${env.ANDROID_HOME}</path>
                    </sdk>
                    <sign>
                        <debug>false</debug>
                    </sign>
                    <extractDuplicates>true</extractDuplicates>
                    <proguard>
                        <skip>false</skip>
                        <config>proguard.cfg</config>
                        <configs>
                            <config>${env.ANDROID_HOME}/tools/proguard/proguard-android.txt</config>
                        </configs>
                        <filterMavenDescriptor>false</filterMavenDescriptor>
                        <filterManifest>false</filterManifest>
                        <jvmArguments>
                            <jvmArgument>-Xms256m</jvmArgument>
                            <jvmArgument>-Xmx512m</jvmArgument>
                        </jvmArguments>
                    </proguard>
                </configuration>
                <extensions>true</extensions>
            </plugin>
            <plugin>
                <groupId>com.jayway.maven.plugins.android.generation2</groupId>
                <artifactId>maven-android-plugin</artifactId>
                <configuration>
                    <zipalign>
                        <verbose>true</verbose>
                        <skip>false</skip>            
                        <inputApk>${project.build.directory}/${project.artifactId}-${project.version}.apk</inputApk>
                        <outputApk>${project.build.directory}/${project.artifactId}-${project.version}-RELEASE.apk>
                        </outputApk>
                    </zipalign>
                    <manifest>
                        <debuggable>false</debuggable>
                        <versionCodeAutoIncrement>true</versionCodeAutoIncrement>
                    </manifest>
                    <proguard>
                        <skip>true</skip>
                    </proguard>
                </configuration>
                <executions>
                    <execution>
                        <id>zipalign</id>
                        <phase>install</phase>
                        <goals>
                            <goal>zipalign</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-site-plugin</artifactId>
                <configuration>
                    <reportPlugins>
                        <plugin>
                            <groupId>org.codehaus.mojo</groupId>
                            <artifactId>findbugs-maven-plugin</artifactId>
                        </plugin>
                    </reportPlugins>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


Then go to the project and run these maven cvommands to compile and run the project.
         mvn clean install
         mvn android:compile
         mvn android:run

And that is all.Thanks

19 November 2014

How to access global variable in android all activities

Hi in this post i will describe how to use global variable to access all the activities in android application.First you have to define application class in manifest file.


<application android:label="@string/app_name" 

     android:icon="@drawable/logo"

     android:name="com.homesystem.net.CustomApplication">

</application>

CustomApplication class is a class which used to store and access global variables.

public class CustomApplication extends Application {

    public static String message = "";

    public static boolean state =true;

    private static CustomApplication singleton;

    public static CustomApplication getInstance() {

        return singleton;

    }

    @Override
    public void onCreate() {
        super.onCreate();
        singleton = this;
    }


    }


And then inside any activity you can update and real values in CustomApplication class.

String Message = CustomApplication .message;
boolean state=CustomApplication .state;


Java JDBC connection using maven

In this article I will describe how to create jdbc connection and read values from mysql database.

First In your POM file add the following dependency.

<dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
     <version>5.1.17</version>
     <type>jar</type>
     <scope>compile</scope>
 </dependency>

Then From your java application you can check the Jdbc connection.In my application i have database called java_form  and table called user_details.

In here i have First check the database connection.And next method insert data to database. Then Retrieve data from database after all  close the connection.

public class DataBaseConnectivity {
    Connection connection;

    /**
     *  Connect database
     * @return
     */
    public boolean connect_database() {
        boolean check_connection = false;
        String database_Url= "jdbc:mysql://localhost/java_form";
        String database_Class= "com.mysql.jdbc.Driver";        
        String username = "root";
        String password = "";
        try {
            Class.forName(database_Class);
          connection = DriverManager.getConnection(database_Url, username, password);          
           
            if (connection != null) {
                check_connection = true;
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return check_connection;
    }

    /**
     *  Insert DATA to table
     * @param uId
     * @return
     */
    public boolean insert_uId(String uId) {
        String query = "INSERT INTO user_details (uID)VALUES (" + uId + ")";
        Statement statement = null;
        try {
            statement = connection.createStatement();
            int resultSet = statement.executeUpdate(query);
            System.out.println("UID added to database");
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return true;
    }

    /**
     *   Retrive data from table
     * @return
     */
    public boolean retrive_Data() {
        String query = "Select uID from user_details";

        try {
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(query);
            while (resultSet.next()) {
                String tableName = resultSet.getString(1);
                System.out.println("UID value : " + tableName);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return true;
    }
}

Get Text from Listview when Listview clicked

This is simple question.But today i spent lot of time to search get text from Listview . Here i will share it for you.

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override

            public void onItemClick(AdapterView<?> parent, View view,

                                    int position, long id) {

                TextView textview= (TextView) view.findViewById(R.id.label);

                String profileName = textview.getText().toString();


            }

        });



10 November 2014

How Send SMS in android Pragmatically

This is very simple.So There are two type to send SMS.First one is SMS manager API and second one is Build-in sms application.In here i have only explain how to send SMS via SMS manager API.
This is the class which support to send SMS.when we using SMS manager API we can't see any UI level change when sending message.

import android.content.Context;

import android.telephony.SmsManager;

import android.widget.Toast;

public class SendSms {

    Context context;

    public SendSms(Context context){

      this.context=context;

    }

    String phoneNo="telnumber(+9471 1111111)";

    public void SendSms(String sms){

        try {

            SmsManager smsManager = SmsManager.getDefault();

            smsManager.sendTextMessage(phoneNo, null, sms, null, null);

            Toast.makeText(context, "SMS Sent!",

                    Toast.LENGTH_LONG).show();

        } catch (Exception e) {

            Toast.makeText(context,

                    "SMS faild, please try again later!",

                    Toast.LENGTH_LONG).show();

            e.printStackTrace();

        }

    }

}

And make sure you have add SMS send uses-permission.
 <uses-permission android:name="android.permission.SEND_SMS" />

And happy coding..

How to receive SMS in android BroadcastReceiver

In this post i will tell you how to receive SMS in your application.If your application need to receive sms from specific number this is the way we want to do.First you need to BroadcastReceiver to receive sms from background.
    First you need to add uses-permission to READ SMS.

    <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.SEND_SMS"></uses-permission>

Then This is the code line for receive SMS.

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.os.Bundle;

import android.telephony.SmsManager;

import android.telephony.SmsMessage;

import android.util.Log;

import android.widget.Toast;

public class ReceiveSms extends BroadcastReceiver {

    final SmsManager sms = SmsManager.getDefault();

    public void onReceive(Context context, Intent intent) {      

        final Bundle bundle = intent.getExtras();

        try {

          if (bundle != null) {

           final Object[] pdusObj = (Object[]) bundle.get("pdus");

          for (int i = 0; i < pdusObj.length; i++) {

        SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);

        String phoneNumber = currentMessage.getDisplayOriginatingAddress();

        String senderNum = phoneNumber;

        String message = currentMessage.getDisplayMessageBody();

        int duration = Toast.LENGTH_LONG;

        Toast toast = Toast.makeText(context,

                            "senderNum: "+ senderNum + ", message: " + message, duration);

                    toast.show();
                }
            }

        } catch (Exception e) {
            Log.e("SmsReceiver", "Exception smsReceiver" + e);

        }

    }

}


And Finally you have to Add your receiver in manifest file(Inside application tags).You must be add android:priority="500" other wise it will not work.

<receiver android:name="com.example.HomeControlSystem.ReceiveSms">
      <intent-filter android:priority="500">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
      </intent-filter> </receiver>

Happy coding..

02 November 2014

Begin with bootstrap

Here i have started twitter bootstrap web application development.In here i will talk basic stuff to build your own responsive web application.First thing first.You need to know what is twitter bootstrap.It is world famous responsive web development framework.First you have to download bootstrap from this link. [http://getbootstrap.com/customize/?id=ecab5932bfb5dc96278d].First unzip the file and Then you need to add index.html file to home folder.

You can use template html file to index.html file.So this is the code.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap 101 Template</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">  
  </head>
  <body>
    <h1>Hello, world!</h1>
    <a href="" class="btn" >Hello World</a>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
 
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>


Then here on words i will talk what are the components one by one.So first look at how to add button and change color and size of button.There are free-defined css type for buttons.

Buttons

There are seven types of buttons.

  <button type="button" class="btn btn-default">Default</button>
  <button type="button" class="btn btn-primary">Primary</button>
  <button type="button" class="btn btn-info">Info</button>
  <button type="button" class="btn btn-success">Success</button>
  <button type="button" class="btn btn-warning">Warning</button>
  <button type="button" class="btn btn-danger">Danger</button>
  <button type="button" class="btn btn-link">Link</button>

When we need to change size of button this also have free-defined sizes.





22 October 2014

Google Maps Android API v2 Key

In here i will explain how to generate android goggle map v2 API key for android application.First You have to generate SHA-1 finger print.For that you use terminal.


keytool -list -v -keystore C:\Users\<username>\.android\debug.keystore -storepass android -keypass android














Then you can see SHA-1 is printing.Then go to here(https://code.google.com/apis/console/?noredirect) and create new project.Then go to API access and click the create new android key button.Then add your sha-1 finger print;packagename and genarate key.

Ex :-AC:C7:99:64:B7:9B:C8:25:53:6D:B2:2F:79:59:59:F9:37:1B:AF:A4;com.example.appname

com.example.appname is your android project package name.Then you can see there is key generated.You can use this key for your application.

Android Volley library json parse example

In this post i will describe how to use android volley library for your json request.First you have to download android volley library.I have uploaded this sample projcet to github so you can download volley.jar file from here(https://github.com/sajith4u/Android_volley_Sample/tree/master/Android_Volley/libs).Or you can download from here(https://drive.google.com/?tab=jo&authuser=0#folders/0B6boUJ62bUIXZUJQbUdoS08tMms).First You have to add AppController class to your package.Befor that make sure you have put volley.jar file in to your lib folder.
package com.example.Android_Volley;

import android.app.Application;

import android.text.TextUtils;

import com.android.volley.Request;

import com.android.volley.RequestQueue;

import com.android.volley.toolbox.Volley;


public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;

    private static AppController mInstance;

    @Override

    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {

        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;

    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }


    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {

        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }

}

Then You have to Add this class to your manifest file.So inside the Application tag put the name of class.
<application android:label="@string/app_name"

                 android:icon="@drawable/ic_launcher"

                 android:name="com.example.Android_Volley.AppController">

        <activity android:name="MyActivity"

                  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>

And also make shure add internet permission in to your application.
 <uses-permission android:name="android.permission.INTERNET"/>

Then inside main activity i have one button and when i click button it will read json object and show in to textview.I have used this public json call to show demo.(http://time.jsontest.com/) it will return date, time and other parameter inside json object.

date:- String
mili seconds :- Double
time:- String

when button clicked it called to this method.
   

    private void makeJsonObjectRequest() {

        showpDialog();

       JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,

                urlJsonObj, null, new Response.Listener<JSONObject>() {

            @Override

            public void onResponse(JSONObject response) {

                try {                    

                 String time = response.getString("time");

                 Double mili = response.getDouble("milliseconds_since_epoch");

                 String date = response.getString("date");

                 jsonResponse = "";

                 jsonResponse += "Time: " + time + "\n\n";

                 jsonResponse += "seconds: " + mili + "\n\n";

                 jsonResponse += "Date: " + date + "\n\n";

                 txtResponse.setText(jsonResponse);

                } catch (JSONException e) {

                    e.printStackTrace();

                    Toast.makeText(getApplicationContext(),

                            "Error: " + e.getMessage(),

                            Toast.LENGTH_LONG).show();
                }

                hidepDialog();

            }

        }, new Response.ErrorListener() {

            @Override

            public void onErrorResponse(VolleyError error) {

            Toast.makeText(getApplicationContext(),

                   error.getMessage(), Toast.LENGTH_SHORT).show();                

                hidepDialog();
            }

        });        

        AppController.getInstance().addToRequestQueue(jsonObjReq);

    }


In this method hideDialog and showDialog methods used to add progressDialog.



21 October 2014

Maven Installation guide

In this Thread i am going to how to use maven.First i will give you what is Maven.Maven is open source Building tool.it is distributed by Apache.If you really new with software development cycle i will tell why we want to use building tool.In software development cycle there are five main development cycles.Planing,Implementation,testing and documenting and Deployment and Maintenance are the development process.So when you build some product there may be bugs,errors.So you have to give the Quality output to your customer.So then you have to testing and development except most bugs fixed.So it is high cost for fixed errors and rebuild.So that's why we used building tool for make easier  our development process.Using Building tool we can test application,documentation easier.

How to install MAVEN in to windows

1 Step :
Download the maven using this url
(http://maven.apache.org/download.cgi)  and extract the zip file in any drive in your machine.

2 Step :
Download and install java in to your machine.

3 Step :
Set Path variables for java and maven.




4 Step:
Check maven is installed properly.


Thanks

Java card Helloworld Applet

This article I will describe how to create java card hello world applet.You have to have
   1.Contact or contact reader
   2.Java card
   3.Eclipse with java card development kit.


First you have to knowledge about how the APDU commands are working in java card.This is the Apdu standard format.




In my example I used CLA value as 80 and INS value as 00 and P1 and P2 are 00,00.The requested format is 80000000.


import javacard.framework.APDU;

import javacard.framework.Applet;

import javacard.framework.ISO7816;

import javacard.framework.ISOException;

import javacard.framework.Util;

public class HelloworldApplet extends Applet {

private static final byte[] helloWorld = { (byte) 'H', (byte) 'e',

(byte) 'l', (byte) 'l', (byte) 'o', (byte) ' ', (byte) 'W',

(byte) 'o', (byte) 'r', (byte) 'l', (byte) 'd', };

private static final byte HW_CLA = (byte) 0x80;

private static final byte HW_INS = (byte) 0x00;

public static void install(byte[] bArray, short bOffset, byte bLength) {

        new HelloworldApplet().register(bArray, (short) (bOffset + 1),

        bArray[bOffset]);

}
public void process(APDU apdu) {

     if (selectingApplet()) {

       return;

}

  byte[] buffer = apdu.getBuffer();

  byte CLA = (byte) (buffer[ISO7816.OFFSET_CLA] & 0xFF);

  byte INS = (byte) (buffer[ISO7816.OFFSET_INS] & 0xFF);

if (CLA != HW_CLA) {

    ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);

}

switch (INS) {

  case HW_INS:

   getHelloWorld(apdu);

   break;

  default:

   ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);

  }
             }

private void getHelloWorld(APDU apdu) {

      byte[] buffer = apdu.getBuffer();

      short length = (short) helloWorld.length;

     Util.arrayCopyNonAtomic(helloWorld, (short) 0, buffer, (short) 0,

     (short) length);

     apdu.setOutgoingAndSend((short) 0, length);

       }

}

Java Eliptic Curve Cryptography Sign/verify Example

In this Post I am going to talk about the Elliptic curve encryption.First I will tell you why we use ECC. ECC is public-key Cryptography. ECC is used for the Authentication and authorization.Mainly The structure is like this way.In here(http://www.johannes-bauer.com/compsci/ecc/) you can see very good explanation how ECC works. .First Using public key we have sign data.and then using private key we can verify data.In here we verify that compare the signing data and what are the we input data.So I used bouncy castle for ECC. In here (http://www.bouncycastle.org/latest_releases.html) You can download the bouncy castle jar and add to the Project.In here I First sign my data using Private key.Then I Verify the signing data using Public key.

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;


import java.security.PublicKey;

import java.security.SecureRandom;
import java.security.Signature;


import java.security.Security;



import java.security.interfaces.ECPublicKey;



import java.security.spec.InvalidKeySpecException;

import java.security.spec.X509EncodedKeySpec;


import org.bouncycastle.jce.ECNamedCurveTable;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;


public class PublickeyEncryption {



public static void main(String args[]) {



try {



/**

 * ECC signature sign and verify
 */
ECParameterSpec ecSpec = ECNamedCurveTable
.getParameterSpec("prime192v1");
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");


g.initialize(ecSpec, new SecureRandom());

// Genarate keypair
KeyPair pair = g.generateKeyPair();
System.out.println("Provider Name :"+BouncyCastleProvider.PROVIDER_NAME);
/**
Genarate Private and Public keys
*/
PublicKey pubKey = pair.getPublic();
PrivateKey prikey = pair.getPrivate();
byte[] inputData = new byte[] { (byte) 0x01, (byte) 0x01,
(byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01,
(byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01,
(byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01,
(byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01,
(byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01,
(byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01,
(byte) 0x01, (byte) 0x01 };
Signature sig = Signature.getInstance("ECDSA", "BC");
/**
Initialize the sign and update data to be Sign
*/
sig.initSign(prikey);
sig.update(inputData);
/**
SIGN the data using private key
*/
byte[] signatureBytes = sig.sign();
System.out.println("Sign byte arry:" + Arrays.toString(signatureBytes));
/**
Initialize the verify and update data to be Verify
*/
sig.initVerify(pubKey);
sig.update(inputData);
/**
Check verify true or False
*/
System.out.println("VERIFY :" + sig.verify(signatureBytes));
} catch (Exception e) {
e.printStackTrace();
}
}
}