Web Services



Jars Required:
----------------
asm-3.3.1jar
jersey-bundle-1.14.jar
servlet-api.jar
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>RestfuleWebServiceDemoAppl</display-name>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.hcl.bean.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hell</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer  
        </servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/order/*</url-pattern>
</servlet-mapping>

</web-app>

Employee.java
----------------------
package com.hcl.bean;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="employee")
public class Employee {

private String employeeId;
private String employeeName;
private String jobType;
private String address;
private Long salary;

//setters and getters

}
===========================
MyServlet.java
-------------------------

package com.hcl.bean;



import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class MyServlet implements Servlet{

@Override
public void destroy() {
// TODO Auto-generated method stub
}

@Override
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}

@Override
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}

@Override
public void init(ServletConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}

@Override
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
System.out.println("Hello World");
}

}
=====================
PostController.java
-----------------------
package com.hcl.controller;

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

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBElement;

import com.hcl.bean.Employee;

@Path("/postwebservice")
public class PostController {

private static Map<String, Employee> employees = new HashMap<String, Employee>();

static {

System.out.println("inside static block");
Employee employee1 = new Employee();
employee1.setEmployeeId("11111");
employee1.setEmployeeName("Dineh Rajput");
employee1.setJobType("Sr.Software Engineer");
employee1.setSalary(70000l);
employee1.setAddress("Noida");
employees.put(employee1.getEmployeeId(), employee1);

Employee employee2 = new Employee();
employee2.setEmployeeId("22222");
employee2.setEmployeeName("Abhishek");
employee2.setJobType("Marketing");
employee2.setSalary(50000l);
employee2.setAddress("New Delhi");
employees.put(employee2.getEmployeeId(), employee2);
Employee employee3 = new Employee();
employee3.setEmployeeId("333333");
employee3.setEmployeeName("Tipu Swain");
employee3.setJobType("SR Programmer Manager");
employee3.setSalary(60000l);
employee3.setAddress("BBSR");
employees.put(employee3.getEmployeeId(), employee3);

}
@POST
@Path("/delete/{id}")
@Produces("application/xml")
public List<Employee> deleteEmployeeById(@PathParam("id") String empId){
System.out.println("Inside delete() method");
boolean flag = employees.containsKey(empId);
employees.remove(empId);
return new ArrayList<>(employees.values());
}
@POST
@Path("/update/{id}")
public List<Employee> updateEmployeeById(@PathParam("id") String empId){
System.out.println("Inside update() method");
Employee emp = employees.get(empId);
emp.setEmployeeName("tejeswar");
employees.put(emp.getEmployeeId(),emp);
return new ArrayList<>(employees.values());
}
@PUT
@Path("/save")
@Consumes({ MediaType.APPLICATION_XML})
    @Produces({ MediaType.APPLICATION_XML})
public List<Employee> listEmployees(JAXBElement<Employee> emp) {
Employee em = emp.getValue();
employees.put(em.getEmployeeId(),em);
return new ArrayList<>(employees.values());
}
}
============================
WebController.java
------------------------
package com.hcl.controller;

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

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import com.hcl.bean.Employee;

@Path("/webservice")
public class WebController{

private static Map<String, Employee> employees = new HashMap<String, Employee>();

static {

Employee employee1 = new Employee();
employee1.setEmployeeId("11111");
employee1.setEmployeeName("Dineh Rajput");
employee1.setJobType("Sr.Software Engineer");
employee1.setSalary(70000l);
employee1.setAddress("Noida");
employees.put(employee1.getEmployeeId(), employee1);

Employee employee2 = new Employee();
employee2.setEmployeeId("22222");
employee2.setEmployeeName("Abhishek");
employee2.setJobType("Marketing");
employee2.setSalary(50000l);
employee2.setAddress("New Delhi");
employees.put(employee2.getEmployeeId(), employee2);
Employee employee3 = new Employee();
employee3.setEmployeeId("333333");
employee3.setEmployeeName("Tipu Swain");
employee3.setJobType("SR Programmer Manager");
employee3.setSalary(60000l);
employee3.setAddress("BBSR");
employees.put(employee3.getEmployeeId(), employee3);

}
@GET
@Path("/hello")
@Produces("text/plain")
public String hello(){
System.out.println("inside hello() method of WebController class");
return "hello world";
}
@GET
@Path("/message/{msg}")
@Produces("text/plain")
public String showMessage(@PathParam("msg") String messege){
return "Your messge is : "+messege;
}
@GET
@Path("/employees")
@Produces("application/xml")
public List<Employee> getAllEmployees(){
return new ArrayList<>(employees.values());
}
@GET
@Path("employees/{empid}")
@Produces("application/xml")
public Employee getEmployeeById(@PathParam("empid") String id){
return employees.get(id);
}
@GET//I had written as @post and suffered for one hour and getting exception like method not available
@Path("employees/json")
@Produces("application/json")
public List<Employee> getAllEmployeesInJsonFormat(){
return new ArrayList<>(employees.values());
}
@GET
@Path("employees/json/{empid}")
@Produces("application/json")
public Employee getEmployeeByIdInJsonFormat(@PathParam("empid") String id){
return employees.get(id);
}
}
==================================
Access the above with the URLs
http://localhost:8080/RestfuleWebServiceDemoAppl/order/webservice/employees/22222
http://localhost:8080/RestfuleWebServiceDemoAppl/order/webservice/employees/json/22222
http://localhost:8080/RestfuleWebServiceDemoAppl/order/webservice/hello
=======================================================================
=================================================================
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
REST web services  consuming
---------------------------- ----------
we have to download 2 jars and extract and place in classpath
gson-2.2.2.jar
commons-codec-1.9.jar

ClouderaRestUtilTest.java
CMCommandResponse.java
CMHost.java
CMHostId.java
CMRoleInfo.java
CMService.java
CMUser.java 
ErrorPojo.java

package com.java.examples;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.binary.Base64;

import com.google.gson.Gson;

public class ClouderaRestUtilTest {
public static Object JsonGetUrlObj(URL url, Class cl) throws IOException
    {

        Object obj = null;
        BufferedReader reader = null;
        HttpURLConnection urlConnection = null;

        try
        {
            urlConnection = (HttpURLConnection) url.openConnection();
            if (url.getUserInfo() != null)
            {
             // String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
             String basicAuth = "Basic " + new String(new Base64().encode(URLDecoder.decode(url.getUserInfo(), "UTF-8").getBytes()));
                urlConnection.setRequestProperty("Authorization", basicAuth);
            }
            InputStream inputStream = urlConnection.getInputStream();

            // url.openStream()
            reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer buffer = new StringBuffer();
            int read;
            char[] chars = new char[1024];
            while ((read = reader.read(chars)) != -1)
                buffer.append(chars, 0, read);

//            logger.debug(buffer.toString());

            Gson gson = new Gson();
            // SCluster sClust = gson.fromJson(buffer.toString(),
            // SCluster.class);
            // logger.info(sClust.theName + ":" + sClust.dnsRes /* + ":" +
            // sClust.acceptLic
            // */);

            obj = gson.fromJson(buffer.toString(), cl);

        } /*
           * catch (JsonSyntaxException e) { logger.error(e); }
           */finally
        {
            if (reader != null)
                reader.close();
            urlConnection.disconnect();
        }
        return obj;
    }

    public static Object JsonPostUrlObj(URL url, Class cl, String urlParameters) throws Exception
    {

        Object obj = null;
        BufferedReader reader = null;
        HttpURLConnection urlConnection = null;
        DataOutputStream wr = null;
        try
        {
            urlConnection = (HttpURLConnection) url.openConnection();
            // Set http request method to POST Type.
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type", "application/json");
            if (url.getUserInfo() != null)
            {
               // String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
             String basicAuth = "Basic " + new String(new Base64().encode(URLDecoder.decode(url.getUserInfo(), "UTF-8").getBytes()));
                urlConnection.setRequestProperty("Authorization", basicAuth);
            }

            // Output Stream
            urlConnection.setDoOutput(true);
             wr = new DataOutputStream(urlConnection.getOutputStream());
            if (!"".equals(urlParameters))
            {
                wr.writeBytes(urlParameters);
            }
            

            int responseCode = urlConnection.getResponseCode();
            String responseMessage = urlConnection.getResponseMessage();
           /* logger.info("\nSending 'POST' request to URL : " + url);
            logger.info("Post parameters : " + urlParameters);
            logger.info("Response Code : " + responseCode);
            logger.info("Response Message : " + responseMessage);*/
            InputStream inputStream = null;
            boolean isError = false;
            if (responseCode >= 400 && responseCode <= 500)
            {
                inputStream = urlConnection.getErrorStream();
                isError = true;
            } else
            {
                inputStream = urlConnection.getInputStream();
            }

            // Input Stream

            // url.openStream()
            reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer buffer = new StringBuffer();
            int read;
            char[] chars = new char[1024];
            while ((read = reader.read(chars)) != -1)
                buffer.append(chars, 0, read);

//            logger.debug(buffer.toString());
            Gson gson = new Gson();
            if (isError)
            {
                obj = gson.fromJson(buffer.toString(), ErrorPojo.class);
                if (reader != null)
                    reader.close();
                urlConnection.disconnect();
                ErrorPojo error = (ErrorPojo) obj;
                throw new Exception(error.getMessage());

            } else
            {
                obj = gson.fromJson(buffer.toString(), cl);
            }

        } finally
        {
            if (reader != null)
                reader.close();
            if(wr != null){
                wr.flush();
                wr.close();
            }
            urlConnection.disconnect();
        }
        return obj;
    }

    public static void JsonPutUrlObj(URL url, String urlParameters) throws IOException
    {

        BufferedReader reader = null;
        HttpURLConnection urlConnection = null;
        DataOutputStream wr = null;
        try
        {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("PUT");
            if (url.getUserInfo() != null)
            {
                //String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
             String basicAuth = "Basic " + new String(new Base64().encode(URLDecoder.decode(url.getUserInfo(), "UTF-8").getBytes()));
                urlConnection.setRequestProperty("Authorization", basicAuth);
                urlConnection.setRequestProperty("Content-Type", "application/json");
            }
            // Output Stream
            ((HttpURLConnection) urlConnection).setDoOutput(true);
             wr = new DataOutputStream(((HttpURLConnection) urlConnection).getOutputStream());
            if (!"".equals(urlParameters))
            {
                wr.writeBytes(urlParameters);
            }
            int responseCode = urlConnection.getResponseCode();
            String responseMessage = urlConnection.getResponseMessage();
           /* logger.info("\nSending 'PUT' request to URL : " + url);
            logger.info("Put parameters : " + urlParameters);
            logger.info("Response Code : " + responseCode);
            logger.info("Response Message : " + responseMessage);*/

            if (responseCode >= 400 && responseCode <= 500)
            {
                InputStream inputStream = urlConnection.getErrorStream();
                reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer buffer = new StringBuffer();
                int read;
                char[] chars = new char[1024];
                while ((read = reader.read(chars)) != -1)
                    buffer.append(chars, 0, read);
                if (reader != null)
                    reader.close();
                inputStream.close();
                urlConnection.disconnect();
                throw new Exception(buffer.toString());
            }
        } catch (Exception e)
        {
//            logger.error(e);
        } finally
        {
            if (reader != null)
                reader.close();
            if (wr != null){
                wr.flush();
                wr.close();
            }
            urlConnection.disconnect();

        }

    }

    public static Object JsonDeleteUrlObj(URL url, Class cl, String urlParameters) throws IOException
    {

        BufferedReader reader = null;
        HttpURLConnection urlConnection = null;
        Object obj = null;

        try
        {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("DELETE");
            if (url.getUserInfo() != null)
            {
//                String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
             String basicAuth = "Basic " + new String(new Base64().encode(URLDecoder.decode(url.getUserInfo(), "UTF-8").getBytes()));
                urlConnection.setRequestProperty("Authorization", basicAuth);
            }

            int responseCode = urlConnection.getResponseCode();
            String responseMessage = urlConnection.getResponseMessage();
           /* logger.info("\nSending 'DELETE' request to URL : " + url);
            logger.info("Delete parameters : " + urlParameters);
            logger.info("Response Code : " + responseCode);
            logger.info("Response Message : " + responseMessage);*/

            // Input Stream
            InputStream inputStream = urlConnection.getInputStream();
            // url.openStream()
            reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer buffer = new StringBuffer();
            int read;
            char[] chars = new char[1024];
            while ((read = reader.read(chars)) != -1)
                buffer.append(chars, 0, read);

//            logger.info("output" + buffer.toString());
            Gson gson = new Gson();
            obj = gson.fromJson(buffer.toString(), cl);

        } finally
        {
            if (reader != null)
                reader.close();
            urlConnection.disconnect();
        }
        return obj;
    }

    public static Object JsonPutUrlObj(URL url, Class cl, String urlParameters) throws Exception
    {
        Object obj = null;
        BufferedReader reader = null;
        HttpURLConnection urlConnection = null;
        DataOutputStream wr=null;
        try
        {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("PUT");
            if (url.getUserInfo() != null)
            {
//                String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
             String basicAuth = "Basic " + new String(new Base64().encode(URLDecoder.decode(url.getUserInfo(), "UTF-8").getBytes()));
                urlConnection.setRequestProperty("Authorization", basicAuth);
                urlConnection.setRequestProperty("Content-Type", "application/json");
            }
            // Output Stream
            ((HttpURLConnection) urlConnection).setDoOutput(true);
             wr = new DataOutputStream(((HttpURLConnection) urlConnection).getOutputStream());
            if (!"".equals(urlParameters))
            {
                wr.writeBytes(urlParameters);
            }
            
            int responseCode = urlConnection.getResponseCode();
            String responseMessage = urlConnection.getResponseMessage();
           /* logger.info("\nSending 'PUT' request to URL : " + url);
            logger.info("Put parameters : " + urlParameters);
            logger.info("Response Code : " + responseCode);
            logger.info("Response Message : " + responseMessage);*/
            // Input Stream
            InputStream inputStream = null;
            boolean isError = false;
            if (responseCode >= 400 && responseCode <= 500)
            {
                inputStream = urlConnection.getErrorStream();
                isError = true;
            } else
            {
                inputStream = urlConnection.getInputStream();
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer buffer = new StringBuffer();
            int read;
            char[] chars = new char[1024];
            while ((read = reader.read(chars)) != -1)
                buffer.append(chars, 0, read);

//            logger.debug(buffer.toString());
            Gson gson = new Gson();
            if (isError)
            {
                obj = gson.fromJson(buffer.toString(), ErrorPojo.class);
                if (reader != null)
                    reader.close();
                urlConnection.disconnect();
                ErrorPojo error = (ErrorPojo) obj;
                throw new Exception(error.getMessage());

            } else
            {
                obj = gson.fromJson(buffer.toString(), cl);
            }
        } catch (Exception e)
        {
//            logger.error(e);
        } finally
        {
            if (reader != null)
                reader.close();
            if(wr != null){
                wr.flush();
                wr.close();
            }
            urlConnection.disconnect();

        }
        return obj;
    }

    private static boolean checkCommand(String imHostname, String commandID) throws Exception
    {
//        String userNamepwd = getManagementConsolePwd(imHostname);
        String strUrl = "http://" + "admin:csico" + "@" + imHostname + ":7180/api/v6/commands/" + commandID;
        try
        {
            URL url = new URL(strUrl);
            CMCommandResponse response = (CMCommandResponse) JsonGetUrlObj(url, CMCommandResponse.class);
            return response.isActive();
        } catch (Exception e)
        {
            return false;
        }
    }
    public static void autoConfigure(String serverIP, String clusterName) throws Exception
    {
//        String userNamepwd = getManagementConsolePwd(serverIP);
        String strUrl = "http://" + "admin:cisco" + "@" + serverIP + ":7180/api/v6/clusters/" + clusterName
                + "/autoConfigure";
        URL configureURL = new URL(strUrl);
        ClouderaRestUtilTest.JsonPutUrlObj(configureURL, "");
    }
    public static void changeUserPasswrd(String serverIP, String username, String password) throws Exception
    {
//        String userNamepwd = getManagementConsolePwd(serverIP);
        String strUrl = "http://" + "admin:cisco" + "@" + serverIP + ":7180/api/v6/users/" + username;
        URL cmuserInfoUrl = new URL(strUrl);
        CMUser user = getUserDetails(serverIP, username);
        user.setPassword(password);
        Gson gson = new Gson();
        String json = gson.toJson(user, CMUser.class);
        JsonPutUrlObj(cmuserInfoUrl, json);

    }
    public static CMUser getUserDetails(String serverIP, String username) throws Exception
    {
//        String userNamepwd = getManagementConsolePwd(serverIP);
        String strUrl = "http://" + "admin:cisco" + "@" + serverIP + ":7180/api/v6/users/" + username;
        URL cmuserInfoUrl = new URL(strUrl);
        CMUser cmUser = (CMUser) JsonGetUrlObj(cmuserInfoUrl, CMUser.class);
        return cmUser;
    }
    //response class may be changed
    public static void main(String[] args) throws Exception {
//     boolean v= checkCommandSuccessStatus(im_hostname, commandID);
    
     //PoST Method Calling
      List<CMService> cmServicesList = new ArrayList<CMService>();
         CMService cmService = new CMService();
         cmService.setType("serviceType");
         cmService.setName("serviceType.toLowerCase()");
         cmService.setDisplayName("serviceType.toLowerCase()");
//         cmService.setClusterName("new CMClusterName(clusterName)");
         cmServicesList.add(cmService);
         String strUrl = "http://" + "admin:cisco" + "@" + "serverIP" + ":7180/api/v6/clusters/" + "clusterName" + "/services/";
         URL addServicesURL = new URL(strUrl);
         Gson gson = new Gson();
         String inputJson = "{\"items\" :"+gson.toJson(cmServicesList)+"}";
     CMCommandResponse response = (CMCommandResponse) ClouderaRestUtilTest.JsonPostUrlObj(addServicesURL, CMCommandResponse.class, inputJson);
}
    public static void deleteRole(String imHostNm, String clusterName, String serviceName, String roles)
            throws Exception
    {
//        String userNamepwd = getManagementConsolePwd(imHostNm);
        String[] roleNamArray = roles.split(",");
        for (String role : roleNamArray)
        {
            String strURL = "http://" + "admin:csico" + "@" + imHostNm + ":7180/api/v6/clusters/" + clusterName
                    + "/services/" + serviceName + "/roles/" + role;
            URL url = new URL(strURL);

            JsonDeleteUrlObj(url, CMRoleInfo.class, "");
        }
    }
    public static CMHostId deleteNodeFromCMHosts(String imHostNm, String hostId) throws Exception
    {
//        String userNamepwd = getManagementConsolePwd(imHostNm);
        String deleteNodeurl = "http://" + "admin:cisco" + "@" + imHostNm + ":7180/api/v6/hosts/" + hostId;
        URL url = new URL(deleteNodeurl);
        CMHostId deleteNode = (CMHostId) JsonDeleteUrlObj(url, CMHostId.class, "");
//        logger.info("Deleted Node from CM" + deleteNode.getHostId());
        return deleteNode;
    }
    private static CMHostId deleteNode(String imHostNm, String clusterName, String hostId) throws Exception
    {
//        String userNamepwd = getManagementConsolePwd(imHostNm);
        String deleteNodeurl = "http://" + "admin:cisco" + "@" + imHostNm + ":7180/api/v6/clusters/" + clusterName
                + "/hosts/" + hostId;
        URL url = new URL(deleteNodeurl);
        CMHostId deleteNode = (CMHostId) JsonDeleteUrlObj(url, CMHostId.class, "");
//        logger.info("Deleted Node" + deleteNode.getHostId());
        return deleteNode;
    }
    private static CMHost moveNodeToOtherRack(String serverIp, CMHost hostToEdit) throws Exception
    {
//        String userNamepwd = getManagementConsolePwd(serverIp);
        Gson gson = new Gson();
        String strURL = "http://" + "admin:cisco" + "@" + serverIp + ":7180/api/v6/hosts/" + hostToEdit.getHostId();
        URL url = new URL(strURL);
        String inputJson = gson.toJson(hostToEdit, CMHost.class);
        CMHost cmHost = (CMHost) JsonPutUrlObj(url, CMHost.class, inputJson);
        return cmHost;

    }

}
------------------------------------------------
package com.java.examples;

