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

Saturday, 20 August 2016

How to Set Multiple data and retrive Using Generic list and Comparator

package com.AddMultiple;
import java.util.*;
/**
 *
 * @author Ananddw
 *
 */
public class Mutiple implements Comparable<Mutiple>{
   
    private String name;
    private String age;
    private String location;
   
   
   
    @Override
    public int compareTo(Mutiple o) {
        return name.compareTo(o.name);
    }
   
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
   
    public static void main(String[]args){
       
        List<Mutiple>list = new ArrayList<Mutiple>();
        for(int i=0;i<3;i++){
           
            Mutiple mutiple =new Mutiple();
            if(i==0){
            mutiple.setName("Anand");
            mutiple.setAge("24");
            mutiple.setLocation("Bangalore");
            }
           
            if(i==1){
            mutiple.setName("Ajeet");
            mutiple.setAge("24");
            mutiple.setLocation("Pune");
            }
            if(i==2){
            mutiple.setName("Antrish");
            mutiple.setAge("24");
            mutiple.setLocation("Chennai");
            }
           
            list.add(mutiple);
           
        }
       
        for(Mutiple mutlist:list){
            System.out.println("==>"+mutlist.getName()+"\t"+mutlist.getAge()+"\t"+mutlist.getLocation());
           
        }
    }
}


++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
O/P
==>Anand    24    Bangalore
==>Ajeet    24    Pune
==>Antrish    24    Chennai

Tuesday, 16 August 2016

How to Get Checked Row Data Using Java Script

                                                                                                                                                                                  <!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table border="1">
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td>Ramesh Raman</td>
<td>5000</td>
<td><input type="checkbox" name="lineitemsCheckBox" id="lineitemsCheckBox" value="Anand"/> </td>
</tr>
<tr>
<td>Shabbir Hussein</td>
<td>7000</td>
<td><input type="checkbox" name="lineitemsCheckBox" id="lineitemsCheckBox" value="Ajeet"/> </td>
</tr>

<tr>
<td>Shabbir Hussein</td>
<td>8</td>
<td><input type="checkbox" name="lineitemsCheckBox" id="lineitemsCheckBox" value="Antrish bhai"/> </td>
</tr>
<tr>

<td>Shabbir Hussein</td>
<td>9</td>
<td><input type="checkbox" name="lineitemsCheckBox" id="lineitemsCheckBox" value="Test"/> </td>
</tr>
</table>

<input type="submit" onclick="Run()">

<script type="text/javascript">
function  Run(){
var lineitemscheckbox = document.getElementsByName('lineitemsCheckBox');
for (var i = 0, len = lineitemscheckbox.length; i < len; i++) {
        if (lineitemscheckbox[i].checked) {
            //alert("checked " + lineitemscheckbox[i].value);
            //lineitemskey[i] = lineitemscheckbox[i].value;
            temp = lineitemscheckbox[i].value;
         // alert("===>"+temp);
 }
 }
}
</script>


</body>
</html>  
<%--In Dymanic value you can passit Like
<input type='checkbox' name='lineitemsCheckBox' id='lineitemsCheckBox' value='"+finalMessage+ "'/>
-->

Sunday, 31 July 2016

Velocity Template Example in Java

Velocity is a simple to use, open source web framework designed to be used as the view component of an MVC architecture. 
..
The main advantage of using Velocity over JSP is that Velocity is simple to use. The Velocity Template Language (VTL) is so constrained in its capabilities that it helps to enforce separation of business logic from the view.  You won't see any Java classes in a Velocity template (an HTML document with some Velocity placeholders). 

.
Add Three Jars : apache-commons-lang.jar , apache-velocity-velocity-1.5.jar , org.apache.commons.collections.jar




/*
 * 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 jaxb;

import java.io.StringWriter;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

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

    public static void main(String[] args)
            throws Exception {
        /*
         *   first, get and initialize an engine
         */

        VelocityEngine ve = new VelocityEngine();
        ve.init();

        /*
         *   organize our data
         */
        ArrayList list = new ArrayList();
        Map map = new HashMap();

        map.put("name", "Anand");
        map.put("salary", "100.00");
        list.add(map);

        map = new HashMap();
        map.put("name", "Antrish");
        map.put("salary", "600.40");
        list.add(map);

        map = new HashMap();
        map.put("name", "Ajeet");
        map.put("salary", "500.00");
        list.add(map);

        /*
         *  add that list to a VelocityContext
         */
        VelocityContext context = new VelocityContext();
        context.put("emplist", list);

        /*
         *   get the Template 
         */
        Template t = ve.getTemplate("test_html.vm");

        /*
         *  now render the template into a Writer, here
         *  a StringWriter
         */
        StringWriter writer = new StringWriter();

        t.merge(context, writer);

        /*
         *  use the output in the body of your emails
         */
        System.out.println(writer.toString());
    }
}


==============test_html.vm=====


  <HTML>
    <HEAD>
      <TITLE>Employee details</TITLE>
    </HEAD>


    <BODY>
      <CENTER>
      <B>$emplist.size() Employee</B>
     
      <BR/>
      This is an email generated by velocity
      <BR/>
      This month only, choose from :
   
      #set( $count = 1 ) 
      <TABLE>
        #foreach( $list in $emplist )
          <TR>
            <TD>$count</TD>
            <TD>$list.name</TD>
            <TD>$list.salary</TD>
          </TR>
          #set( $count = $count + 1 )
        #end
      </TABLE>
     
   
      </CENTER>

    </BODY>
  </HTML>
 

Thursday, 14 July 2016

What is difference between Vector and ArrayList in Java?

  • One of the important interview question in java specially from Experience candidate
Vector :-

         /*
         * Vector is synchronized and thread-safe.
         * Performance wise slower then ArrayList.
         * One Thread is running at a time.
         * Once thread got completed it gives lock to other thread
         * Thread Safe
         */


 ArrayList :-
       /*
         * ArrayList is not synchronized nor thread-safe.
         * Performance wise faster then Vector.
         * multiple Threads is running at a time.
         * Not Thread Safe
         */


Programme



/*
 * 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 highleveljava;

import java.util.*;

/**
 *
 * @author Admin
 */
public class ArrayListandVector {

    public Vector vector;
    public List list;
    public String fname = "Ajeet";
    public String tname = "Antrish";
    public String lname = "Anand";

    public void compareALVC() {
        vector = new Vector();
        /*
         Add Some Data into Vector
         */

        vector.add(fname);
        vector.add(tname);
        vector.add(lname);

        System.out.println("Vector data is " + vector);

        /*
         * Vector is synchronized and thread-safe.
         * Performance wise slower then ArrayList.
         * One Thread is running at a time.
         * Once thread got completed it gives lock to other thread
         * Thread Safe
         */
        list = new ArrayList();
        /*
         Add Some Data into ArrayList
         */
        list.add(fname);
        list.add(tname);
        list.add(lname);

        System.out.println("List data is " + list);


        /*
         * ArrayList is not synchronized nor thread-safe.
         * Performance wise faster then Vector.
         * multiple Threads is running at a time.
         * Not Thread Safe
         */
    }

    public static void main(String[] args) {

        ArrayListandVector classobject = new ArrayListandVector();
        classobject.compareALVC();
    }

}
 

Map class field to map

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