Saturday, November 1, 2014

PNR Status Application

Hey!! I have developed an application to check your pnr status Have you booked any train ticket with which is not confirmed?. Then you can check it right now here.
Click here to access

API from railpnrapi paid service
Developed on Grails Platform
source code available in github

Wednesday, October 22, 2014

Convert JSON to JavaObject

An easiest approach to parse Json.
org.codehaus.jackson.map.ObjectMapper
#ObjectMapper
This mapper provides functionality for conversting between Java objects and matching JSON. It will use instances of JsonParser and JsonGenerator for implementing actual reading/writing of JSON.

We show the binding to convert JSon to JavaObject

1)student.json



{
   "studentName":"John",
   "age":"15",
   "class":10,
   "schoolDetails":{
      "schoolName":"St Xavier",
      "city":"Bangalore",
      "street":"Nice Road",
      "area":"Electronic city"
      
   },
   "studentResults":[
      {
         "sno":"1",
         "description":"Quarterly Exams",
         "marks":500,
         "grade":"A"
      },
      {
         "sno":"2",
         "description":"Half yearly Exams",
         "marks":478,
         "grade":"B"
      },
   {
         "sno":"3",
         "description":"Annual yearly Exams",
         "marks":507,
         "grade":"A"
      }
   ]
}

2)Create a class to map Json

From the above Json you should be able identify datatypes, custom objects, array/lists of objects.
 a) Create a class StudentData or it can be anything, add studentName,age,class as memeber variables.(here we have student's class. Since class
    is a keyword in java, it cannot be used as a variable, so declare it as clazz)
 b) schoolDetails is an Object in JSON , create a class StudentDetails with its member variables and add schoolDetails as a member in StudentData
    class.
 c) studentResults is an Array/List, create a class StudentResults with its members and add a list property that accepts StudentResults in
    StudentData class.
 d) If every thing is done your class should look like the below class.
 e) Since we defined class as clazz in order to map them correctly use JsonProperty annotation.
     @JsonProperty("class")
     private int clazz;



package json2obj;

import org.codehaus.jackson.annotate.JsonProperty;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: RAVI
 * Date: 23/10/14
 * Time: 9:16 AM
 * To change this template use File | Settings | File Templates.
 */
public class StudentData {
    private String studentName;
    private String age;
    @JsonProperty("class")
    private int clazz;
    private SchoolDetails schoolDetails;
    private List<StudentResults> studentResults;

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public int getClazz() {
        return clazz;
    }

    public void setClazz(int clazz) {
        this.clazz = clazz;
    }

    public SchoolDetails getSchoolDetails() {
        return schoolDetails;
    }

    public void setSchoolDetails(SchoolDetails schoolDetails) {
        this.schoolDetails = schoolDetails;
    }

    public List<StudentResults> getStudentResults() {
        return studentResults;
    }

    public void setStudentResults(List<StudentResults> studentResults) {
        this.studentResults = studentResults;
    }



    public String toString(){
        String sData = "";
        sData+= "Student Details\n===============\nStudent Name:"+studentName+" Age:"+age+" class:"+clazz+"\n";

        sData+= "School Details\n================\nSchool Name:"+schoolDetails.getSchoolName()+" City:"+schoolDetails.getCity()+" Street:"+schoolDetails.getStreet()+" Area:"+schoolDetails.getArea()+"\n";
        sData+="Student Results\n================\n";
        for(StudentResults sr:studentResults){
         sData+= "SNO:"+sr.getSno()+" Description:"+sr.getDescription()+" Marks:"+sr.getMarks()+" Grade:"+sr.getGrade()+"\n";

        }
        return  sData;
    }
}

class SchoolDetails{
    private String schoolName;
    private String city;
    private String street;
    private String area;

    public String getSchoolName() {
        return schoolName;
    }

    public void setSchoolName(String schoolName) {
        this.schoolName = schoolName;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }
}

class StudentResults{
    private String sno;
    private String description;
    private int marks;
    private String grade;

    public String getSno() {
        return sno;
    }