public class CMCommandResponse
{
    private int     id;
    private String  name;
    private boolean active;
    private boolean success;
    
    /*@SerializedName("clusters")
    private List<CMClusterInfo> clusterList;
@SerializedName("hosts")
    private List<CMHost> cMHost;

public List<CMClusterInfo> getClusterList() {
return clusterList;
}*/

    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

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

    public boolean isActive()
    {
        return active;
    }

    public void setActive(boolean active)
    {
        this.active = active;
    }

    public void setSuccess(boolean success)
    {
        this.success = success;
    }

    public boolean isSuccess()
    {
        return success;
    }

}
------------------------------------------------------
package com.java.examples;


public class CMHost
{
    private String hostId;

    private String ipAddress;

    private String hostname;

    private String rackId;
    
    private String  healthSummary;
    
    private String commissionState;
    
    private String totalPhysMemBytes;

    public String getHostId()
    {
        return hostId;
    }

    public void setHostId(String hostId)
    {
        this.hostId = hostId;
    }

    public String getIpAddress()
    {
        return ipAddress;
    }

    public void setIpAddress(String ipAddress)
    {
        this.ipAddress = ipAddress;
    }

    public String getHostname()
    {
        return hostname;
    }

    public void setHostname(String hostname)
    {
        this.hostname = hostname;
    }

