Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

20 October 2017

Spring Boot Exception Handling





Long time I couldn't have time to write in my blog. So this time I am going to talk about spring boot exception handling with error code mapping. This blog post helpful to who are new to spring boot. The first thing is define error codes.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public enum ApiError {
    
    INVALID_REQUEST_PARAMETERS("E10001", "Invalid request parameters"),

    PRODUCT_NOT_FOUND("E1001", "Product not found");

    private final String errorCode;
    private final String errorMessage;

    ApiError(String errorCode, String errorMessage) {
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }
}


The next task is write  runtime exception type based on HTTP status.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import io.apptizer.api.errors.codes.ApiError;

public class ResourceNotFoundException extends RuntimeException {

    private ApiError apiErrors;

    public ResourceNotFoundException(ApiError apiErrors, String message) {
        super(message);
        this.apiErrors = apiErrors;
    }

    public ApiErrors getApiErrors() {
        return apiErrors;
    }

    public void setApiErrors(ApiErrors apiErrors) {
        this.apiErrors = apiErrors;
    }
}

And final task is write exception mapper handler.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class ExceptionMapperHandler {
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorInfo> resourceNotFound(ResourceNotFoundException ex) {
        ErrorInfo errorInfo = new ErrorInfo(ex.getApiErrors().getErrorCode(), ex.getMessage());
        return new ResponseEntity<>(errorInfo, HttpStatus.NOT_FOUND);
    }
}

then in your rest service you can throw exception with error code mapping.

throw new ResourceNotFoundException(ApiError.PRODUCT_NOT_FOUND, "Product Task Not Found");

And that is it.If you have any better way please put your comments.

06 November 2016

Easy Way to Create wrapper for Java Project

Most of the articles I have written for android related development issues. I thought need to write something new for java and spring related article.when I was in university when we running project what wed did was always run the project using IDE. But after joining to industry we know that we have to write executable file to run project in different environments. Let's say customer server may be windows, linux or mac .Then we have to create executable file which run in all platforms. If the project is simple what we can do is create executable jar and give to customer.

 But if the project contents configuration files this approach is not good.  Then we have to use better way to bundle executable files. So in this tutorial I will show you to how to create wrapper for java project but make sure you have to use maven.

First you have to add following property to pom.xml

1
2
3
<properties>
    <wrapper.location>${project.build.directory}/generated-resources/appassembler/jsw/#wrapper-name</wrapper.location>
</properties>

Then need to add following plugins to pom.xml and make sure change the main class and wrapper name.

  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
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
<build>
<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <executions>
            <execution>
                <id>copy-resources</id>
                <phase>process-classes</phase>
                <goals>
                    <goal>copy-resources</goal>
                </goals>
                <configuration>
                    <outputDirectory>${project.build.directory}/conf</outputDirectory>
                    <resources>
                        <resource>
                            <directory>${project.basedir}/src/main/resources</directory>
                        </resource>
                    </resources>
                </configuration>
            </execution>
        </executions>
    </plugin>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
            <excludes>
                <exclude>**/*.yml</exclude>
                <exclude>**/*.txt</exclude>
            </excludes>
        </configuration>
    </plugin>
    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>appassembler-maven-plugin</artifactId>
        <version>1.10</version>
        <executions>
            <execution>
                <id>generate-jsw-scripts</id>
                <phase>package</phase>
                <goals>
                    <goal>generate-daemons</goal>
                </goals>
                <configuration>
                    <repositoryLayout>flat</repositoryLayout>
                    <configurationDirectory>conf</configurationDirectory>
                    <daemons>
                        <daemon>
                            <id>#wrapper-name</id>
                            <wrapperMainClass>org.tanukisoftware.wrapper.WrapperSimpleApp</wrapperMainClass>
                            <mainClass>#Main-class</mainClass>
                            <commandLineArguments>
                                <commandLineArgument>start</commandLineArgument>
                            </commandLineArguments>
                            <platforms>
                                <platform>jsw</platform>
                            </platforms>
                            <generatorConfigurations>
                                <generatorConfiguration>
                                    <generator>jsw</generator>
                                    <configuration>
                                        <property>
                                            <name>wrapper.java.additional.1</name>
                                            <value>-Xloggc:logs/gclog</value>
                                        </property>
                                        <property>
                                            <name>wrapper.java.additional.2</name>
                                            <value>-XX:MaxDirectMemorySize=256M</value>
                                        </property>
                                        <property>
                                            <name>configuration.directory.in.classpath.first</name>
                                            <value>conf</value>
                                        </property>
                                        <property>
                                            <name>set.default.REPO_DIR</name>
                                            <value>lib</value>
                                        </property>
                                        <property>
                                            <name>wrapper.logfile</name>
                                            <value>logs/wrapper.log</value>
                                        </property>
                                    </configuration>
                                    <includes>
                                        <include>linux-x86-32</include>
                                        <include>linux-x86-64</include>
                                    </includes>
                                </generatorConfiguration>
                            </generatorConfigurations>
                        </daemon>
                    </daemons>
                </configuration>
            </execution>
        </executions>
    </plugin>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-antrun-plugin</artifactId>
        <version>1.6</version>
        <executions>
            <execution>
                <id>make-log-dir</id>
                <phase>package</phase>
                <configuration>
                    <tasks>
                        <mkdir dir="${wrapper.location}/logs" />
                        <copy todir="${wrapper.location}/conf">
                            <fileset dir="target/conf" />
                        </copy>
                        <chmod dir="${wrapper.location}/bin" includes="**/*" perm="0755" />
                    </tasks>
                </configuration>
                <goals>
                    <goal>run</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
    <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>2.5.3</version>
        <configuration>
            <descriptor>src/assembly/dep.xml</descriptor>
            <finalName>#app-name</finalName>
        </configuration>
        <executions>
            <execution>
                <id>create-archive</id>
                <phase>package</phase>
                <goals>
                    <goal>single</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