    public void setSno(String sno) {
        this.sno = sno;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getMarks() {
        return marks;
    }

    public void setMarks(int marks) {
        this.marks = marks;
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }
}

3)Convert JSON to Java Object

Add the following dependency
<dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
</dependency>
The following class will convert Json to Object

package json2obj;

import org.codehaus.jackson.map.ObjectMapper;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: RAVI
 * Date: 23/10/14
 * Time: 9:05 AM
 * To change this template use File | Settings | File Templates.
 */
public class ConvertJsonToObj {
    public static void main(String... args) throws IOException {
        FileReader fr = new FileReader("src/main/resources/student.json");
        BufferedReader bufferedReader = new BufferedReader(fr);

        String jsonString  = "";
         String curLine ="";
        while((curLine = bufferedReader.readLine())!=null){
              jsonString+=curLine.trim();
        }

        System.out.println(jsonString);

        ObjectMapper objectMapper = new ObjectMapper();
         StudentData sd = new StudentData();
        sd = objectMapper.readValue(jsonString,StudentData.class);

        System.out.println(sd);


    }
}

Output:

Student Details
===============
Student Name:John Age:15 class:10
School Details
================
School Name:St Xavier City:Bangalore Street:Nice Road Area:Electronic city
Student Results
================
SNO:1 Description:Quarterly Exams Marks:500 Grade:A
SNO:2 Description:Half yearly Exams Marks:478 Grade:B
SNO:3 Description:Annual yearly Exams Marks:507 Grade:A

Sunday, October 19, 2014

JAXB XML Parsing

How easy to parse an xml??? You might be having a huge xml, but still its not a matter to parse it even you don't know its structure. Now! you will see how to parse any xml using jaxb. All necessary is only a xsd. Don't worry even if you don't have it. You can create your xsd using different tools/online. If you need to create it your self you should be knowing xsd rules. Lets see an example 1)This is your xml

200
1234567890
12311
HWH DLI KLK MAI
23-12-2013

DLI
Delhi


KLK
Kalka


KLK
Kalka


DLI
Delhi

1A
3
N


1
CNF ,GN
CNF


2
CNF ,GN
CNF


3
CNF ,GN
CNF





2) Generate xsd using eclipse/tools/online/yourself... 3) Generate jaxb classes. a)Create a maven based project b)add the following lines to your pom.xml(its a plugin to convert your xsd schema to corresponding jaxb classes.)

<build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.jvnet.jaxb2.maven2</groupId>
                <artifactId>maven-jaxb2-plugin</artifactId>
                <version>0.8.3</version>
                <configuration>
                   <schemaDirectory>src/main/resources/schema</schemaDirectory>
                   <bindingDirectory>src/main/resources/schema</bindingDirectory>
                   <generatePackage>org.pnr</generatePackage>
                   <strict>false</strict>
                   <extension>true</extension>
                   <plugins>
                       <plugin>
                           <groupId>org.jvnet.jaxb2_commons</groupId>
                           <artifactId>jaxb2-basics</artifactId>
                           <version>0.6.2</version>
                       </plugin>
                       <plugin>
                           <groupId>org.jvnet.jaxb2_commons</groupId>
                           <artifactId>jaxb2-basics-annotate</artifactId>
                           <version>0.6.2</version>
                       </plugin>
                   </plugins>
                   <args>
                       <arg>-Xannotate</arg>
                       <arg>-XtoString</arg>
                   </args>
                </configuration>
                <executions>
                    <execution>
                        <id>generate</id>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.jvnet.jaxb2_commons</groupId>
            <artifactId>jaxb2-basics-runtime</artifactId>
            <version>0.6.2</version>
        </dependency>
    </dependencies>

       
4) Create a directory with name schema in your resource folder in your project(it can be any place, but specify the location of xsd in your pom.xml) Place the xsd file in resources/schema folder for which jaxb classes should be generated.

5) Build the project using command mvn clean install -e 6) you can see all the generated files in target/generated-sources/xjc path present in their packages, specified in pom.xml i.e org.pnr 7)Place the generated ObjectFactory.java and Xml.java in your class path. Or directly place them in your package structure. 8)Finally it's time to see jaxb parsing.
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;