    public String getRackId()
    {
        return rackId;
    }

    public void setRackId(String rackId)
    {
        this.rackId = rackId;
    }

    @Override
    public String toString()
    {
        // TODO Auto-generated method stub
        return hostId+" "+ipAddress+" "+hostname+" "+rackId;
    }

    public void setHealthSummary(String healthSummary)
    {
        this.healthSummary = healthSummary;
    }

    public String getHealthSummary()
    {
        return healthSummary;
    }

    public void setCommissionState(String commissionState)
    {
        this.commissionState = commissionState;
    }

    public String getCommissionState()
    {
        return commissionState;
    }

    public String getTotalPhysMemBytes()
    {
        return totalPhysMemBytes;
    }

    public void setTotalPhysMemBytes(String totalPhysMemBytes)
    {
        this.totalPhysMemBytes = totalPhysMemBytes;
    }

    
}
--------------------------------
package com.java.examples;

public class CMHostId
{
    private String hostId;

    public CMHostId()
    {
    }

    public CMHostId(String hostId)
    {
        this.hostId = hostId;
    }

    public void setHostId(String hostId)
    {
        this.hostId = hostId;
    }

    public String getHostId()
    {
        return hostId;
    }

    @Override
    public String toString()
    {
        return "CMHostId [hostId=" + hostId + "]";
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((hostId == null) ? 0 : hostId.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        CMHostId other = (CMHostId) obj;
        if (hostId == null)
        {
            if (other.hostId != null)
                return false;
        } else if (!hostId.equals(other.hostId))
            return false;
        return true;
    }


}
----------------------------------
package com.java.examples;
import com.google.gson.annotations.SerializedName;
public class CMRoleInfo
{
    private String        name;
    private String        type;

