Friday, 30 September 2016

Ant Build File Creation in Java Using Apache Ant

How to create apache ant build file in project

  • If you are using Eclipse  open the eclipse right click then select Export and select "Ant Build File" then after that select your project where you want to create build file then finish 

 So it will create build.xml for us . the minimal code to create jar using apache ant build is

<?xml version="1.0" encoding="UTF-8"?>
<project name="Example" default="makejar" basedir=".">
   
  <target name ="makejar" description="Jar File Creation">
    <jar jarfile="Test.jar" includes="*.class" basedir="bin"/>
      <echo>******** Jars Files Create Inside Project ********** </echo>
  </target>
</project>

Monday, 26 September 2016

Class Array JSON Creation in Java

How to create Class level Array and dynamic generate JSON  using Jackson API


package com.test.rest;

import java.lang.reflect.Array;

import com.bean.Animal;
import com.bean.Employee;
import com.bean.Student;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 *
 * @author anand
 *
 */
public class JsonUtility {
    public ObjectMapper mapper;
    public String jsonString;

    /*
     * This method will Used to Convert ClassObject to JSON  and
     * return as a form of JSON as a String
     */
   
   
    public String ConvetObjectArrayToJSON(Object [] array){
             mapper = new ObjectMapper();
        String jsonArray=null;
        System.out.println(array[i]);
        try{
        for(int i=0;i<array.length;i++){
            System.out.println(array[i].getClass());
           
            jsonString = mapper.writeValueAsString(array[i]);
            jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(array[i]);
            System.out.println(array[i].getClass()+"=="+jsonString);
        }
        }catch(Exception e){
            e.printStackTrace();
        }
       
       
        return jsonArray;
    }
   
    public static void main(String []args){
       
       
        Student student=new Student();
        student.setStudentname("Anand");
        student.setStudentPlace("Bangalore");
        student.setStudentResult("Ok");
       
       
        Employee emp= new Employee();
        emp.setEmployeeName("Antrish");
        emp.setEmployeeLocation("Chennai");
        emp.setEmployeeResult("Capgimini");
       
       
        Animal animal=new Animal();
        animal.setAnimalName("Dog");
        animal.setAnimalPlace("Mumbai");
        animal.setAnimalResult("Eat");
       
       
        Object[] object=new Object[]{student,emp,animal};
        JsonUtility  jsonutility=new JsonUtility();
       
        jsonutility.ConvertObjecttoJSOn(emp);
        jsonutility.ConvetObjectArrayToJSON(object);
          
       
    }
   
}

======================
POJO Classes are

Employee.java

    private String employeeName;
    private String employeeLocation;
    private String employeeResult;

//Setters and Getters


Student.java

    private String studentname;
    private String studentPlace;
    private String studentResult;

//Setters and Getters


    private String animalName;
    private String animalPlace;
    private String animalResult;

// Setters and Getters


=======Output ====


com.bean.Student@17550481
class com.bean.Student
class com.bean.Student=={
  "studentname" : "Anand",
  "studentPlace" : "Bangalore",
  "studentResult" : "Ok"
}
class com.bean.Employee
class com.bean.Employee=={
  "employeeName" : "Antrish",
  "employeeLocation" : "Chennai",
  "employeeResult" : "Capgimini"
}
class com.bean.Animal
class com.bean.Animal=={
  "animalName" : "Dog",
  "animalPlace" : "Mumbai",
  "animalResult" : "Eat"
}







Wednesday, 21 September 2016

Rest API Post Example With Client in Java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rest;

/**
 *
 * @author ananddw
 */
public class Accounts {
   
    String accountid;
    String accountname;
    String accountholdername;
    String accountholderlocation;

    public String getAccountid() {
        return accountid;
    }

    public void setAccountid(String accountid) {
        this.accountid = accountid;
    }

    public String getAccountname() {
        return accountname;
    }

    public void setAccountname(String accountname) {
        this.accountname = accountname;
    }

    public String getAccountholdername() {
        return accountholdername;
    }

    public void setAccountholdername(String accountholdername) {
        this.accountholdername = accountholdername;
    }

    public String getAccountholderlocation() {
        return accountholderlocation;
    }

    public void setAccountholderlocation(String accountholderlocation) {
        this.accountholderlocation = accountholderlocation;
    }
   
   
    @Override
    public String toString() {
        return "Product [accountname=" + accountname + ", accountholderlocation=" + accountholderlocation + ", accountholdername=" + accountholdername + ", accountid=" + accountid +  "]";
    }
   
   
}









=======================
@Path("/accounts")
public class JSONService {
@POST
    @Path("/account")
    @Consumes("application/json")
    public Response getAccountsInJSON(Accounts account) {

        String result ="Account created : "+account;
       
        return Response.status(201).entity(result).build();

    }
}
=======================

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rest;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 *
 * @author ananddw
 */
public class JSONUtility {