</plugins>
</build>




And final Step is need to add assembly file to your project. Create assembly folder inside src folder and put the following dep.xml file in to it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"          xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<id>bin</id>
<formats>
    <format>zip</format>
</formats>
<fileSets>
    <fileSet>
        <directory>${wrapper.location}</directory>
        <outputDirectory>/</outputDirectory>
    </fileSet>
</fileSets>
</assembly>

And now you can see the wrapper-name.zip file in target folder. after extracting it inside the bin folder four executable files are there and bat file for windows and wrapper for linux . All the dependency jar files are under lib folder. and configurations in conf folder. Now in this way we can easily handle projects. Hope now you will learn something from my tutorial.

12 December 2015

RESTful web service In 5 Minutes using DropWizard

These days I am Learning new framework called "Dropwizard".So I thought I want to share what I learn from Dropwizard. Before going to what is Dropwizard I want to tell some difficulties when building rest server application.When I was in university I don't know how to implement Restful webservice and i thought it was difficult task even for  Testing purpose.Then I learn apache CXF web server and the problem was there are lot of dependencies need to create rest server. Ex:-Apache Cxf,Jackson serialization library,log4j for logging ,Junit for Testing And other libraries.So Even for me to hard to remember all the dependency libraries. So the Solution is Dropwizard. Dropwizard is Lightweight framework which have all the dependencies in one place. Dropwizard also support to expand to your project in layered structure such as api/db/client.

What is Drop-wizard

Drop wizard is simply All the listed libraries in one package.



  • metrics
  • jetty
  • jersey
  • jackson
  • jdbi
  • hibernate
  • logback
  • mustache
  • freemarker



Start Using Maven archetype

1
2
mvn archetype:generate -DgroupId=dec.mchoice.tech.talk -DartifactId=Sample-dw-app -Dname=SampleApplication -Dpackage=dev.mchoice.tech.talk
dev.innova.drp -DarchetypeGroupId=io.dropwizard.archetypes -DarchetypeArtifactId=java-simple -DinteractiveMode=false

After creating project it will create this kind of project structure.


Biggest advantage of use maven archetype no need to configure any dependencies or plugin in POM.xml file and it will generate executable jar file .  Next step is create Rest API end point.


 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
@Path("/student")

public class StudentManagement {
    @POST

    @Timed

    @Path("/save")

    @Produces(MediaType.APPLICATION_JSON)

    @Consumes({MediaType.APPLICATION_JSON})

    public Response addPerson(Student student) {

        Map<String, Object> response = new HashMap<>();

        response.put("statusCode", "S1000");

        response.put("description", "Successfully added Student");

        return Response.ok(response).build();

    }

}
And then you have to register your rest API in drop wizard configuration.


1
2
3
4
5
6
7
8
@Override
    public void run(final SampleApplicationConfiguration configuration,

                    final Environment environment) {

        environment.jersey().register(new StudentManagement());

    }
And now All the API related stuff are finished.So you need to run your Application.First go to target folder in project and run


1
java -jar Sample-dw-app-1.0-SNAPSHOT.jar server

After running it will start in 8080 port(application port) and there is another port 8081 (Admin port ).
Next tutorial we will discuss how to change the default configurations and what are the usages of admin port.



Then you can use curl request or postmen to send request and check the Rest API.

21 November 2015

Android Bluetooth tutorial 1

As a first step in here i have discuss how to check android enable or not and make Discoverable  in android.Before You have to add permissions in your manifest file.

    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.BLUETOOTH" />