    @SerializedName("hostRef")
    private CMHostId      hostRef;
    private String        healthSummary;
    private String        roleState;
//    private CMRoleConfigs config;

    public String getName()
    {
        return name;
    }

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

    public String getType()
    {
        return type;
    }

    public void setType(String type)
    {
        this.type = type;
    }

   /* public CMHostId getHostRef()
    {
        return hostRef;
    }

    public void setHostRef(CMHostId hostRef)
    {
        this.hostRef = hostRef;
    }*/

    public String getHealthSummary()
    {
        return healthSummary;
    }

    public void setHealthSummary(String healthSummary)
    {
        this.healthSummary = healthSummary;
    }

    /*@Override
    public String toString()
    {
        return "CMRoleInfo [healthSummary=" + healthSummary + ", hostRef=" + hostRef + ", name=" + name + ", type="
                + type + "]";
    }*/

    public void setRoleState(String roleState)
    {
        this.roleState = roleState;
    }

    public String getRoleState()
    {
        return roleState;
    }

    /*public CMRoleConfigs getConfig()
    {
        return config;
    }

    public void setConfig(CMRoleConfigs config)
    {
        this.config = config;
    }*/
}
---------------------------------------------
package com.java.examples;

public class CMService
{

    private String        name;
    private String        displayName;
    private String        type;