    public static void main(String[] args) {
        JSONUtility obj = new JSONUtility();
        obj.run();
    }

    public String run() {
        ObjectMapper mapper = new ObjectMapper();
        Accounts staff = createDummyObject();
        String jsonInString = null;
        try {
            jsonInString = mapper.writeValueAsString(staff);
            System.out.println(jsonInString);
            String preetyJSON = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonInString;
    }

    public Accounts createDummyObject() {

        Accounts staff = new Accounts();

        staff.setAccountholderlocation("Bangalore");
        staff.setAccountholdername("Anand");
        staff.setAccountid("Anand-MSPYL");
        staff.setAccountname("HDFC");

        return staff;

    }

}

====================================

 /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 *
 * @author Admin
 */
public class AccountClientPost {
     public static void main(String[] args) {

        try {

            URL url = new URL(
                    "http://localhost:8084/RESTAPI/rest/accounts/account");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
             JSONUtility obj = new JSONUtility();
              String input= obj.run();
          

            OutputStream os = conn.getOutputStream();
            os.write(input.getBytes());
            os.flush();

            if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {

                System.out.println(output);
            }

            conn.disconnect();

        } catch (MalformedURLException e) {

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

            e.printStackTrace();

        }

    }
}



===============web.xml ==============

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xmlns="http://java.sun.com/xml/ns/javaee" 
   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>User Management</display-name>
   <servlet>
      <servlet-name>Jersey RESTful Application</servlet-name>
      <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
         <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.rest</param-value>
         </init-param>
      </servlet>
   <servlet-mapping>
   <servlet-name>Jersey RESTful Application</servlet-name>
      <url-pattern>/rest/*</url-pattern>
   </servlet-mapping>  
</web-app>


Please uploaded  jersay and Jackson jars .

Happy to help Thanks

Thursday, 15 September 2016

Rest API Example in java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.test;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Admin
 */
@XmlRootElement(name = "registration")
public class StudentRegistration {

    String name;
    int roolnumber;
    String location;

    @XmlElement
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlElement
    public String getLocation() {
        return location;
    }

    public int getRoolnumber() {
        return roolnumber;
    }

    @XmlAttribute
    public void setRoolnumber(int roolnumber) {
        this.roolnumber = roolnumber;
    }

    public void setLocation(String location) {
        this.location = location;
    }

}

====================
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.test;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.tutorialspoint.StudentRegistration;

/**
 *
 * @author Admin
 */

@Path("/students")
public class StudentsREST {

    @GET
    @Path("/{roolnumber}/{name}/{location}")
    @Produces(MediaType.APPLICATION_XML)
    public StudentRegistration getStudents(@PathParam("roolnumber") int roolnumber,@PathParam("name")String name, @PathParam("location")String location) {

        StudentRegistration register = new StudentRegistration();

        register.setName(name);
        register.setLocation(location);
        register.setRoolnumber(roolnumber);


        return register;

    }

}

===============web.xml ==============

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://java.sun.com/xml/ns/javaee"
   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>User Management</display-name>
   <servlet>
      <servlet-name>Jersey RESTful Application</servlet-name>
      <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
         <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.test</param-value>
         </init-param>
      </servlet>
   <servlet-mapping>
   <servlet-name>Jersey RESTful Application</servlet-name>
      <url-pattern>/rest/*</url-pattern>
   </servlet-mapping> 
</web-app>

PS: Add all the required Jars




Tuesday, 6 September 2016

How to disable back button after Login in Java

Here is the simple programme when you login with your application it will disable the back button in browser

index.jsp

<%--
    Document   : index
    Created on : Sep 6, 2016, 1:17:40 PM
    Author     : ananddw
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Login Page </title>
    </head>
    <body>
        <form action="sucess.jsp" method="post">
        <table>
            <tr>
                <td>UserName</td>
                <td><input type="text" name="uname" id="uname"/></td>
            </tr>
           
            <tr>
                <td>Password</td>
                <td><input type="password" name="pword" id="pword"/></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Login"/></td>
            </tr>
           
        </table>
            </form>
    </body>
</html>

sucess.jsp 

<%--
    Document   : sucess
    Created on : Sep 6, 2016, 1:24:13 PM
    Author     : ananddw
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <%
        String username = request.getParameter("uname");
        String password = request.getParameter("pword");
        System.out.println("User Name is " + username + "\t" + "and password is " + password);
    %>
    <body onload="preventBack()">
    <center>
        Hi <%=username%> welcome in Home Page You can't go back
    </center>
</body>
<script>
    history.pushState(null, null, document.title);
    window.addEventListener('popstate', function () {
        history.pushState(null, null, document.title);
    });

</script>
</html>


To Download Source Code or War Click here https://drive.google.com/drive/folders/0B5SLW_aQO5FiSFFnX1V4QzlzM00

Map class field to map

 import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class AutogeneratedClassMapper {     public static M...