import pnr.Xml;
import pnr.ObjectFactory;
/**
 * Created with IntelliJ IDEA.
 * User: RAVI
 * Date: 11/10/14
 * Time: 12:10 PM
 * To change this template use File | Settings | File Templates.
 */
public class TestXmlToJaxb {

    public static void main(String args[]){
         Converter c = new Converter();
        c.doConversion();
    }
}

class Converter{
    public void doConversion(){
                
               String xmlString = "" +
                                  "200" +
                                  "1234567890" +
                                  "12311" +
                                  "HWH DLI KLK MAI" +
                                  "23-12-2013" +
                                  "" +
                                  "DLI" +
                                  "Delhi" +
                                  "" +
                                  "" +
                                  "KLK" +
                                  "Kalka" +
                                  "" +
                                  "" +
                                  "KLK" +
                                  "Kalka" +
                                  "" +
                                  "" +
                                  "DLI" +
                                  "Delhi" +
                                  "" +
                                  "1A" +
                                  "3" +
                                  "N" +
                                  "" +
                                  "" +
                                  "1" +
                                  "CNF ,GN" +
                                  "CNF" +
                                  "" +
                                  "" +
                                  "2" +
                                  "CNF ,GN" +
                                  "CNF" +
                                  "" +
                                  "" +
                                  "3" +
                                  "CNF ,GN" +
                                  "CNF" +
                                  "" +
                                  "" +
                                  "" +
                                  "";
    try{

        JAXBContext jaxbContext = JAXBContext.newInstance(Xml.class);

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        Xml xmll = (Xml) jaxbUnmarshaller.unmarshal(new StringReader(xmlString));
        System.out.println(xmll);
        System.out.println(xmll.getResponseCode());
        Xml.Passengers pass = xmll.getPassengers();
        System.out.println(pass.getPassenger().get(1));

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

    }
}
Output:
pnr.Xml@311671b2[responseCode=200, pnr=1234567890, trainNum=12311, trainName=HWH DLI KLK MAI, doj=23-12-2013, fromStation=pnr.Xml$FromStation@7d2452e8[code=DLI, name=Delhi], toStation=pnr.Xml$ToStation@5bbf3d87[code=KLK, name=Kalka], reservationUpto=pnr.Xml$ReservationUpto@6860991f[code=KLK, name=Kalka],

boardingPoint=pnr.Xml$BoardingPoint@1de4f7c2[code=DLI, name=Delhi], clazz=1A, noOfPassengers=3, chartPrepared=N, 

passengers=pnr.Xml$Passengers@2345f0e3[passenger={pnr.Xml$Passengers$Passenger@44c9d92c[sr=1, bookingStatus=CNF ,GN, currentStatus=CNF],pnr.Xml$Passengers$Passenger@1fd0fafc[sr=2, bookingStatus=CNF ,GN, currentStatus=CNF],pnr.Xml$Passengers$Passenger@510dc6b5[sr=3, bookingStatus=CNF ,GN, currentStatus=CNF]}], error=]
200
pnr.Xml$Passengers$Passenger@1fd0fafc[sr=2, bookingStatus=CNF ,GN, currentStatus=CNF]

Tuesday, September 30, 2014

Android Battery Manager to display charging status

Android application to display battery charging percentage. This application display's charging percentage in notification area, and gets updated whenever battery is discharged. Source code available in github at https://github.com/raviteja548/battery-manager
Download Source

Tuesday, August 19, 2014

SVN Installation, Backup and Restore

Simple installation of svn. It says how to restore a backup and restore it. You can use the backup file to restore whenever svn is installed freshly.

Command to backup Repository:

svnadmin dump "repo location" > "backup file" (do not include quotations)
Example:
c:>svnadmin dump c:\svnrepo > svnbackup_file_name


Command to Restore repository:


svnadmin load "svn location where repo is created" < "svn backup file name"
Example:
c:>svnadmin load c:\svnrepo < svnbackup_file_name