    private String        serviceState;

    private String        healthSummary;

  /*  @SerializedName("clusterRef")
    private CMClusterName clusterName;

    @SerializedName("config")
    private CMServiceConfigItems configItems;
    
    @SerializedName("roles")
    private List<CMRoleInfo>      roleList;

    @SerializedName("roleConfigGroups")
    private List<CMRoleConfigGroup> roleConfigGroupList;*/
    
    public String getName()
    {
        return name;
    }

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

    public String getType()
    {
        return type;
    }

    public void setType(String type)
    {
        this.type = type;
    }

  /*  public CMClusterName getClusterName()
    {
        return clusterName;
    }

    public void setClusterName(CMClusterName clusterName)
    {
        this.clusterName = clusterName;
    }

    public List<CMRoleInfo> getRoleList()
    {
        return roleList;
    }

    public void setRoleList(List<CMRoleInfo> roleList)
    {
        this.roleList = roleList;
    }
*/
    public void setDisplayName(String displayName)
    {
        this.displayName = displayName;
    }

    public String getDisplayName()
    {
        return displayName;
    }

    public void setHealthSummary(String healthSummary)
    {
        this.healthSummary = healthSummary;
    }

    public String getHealthSummary()
    {
        return healthSummary;
    }

    public void setServiceState(String serviceState)
    {
        this.serviceState = serviceState;
    }