In your Android app make sure check the android enable or not in onStart method.Before that you have to add following codes in your onCreate method.

  private BluetoothAdapter mBluetoothAdapter = null;
 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

If Your android phone doesn't support Bluetooth it will close.

 if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }

when calling to onStart app add the following code.

@Override
    public void onStart() {
        super.onStart();
         if (!mBluetoothAdapter.isEnabled()) {

            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
       
           }
           }

How to make discoverable. It also start an intent.The time duration you can increase.This will need for scan devices.


 public  void ensureDiscoverable() {
      
        if (mBluetoothAdapter.getScanMode() !=
            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }

    }



04 October 2015

Android Google cloud messaging Test server

Java GCM Testing Server

Today I will share how to create java Testing Application for send android GCM notifications to android client.There are lot of examples how to create android GCM client application but for testing the notification flow you need server.But I couldn't found any good example how to create java server.So I found Library for send notifications so i used that library and create simple swing application to send notification.



Sample Code

This is the code-sample which I have already pushed in to github location(https://github.com/sajith4u/android-gsm-sample).


  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
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package dev.innova.sajith;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;


public class MainClass {

    public static void main(String[] args) {
        System.out.println("starting gcm-server Application");
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                init();
            }
        });

    }

    /**
     *  Send Notification to server
     * @param apiKey
     * @param registrationId
     * @param title
     * @param messagetext
     * @return
     */
    public static String send(String apiKey, String registrationId,String title,String messagetext) {
        Sender sender = new Sender(apiKey);
        Result result = null;
        Message message = new Message.Builder()
                .addData("message",messagetext)
                .addData("title", title)
                .build();
        try {
            result = sender.send(message, registrationId, 2);
            System.out.println("Result : " + result.getMessageId());
            System.out.println("Result ErrorCode : " + result.getErrorCodeName());
            System.out.println("Result : " + result.getCanonicalRegistrationId());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    /**
     * Initialize the Swing form
     */
    public static void init() {
        JFrame frame = new JFrame("Notification Sender");
        frame.setSize(600, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        frame.add(panel);
        placeComponents(panel);

        frame.setVisible(true);
    }

    /**
     *  Add Items to Swing form
     * @param panel
     */
    private static void placeComponents(JPanel panel) {

        panel.setLayout(null);

        JLabel apiKeyLabel = new JLabel("ApiKey");
        apiKeyLabel.setBounds(50, 20, 100, 40);
        panel.add(apiKeyLabel);

       final JTextField apiKeyText = new JTextField(20);
        apiKeyText.setBounds(160, 20, 400, 40);
        panel.add(apiKeyText);

        JLabel registrationLabel = new JLabel("Registraion ID");
        registrationLabel.setBounds(50, 70, 100, 40);
        panel.add(registrationLabel);

        final JTextField registrationText = new JTextField(20);
        registrationText.setBounds(160, 70, 400, 40);
        panel.add(registrationText);

        JLabel titleLabel = new JLabel("Title :");
        titleLabel.setBounds(50, 120, 100, 40);
        panel.add(titleLabel);

        final JTextField titleText = new JTextField(20);
        titleText.setBounds(160, 120, 400, 40);
        panel.add(titleText);

        JLabel messageLabel = new JLabel("Message :");
        messageLabel.setBounds(50, 170, 100, 40);
        panel.add(messageLabel);

        final JTextField messageText = new JTextField(20);
        messageText.setBounds(160, 170, 400, 40);
        panel.add(messageText);

        JButton resetButton = new JButton("Reset");
        resetButton.setBounds(50, 220, 120, 40);
        panel.add(resetButton);

        JButton sendNotification = new JButton("Send");
        sendNotification.setBounds(250, 220, 120, 40);
        panel.add(sendNotification);

        final JLabel statusLabel = new JLabel("status :");
        statusLabel.setBounds(50, 270, 400, 100);
        panel.add(statusLabel);

        sendNotification.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusLabel.setText("");
                String message = messageText.getText();
                String apiKey = apiKeyText.getText();
                String registrationKey = registrationText.getText();
                String titleMessage = titleText.getText();
                if((registrationKey.equals("")||registrationKey.equals(null))||(apiKey.equals("")||apiKey.equals(null))||(message.equals("")||message.equals(null))){
                    statusLabel.setText("Please Fill the above three Fields");
                }else {
                    statusLabel.setText("sending message ...........");
                    String response = send(apiKey,registrationKey,titleMessage,message);
                    statusLabel.setText(response);
                }

            }
        });

        resetButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusLabel.setText("");
                messageText.setText("");
                apiKeyText.setText("");
                registrationText.setText("");
                titleText.setText("");
            }
        });

    }


}

For use this application you need API key which provided when creating application in Google could platform and registration Id.In the next post I will share simple android client application and how to test using this server.

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