    public String getServiceState()
    {
        return serviceState;
    }

   /* public void setConfigItems(CMServiceConfigItems configItems)
    {
        this.configItems = configItems;
    }

    public CMServiceConfigItems getConfigItems()
    {
        return configItems;
    }

    public void setRoleConfigGroupList(List<CMRoleConfigGroup> roleConfigGroupList)
    {
        this.roleConfigGroupList = roleConfigGroupList;
    }

    public List<CMRoleConfigGroup> getRoleConfigGroupList()
    {
        return roleConfigGroupList;
    }*/

}
--------------------
package com.java.examples;

import java.util.List;

import com.google.gson.annotations.SerializedName;

public class CMUser
{
    private String       name;

    private String       password;

    @SerializedName("roles")
    private List<String> roles;

    public String getName()
    {
        return name;
    }

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

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }

    public List<String> getRoles()
    {
        return roles;
    }

    public void setRoles(List<String> roles)
    {
        this.roles = roles;
    }

}
-----------------------------------
package com.java.examples;

import com.google.gson.annotations.SerializedName;

public class ErrorPojo
{
    @SerializedName("message")
    private String message;

    public void setMessage(String message)
    {
        this.message = message;
    }

    public String getMessage()
    {
        return message;
    }
    
}
---------------------------------------------------------------------
http://cloudera.github.io/cm_api/apidocs/v6/rest.html
=================================================
changePassword.jsp
ChangePasswordController.java
forgotPassword.java
forgotPasswordChallengeQuestion.java
forgotPasswordConfirm.jsp
ForgotPasswordController.java
passwordChanged.jsp
passwordChangePolicy.html

changePassword.jsp
-----------------------
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page session="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<h1>change password</h1>
<h3>
Please create a new Password. Your password should<br> confirm
to the password creation rules
</h3>
<form:form modelAttribute="user" method="POST">
<table>
<tr>
<td abbr="right">To Know more about the rules<a href="passwordChangePolicy.html">Click here</a></td>
</tr>
<tr>
<td>Old Password</td>
<td><form:password path="oldPassword" /></td>
</tr>
<tr>
<td>New Password</td>
<td><form:password path="newPassword" /></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><form:password path="confirmChangePassword" /></td>
</tr>
<tr>
<td><input type="reset" value="Cancel" /></td>
<td><input type="submit" value="Continue" /></td>
</tr>
</table>

</form:form>
</center>
</body>
</html>
ChangePasswordController.java
------------------------------
package com.rsa.selfservice.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.rsa.selfservice.model.User;

/**
 * @author rajesh
 *
 */
@SessionAttributes("user")
@Controller
public class ChangePasswordController {
/**
 * user session key name
 */
private static final String USER_ATTRIBUTE_KEY = "user";


/*Change Password Start*/
@RequestMapping(value = "/changePassword", method = RequestMethod.GET)
public String showchangePasswordForm(@ModelAttribute User user, Model model) {
model.addAttribute(USER_ATTRIBUTE_KEY, user);
return "changePassword";
}

@RequestMapping(value = "/changePassword", method = RequestMethod.POST)
public String showPasswordChanged(@ModelAttribute User user, BindingResult result, Model model) {

return "redirect:passwordChanged";
}

@RequestMapping(value = "/passwordChanged", method = RequestMethod.GET)
public String passwordChanged(@ModelAttribute User user, Model model) {
model.addAttribute(USER_ATTRIBUTE_KEY, user);
return "passwordChanged";
}

@RequestMapping(value = "/passwordChanged", method = RequestMethod.POST)
public String showLoginPage(@ModelAttribute User user, BindingResult result, Model model) {

return "login";
}
/*userAccountValidator.validate(user, result);

if(result.hasErrors()) {
return "registrationUserDetails";
}

ldapUserDao.createUser(user);

return "redirect:challengeQuestions";
}*/

}
===========================
forgotPassword.java
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ page session="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Forgot user name</title>
</head>
<body><center><h1>Forgot user Password</h1>
Please enter Your Username.<br>
Link to create new password will be sent to the email address<br>
 associated with your account

<form:form modelAttribute="user" method="POST">
<table>
    <tr>
        <td> User Name </td>
        <td><form:input path="firstName" /></td>
    </tr>
 
    <tr>
        <td colspan="2">
            <input type="reset" value="Cancel"/>
              <input type="submit" value="Continue"/>
        </td>
    </tr>
</table>
</form:form>
</center>
</body>
</html>
---------------------------------
forgotPasswordChallengeQuestion.java
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ page session="false"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Forgot Password screen1</title>
</head>

<body>

<center>
<h1>Challenge Question Password</h1>
<h3>
Please identify Yourself by answering the below question.<br>
<br>
</h3>
<form:form modelAttribute="user" method="POST">
What was the last name of your favorite teacher in fina; year of high school?
<form:input path="teacherLastName" size="40" /><br><br>
<input type="reset" value="Cancel"></input>
<input type="submit" value="Continue"></input>
</form:form>

</center>

</body>
</html>
--------------------------
forgotPasswordConfirm.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ page session="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Confirm Forgot Password 2 nd page</title>
</head>
<body>
<center>
<h1>Forgot Password</h1>
<form:form modelAttribute="user" method="POST">
Welcome  Jason Smith :
To create a new password,<br>
You must prove your identity by answering a challenge question<br>
 in the next Screen<br><br>
Press Continue to proceed<br><br>
<input type="reset" value="Cancel"></input>
<input type="submit" value="Continue"></input>
</form:form>

</center>

</body>
</html>
==========================
ForgotPasswordController.java
-------------------------------

package com.rsa.selfservice.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.rsa.selfservice.model.User;

/**
 * @author rajesh
 *
 */
@SessionAttributes("user")
@Controller
public class ForgotPasswordController {

private static final String USER_ATTRIBUTE_KEY = "user";
/* Forgot Password Start */
@RequestMapping(value = "/forgotPassword", method = RequestMethod.GET)
public String showForgotPasswordPage(@ModelAttribute User user, Model model) {
model.addAttribute(USER_ATTRIBUTE_KEY, user);
return "forgotPassword";
}

@RequestMapping(value = "/forgotPassword", method = RequestMethod.POST)
public String showPasswordChanged(@ModelAttribute User user, BindingResult result, Model model) {

return "redirect:forgotPasswordConfirm";
}

@RequestMapping(value = "/forgotPasswordConfirm", method = RequestMethod.GET)
public String showforgotPasswordConfirmPage(@ModelAttribute User user, Model model) {
model.addAttribute(USER_ATTRIBUTE_KEY, user);
return "forgotPasswordConfirm";
}

@RequestMapping(value = "/forgotPasswordConfirm", method = RequestMethod.POST)
public String showChallengeQuestionPage(@ModelAttribute User user, BindingResult result, Model model) {

//return "redirect:changePassword";
return "redirect:forgotPasswordChallengeQuestion";
}

@RequestMapping(value = "/forgotPasswordChallengeQuestion", method = RequestMethod.GET)
public String showChallengeQuestionPage(@ModelAttribute User user, Model model) {
model.addAttribute(USER_ATTRIBUTE_KEY, user);
return "forgotPasswordChallengeQuestion";
}
@RequestMapping(value = "/forgotPasswordChallengeQuestion", method = RequestMethod.POST)
public String showChangePasswordPage(@ModelAttribute User user, BindingResult result, Model model) {

return "redirect:changePassword";
//return "redirect:challengeQuestion";
}
/* Forgot Password Start */

}
-----------------------
passwordChanged.jsp
----------------------------.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ page session="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body><center>
 <h1>Change Password</h1>
<h3>You have successfully Changed your Password<br>

Press the continue button below to login with your new password</h3>
 <form:form modelAttribute="user" method="POST">

<input type="submit" value="Continue"></input>
</form:form>
</center>
</body>
</html>
==================================
passwordChangePolicy.html
--------------------------
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
passwordChangePolicy.html
</body>
</html>

No comments:

Post a Comment