Tuesday 31 December 2013

Spring mvc Security

 Spring mvc Security(Form base Authentication)

Hello Friends i  wish you a very happy new year.suppose you want to implement Security in MVC Application then what you supposed to do.well Spring provides a very good way for authentication.all you have to do is download jars or maven dependancy  required to implement spring mvc security.

You can implement form base authentication using spring_j_secuirty,

here is sample code to implement spring mvc security :
 login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Login Page For Security</title>
<style>
.errorblock {
    color: #ff0000;
    background-color: #ffEEEE;
    border: 3px solid #ff0000;
    padding: 8px;
    margin: 16px;
}
</style>
</head>
<body onload='document.f.j_username.focus();'>
    <h3>Login with Username and Password </h3>

    <c:if test="${not empty error}">
        <div class="errorblock">
            Your login attempt was not successful, try again
        </div>
    </c:if>

    <form name='f' action="<c:url value='j_spring_security_check' />"
        method='POST'>

        <table>
            <tr>
                <td>User:</td>
                <td><input type='text' name='j_username' value=''>
                </td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type='password' name='j_password' />
                </td>
            </tr>
            <tr>
                <td colspan='2'><input name="submit" type="submit" value="submit" />
                </td>
            </tr>
            <tr>
                <td colspan='2'><input name="reset" type="reset" />
                </td>
            </tr>
        </table>

    </form>
</body>
</html>

index.jsp

index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>welcome</title>
</head>
<body>
    <h2> Successfully logged in !!</h2>
    <a href='<c:url value="/j_spring_security_logout" />' > Logout</a>
</body>
</html>


Controller class:
package org.test.controller;

import java.security.Principal;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class LoginController
{
   
    public LoginController() { }
   

    @RequestMapping(value="/index", method = RequestMethod.GET)
    public String executeSecurity(ModelMap model, Principal principal ) {

        //String name = principal.getName();

//        model.addAttribute("author", name);
        //model.addAttribute("message", "Welcome To Login Form Based Spring Security Example!!!");
        return "welcome";

    }

    @RequestMapping(value="/login", method = RequestMethod.GET)
    public String login(ModelMap model) {

        return "login";

    }

    @RequestMapping(value="/fail2login", method = RequestMethod.GET)
    public String loginerror(ModelMap model) {

        model.addAttribute("error", "true");
        return "login";

    }

    @RequestMapping(value="/logout", method = RequestMethod.GET)
    public String logout(ModelMap model) {

        return "login";

    }
   
   
}

database.properties

database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/test
database.user=root
database.password=admin!@#
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update




web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <servlet>
        <servlet-name>sdnext</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>sdnext</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <listener>
        <listener-class>
                  org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/springsecurity.xml,/WEB-INF/applicationcontext.xml
        </param-value>
    </context-param>
   
    <welcome-file-list>
        <welcome-file>/WEB-INF/views/default.jsp</welcome-file>
    </welcome-file-list>
   
    <!-- Spring Security -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>
                  org.springframework.web.filter.DelegatingFilterProxy
                </filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
   
</web-app>

springsecurity.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/security
                           http://www.springframework.org/schema/security/spring-security-3.1.xsd">

   <security:http auto-config="true" >
        <security:intercept-url pattern="/index*" access="ROLE_USER" />
        <security:form-login login-page="/login" default-target-url="/index"
            authentication-failure-url="/fail2login" />
        <security:logout logout-success-url="/logout" />
    </security:http>

    <security:authentication-manager>
      <security:authentication-provider>
      
        <security:jdbc-user-service data-source-ref="dataSource" 
            users-by-username-query="select username, password, active from users where username=?"
                authorities-by-username-query="select us.username, ur.authority from users us, user_roles ur where us.user_id = ur.user_id and us.username =?  "
        />
      </security:authentication-provider>
    </security:authentication-manager>

</beans>

applicationcontext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
   
    <context:property-placeholder location="classpath:resources/database.properties" />
    <context:component-scan base-package="org.test" />

    <tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
   
    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
   
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${database.driver}" />
        <property name="url" value="${database.url}" />
        <property name="username" value="${database.user}" />
        <property name="password" value="${database.password}" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>              
            </props>
        </property>
    </bean>
      
</beans>

thanks i hope you will get it.for any query ping me on pathak.nisarg@yahoo.com




Tuesday 24 December 2013

Spring Xstream

Spring Xstream
 
Hello Friends i am going to demonstrate Spring Xstream,Xstream is a library to marshal objects to xml and vice-versa without requirement of any mapping file. Notice that castor requires an mapping file.

Here is sample code:
 //object that i am serializing using Xstream
package org.demo;

public class Employee {

    private int id;
    private String name;
    private float salary;
   
    public Employee() { }
    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 float getSalary() {
        return salary;
    }
    public void setSalary(float salary) {
        this.salary = salary;
    }


}


//code of conversion from java object into xml form
Client.java
    package org.demo;

import javax.xml.transform.stream.StreamResult;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.XmlMappingException;

import java.io.FileWriter;
import java.io.IOException;

public class Client
{

   
   
    public static void main(String[] args) throws XmlMappingException, IOException, BeansException
    {
       
            ApplicationContext context= new ClassPathXmlApplicationContext("spring.xml");
           
           
            Marshaller marshaller=(Marshaller)context.getBean("xstreamMarshellerBean");
           
            Employee e=new Employee();
            e.setId(1);
            e.setName("Dhruti");
            e.setSalary(20000);
            marshaller.marshal(e,new StreamResult(new FileWriter("employee.xml")));
           
        }   

}

spring.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 
     
<bean id="xstreamMarshallerBean" class="org.springframework.oxm.xstream.XStreamMarshaller" scope="singelton"> 
    <property name="annotatedClasses" value="org.demo.Employee"/> 

</bean>

</beans>

hope you will get my point.in next post i will demonstrate you how to work with spring caster .
thanks
for any query ping me on pathak.nisarg@yahoo.com

Monday 23 December 2013

Spring jsf Hibernate Integration

 Spring jsf Hibernate Integration 

Hello Friends.i am going to demonstrate you Spring Hibernate jsf integration project.here in this example i am follwing DAO pattern to interact with database.
You need to add jars associated with spring ,hibernate and jsf .
As it does not include any thorough understanding the concept i am moving towards code ,the code is as given below :


 Java/Reources->org.integration.model
package org.integration.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
public class User
{
       
   
    @Id
    private int id;
    @Column(nullable=false)
    private String username;
    @Column(nullable=false)
    private String password;
   
   
    public int getId()
    {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
   
   
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
   
   
}
under Java Resources->org.integration.dao

package org.integration.dao;

import org.integration.model.User;

public interface UserDao
{
   
    public void addUser(User u);
    public void updateUser(int id);
    public void deleteUser(int id);
   

}
under Java Resources->org.integration.dao

package org.integration.dao;

import org.hibernate.SessionFactory;
import org.integration.model.User;

public class UserDaoImpl implements UserDao
{
   
    private SessionFactory sessionfactory;
   

    public SessionFactory getSessionfactory() {
        return sessionfactory;
    }

    public void setSessionfactory(SessionFactory sessionfactory) {
        this.sessionfactory = sessionfactory;
    }

    @Override
    public void addUser(User u)
    {
       
        getSessionfactory().getCurrentSession().save(u);
       
       
    }

    @Override
    public void updateUser(int id)
    {
        getSessionfactory().getCurrentSession().update(id);
    }

    @Override
    public void deleteUser(int id)
    {
        getSessionfactory().getCurrentSession().delete(id);
       
       
    }

}

under Java Resources->org.integration.service
package org.integration.service;

import org.integration.model.User;

public interface UserService
{
   
    public void addUser(User u);
    public void updateUser(int id);
    public void deleteUser(int id);

}

 under Java Resources->org.integration.service

package org.integration.service;

import org.integration.dao.UserDao;
import org.integration.model.User;

public class UserServiceImpl implements UserService
{
    private UserDao userDAO;

    public UserDao getUserDAO() {
        return userDAO;
    }

    public void setUserDAO(UserDao userDAO)
    {
        this.userDAO = userDAO;
    }

    @Override
    public void addUser(User u)
    {
       
       
    getUserDAO().addUser(u);
   
       
    }

    @Override
    public void updateUser(int id)
    {

    getUserDAO().updateUser(id);
   
       
    }

    @Override
    public void deleteUser(int id)
    {
       
    getUserDAO().deleteUser(id);
   
    }
 
   
}
 under Java Resources->org.integration.beanManager

package org.integration.beanManager;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;

import org.integration.model.User;
import org.integration.service.UserService;
import org.springframework.dao.DataAccessException;

@ManagedBean
public class UserHandler implements Serializable
{
/**
     *
     */
    private static final long serialVersionUID = 1L;

@ManagedProperty(value = "#{userservice}")
private UserService userservice;

private int id;
private String name;
private String password;

public UserHandler()
{
   
}

public UserService getUserservice() {
    return userservice;
}
public void setUserservice(UserService userservice) {
    this.userservice = userservice;
}
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 String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}

public String add()
{
    try
    {
User u=new  User();

u.setId(getId());
u.setUsername(getName());
u.setPassword(getPassword());

getUserservice().addUser(u);
    }
    catch(DataAccessException d)
    {
      
    }
return "Success";

}
public String update(int id)
{
    getUserservice().updateUser(id);
   
    return "Update";
   
}
public String  delete(int id)
{

    getUserservice().deleteUser(id);

    return "Delete";
}



   
}


 index.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
     xmlns:h="http://java.sun.com/jsf/html"
     xmlns:f="http://java.sun.com/jsf/core"
     xmlns:p="http://primefaces.org/ui">
    <h:head><title>Spring hibernate jsf integration</title></h:head>
 <body>
     <h:form>
         <table>
             <tr>
                <td><h:outputLabel for="id" value="id" /></td>
                <td><p:inputText id="id" value="#{UserHandler.id}"/></td>
              
             </tr>
             <tr>
                <td><h:outputLabel for="name" value="name:" /></td>
                <td><p:inputText id="name" value="#{UserHandler.name}"/> </td>
             </tr>
             <tr>
                <td><p:commandButton id="submit" value="Save" action="#{UserHandler.save}" ajax="false"/></td>
                <td><p:commandButton id="reset" value="Reset" action="#{UserHandler.reset}" ajax="false"/></td>
             </tr>
         </table>
     </h:form>
</body>
</html> 
    
 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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>SpringHibernateJSF</display-name>

 <!-- Spring Context Configuration' s Path definition -->
      <context-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>
            /WEB-INF/Spring-Context.xml
         </param-value>
      </context-param>
     
     
     
 <!-- The Bootstrap listener to start up and shut down Spring's root WebApplicationContext. It is registered to Servlet Container -->
      <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
      </listener>
      <listener>
        <listener-class>
            org.springframework.web.context.request.RequestContextListener
        </listener-class>
      </listener>
     
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
  </servlet-mapping>
  <context-param>
    <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
  </context-param>
  <context-param>
    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
    <param-value>resources.application</param-value>
  </context-param>
  <listener>
    <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
  </listener>
</web-app>

Spring-Context.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
      
      
      
      
        <bean id="User" class="org.integration.model.User">
        </bean>
      
        <bean id="UserDAO" class="org.integration.dao.UserDaoImpl">
        <property name="sessionfactory" ref="SessionFactory"></property>
        </bean>
      
        <bean id="UserService" class="org.integration.service.UserServiceImpl">
        <property name="userDAO" ref="UserDAO"/>
        </bean>
      
      
         <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName" value="jdbc/MyDb" />
        <property name="resourceRef" value="true" />
        <property name="expectedType" value="javax.sql.DataSource"/>
        </bean>
       
        <bean id="SessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
       
       
        <property name="hibernateProperties">
       
            <list>
                <value>org.integration.model.User</value>
            </list>
       
          
        </property>
        <property name="mappingDirectoryLocations">
         <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.DerbyDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
            </property>
       
        </bean>


</beans>

[Note: example only demonstrates to add user daa,it does not associated any ui component with action event such as update,  delete]

hope you will get my point

thanks
for any query ping me on pathak.nisarg@yahoo.com
















 

Saturday 21 December 2013

JAX-RS Returning Data Using Response

JAX-RS  Returning Data

Hi friends .i am bit busy now a days.as i have told you in this session i am going to demonstrate you how different content types will be returned by jax-rs.

in below example i am again demonstrating you the same example of university web service.before going into code i will show how web service works using schematic representation:






The code snippet and detail description is marked as a comment in code.the code is as follows:
index.jsp

<?xml version="1.0" encoding="ISO-8859-1" ?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0">
    <jsp:directive.page contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1" session="false"/>
    <jsp:output doctype-root-element="html"
        doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
        doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
        omit-xml-declaration="true" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Insert title here</title>
</head>
<body>
<form method="get" action="rest/university/Json">

    <table>
            <tr>
                <td><input type="text" name="usename"></input>
                </td>
            </tr>
           
            <tr>
                <td><input type="password" name="password"></input>
                </td>
            </tr>
           
            <tr>
                <td><input type="submit" name="submit"></input>
                </td>
            </tr>
    </table>   

</form>
</body>
</html>
</jsp:root>

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/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
  <servlet>
    <servlet-name>Jersey Rest Services</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey Rest Services</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

university web service

package org.web;

import javax.json.Json;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

@Path("/university")
public class Univeristy
{
    @SuppressWarnings("unused")
    @Context
    private UriInfo context;

    /**
     * Default constructor.
     */
    public Univeristy()
    {
        // TODO Auto-generated constructor stub
    }
   
  //call by  http://localhost:8080/rest/university/Json after passing values to form

    @Path("/Json")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response displayJsondata(@FormParam("username") String username,@FormParam("password")String password)
    {
       
        if(username.equals("") && password.equals(""))
            return Response.serverError().entity("Username and password should not be blank").build();
       
        String  data=username+password;
       
        return Response.ok(data,MediaType.APPLICATION_JSON_TYPE).build();
       
       
    }
   
    //Response using form parameters
   //call by  http://localhost:8080/rest/university/Xml
       
    @Path("/Xml")
    @GET
    @Produces(MediaType.APPLICATION_ATOM_XML)
    public Response displayXmlData(@FormParam("username") String username,@FormParam("password")String password)
    {
        if(username.equals("") && password.equals(""))
        return Response.serverError().entity("Username and password should not be blank").build();
        String data=username+password;
       
        return Response.ok(data,MediaType.APPLICATION_ATOM_XML).build();
    }
   
   
  

}

Thanks hope you will get it.
For Any query related to post ping me on pathak.nisarg@yahoo.com

Tuesday 17 December 2013

JAX-RS Parameter Passing

Parameter Passing using JAX-RS

Hello friends hope you all are fine.i am going to demonstrate you simple code for how to passing various kinds of parameters using jax-rs web service.some of the annotations which is used to pass parameter to web service is as follows:

@FormParam
->used to get form parameters  passed to web service 
@QueryParam
->used to get form parameters passed to web service 
@PathParam
->used to get form parameters  passed to web service  
@MatrixParam
->used to get form parameters  passed to web service . 

Sample Code:
index.jsp

<?xml version="1.0" encoding="ISO-8859-1" ?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0">
    <jsp:directive.page contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1" session="false"/>
    <jsp:output doctype-root-element="html"
        doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
        doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
        omit-xml-declaration="true" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Insert title here</title>
</head>
<body>

<form method="post" action="rest/university/param">
    <table>
            <tr>
                <td><input type="text" name="usename"></input>
                </td>
            </tr>
           
            <tr>
                <td><input type="text" name="password"></input>
                </td>
            </tr>
           
            <tr>
                <td><input type="submit" name="submit"></input>
                </td>
            </tr>
    </table>   

</form>

</body>
</html>
</jsp:root>

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/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
 
 
 
  <servlet>
    <servlet-name>Jersey Rest Services</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey Rest Services</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

 Sample jax-rs code :
package org.paramdemo;

import javax.websocket.server.PathParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

@Path("/university")
public class University
{
    @SuppressWarnings("unused")
    @Context
    private UriInfo context;

    /**
     * Default constructor.
     */
    public University() {
        // TODO Auto-generated constructor stub
    }

    /**
     * Retrieves representation of an instance of University
     * @return an instance of String
     */
    @Path("/param")
    @GET
    @Produces("application/xml")
    public String getFormData(@FormParam("username")String username ,@FormParam("password")String password)
    {
        return "Your UserName is : " +username +" & Password is : "+password;
       
    }
   
    @GET
    @Path("/queryparam")
    public Response getQueryData(@QueryParam("username") String username,@QueryParam("Password")String password)
    {
       
        String info="Username is: "+username+""+"password is: "+password;
        return Response.status(200).entity(info).build();
       
    }
   
    @GET
    @Path("/pathparam/{username}/{password}")
    public Response getPathData(@PathParam("username") String Username,@PathParam("password")String Password)
    {
       
        String info="UserName is :"+Username+"Password is :"+Password;
       
       
        return Response.status(200).entity(info).build();
       
       
       
    }
   
    @GET
    @Path("/matrixparam")
   
    public Response GetMatrixParam(@MatrixParam("username")String Username,@MatrixParam("password")String Password)
    {
   String info="UserName is :"+Username+"Password is :"+Password;
       
       
        return Response.status(200).entity(info).build();
    }

}

Hope you will get my point
Thanks

Testing a Restful web service is similar to testing a Soap web service.so i am not going to discuss it next time.
if you have any query regarding webservice than ping me.
next time i will write on how to how to generate json/xml document using jax-rs and how to integrate Spring ,hibernate & jsf into a single web application. 

for any query ping me on pathak.nisarg@yahoo.com




Monday 16 December 2013

JAX-RS


JAX-RS

Hello Friends hope you All are aware of Restful web services.if not than let me put something about Restful web service.There are two ways using which Client can access web service
(1) SOAP
(2) Restful

The key Difference between Soap web service and Restful web service is using Restful web service is in Restful web service client can access resource using its Uri.in soap web service client have to go through WSDL(WebService Description Language) in order to access web service.here i am using jetty plugin which is http server inorder to handle http request initiated by client .you need to add this plugin into project.


i am defining university Resource which consist of various web methods.getData(),getHTMLUniversityInfo(),getStudentInfo() etc.note that i am pulling out data using jdbc API that means is i am integrating jdbc with restful web services.

Restful web service architecture will look like given below:



in order to deploy web application i need to have one jsp page to make sure that application is successfully deployed on web server.even if it is of no use.


//Static Connection Class
package org.demo.jaxrs;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionUtil
{
   
   
    private static Connection conn;

    public static Connection getConn()
    {
        return conn;
    }

    public static void setConn(Connection conn) {
        ConnectionUtil.conn = conn;
    }
   
    public static Connection  getConnection()
    {
       
        try
        {
            Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
            conn=DriverManager.getConnection("jdbc:derby://localhost:1527/sample,create=true","app","app");
           
           
        }
        catch(ClassNotFoundException cn){cn.printStackTrace();}
        catch (InstantiationException e) {e.printStackTrace();}
        catch (IllegalAccessException e) {e.printStackTrace();}
        catch (SQLException e) {e.printStackTrace();}
       
       
        return conn;
       
    }
   
}
//University Resource ,can be pulled up as a Restful web service
package org.demo.jaxrs;




import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.sql.PreparedStatement;
//import javax.enterprise.inject.Produces;
import javax.websocket.server.PathParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;


//using jax-rs ,the resource can be accessed using uri where as in jax-ws ,client have to go through wsdl
@Path("/university")
//university is resource that client can access

public class University
{

      
//i am using precompiled version of query
    ResultSet rs;
    PreparedStatement ps;
   
   
    @GET
   
    @javax.ws.rs.Produces(MediaType.TEXT_PLAIN)
   
    public String getData()
    {
        String rollno="";
        String name="";
        try
        {
            ps=ConnectionUtil.getConnection().prepareStatement("select * from university");
            rs=ps.executeQuery();
          
            while(rs.next())
            {
                  rollno = rs.getString("Rollno");
                    name = rs.getString("name");
                  
                  
            }
          
        } catch (SQLException e){e.printStackTrace();}
      
      
      
        return  rollno.toString()+name.toString();
    }
        @GET
      
        @javax.ws.rs.Produces(MediaType.TEXT_PLAIN)
      
        public String getHTMLUniversityInfo()
        {
            return "<html>" +"<title>"+"University information"+"</title>"+"<body><h1>"+"Name -Indian University"+"</body></h1>"+"</html>";
          
        }
      
        @GET
        @Path("{studentrollno1}/{name}")

      
        //you can also use return type as a responsebuilder which returns status code if it successfully compiles
        @javax.ws.rs.Produces(MediaType.TEXT_PLAIN)
        public String getStudentInfo(@PathParam("studentrollno1") String roll1,@PathParam("name") String name)
        {
            int count =0;
          
          
            try
            {
                ps=ConnectionUtil.getConnection().prepareStatement("select * from university where (first_name = ? or last_name = ?) and address = ?");
                rs=ps.executeQuery("select * from university ");
              
                ps.setString(1, roll1);
                ps.setString(2, name);
              
                 count=ps.executeUpdate();
              
              
            }
            catch (SQLException e) {e.printStackTrace();}
          
          
          
          
            return "you sent me  roll number & name  using path param annotation : "+roll1+"roll no: 2"+name+"with Update is :"+count;
        }
      
        @GET
        @Path("{filename}")
      
      
        @javax.ws.rs.Produces(MediaType.TEXT_PLAIN)
        public Response getFileInTextFormat(@PathParam("fileName") String fileName)
        {
          
                System.out.println("File Requested is :  "+fileName);
      
              
                if(fileName==null || fileName.isEmpty())
                {
                    ResponseBuilder response=Response.status(Status.BAD_REQUEST);
                  
                    return response.build();
                  
                }
                File file=new File("D:/demoTxtFile.txt");
              
              
                ResponseBuilder response=Response.ok((Object)file);
                    response.header("Content-Disposition","attatchment;filename=\"howtodoinjava.txt\"");
      
                return response.build();
              
        }
        @GET
        @Path("{fileName}")
          
      
        @javax.ws.rs.Produces("image/jpeg")

            public Response getFileInJpegFormat(@javax.ws.rs.PathParam("fileName") String fileName)
            {
                System.out.println("File Requested is : "+fileName);
              
                if(fileName.isEmpty() || fileName==null)
                {
                    ResponseBuilder response=Response.status(Status.BAD_REQUEST);
                    return response.build();
                }
                File file= new File("d:/demoJpegFile.jpeg");
                ResponseBuilder response=Response.ok((Object)file);
              
                response.header("Content-Disposition","attatchment;filename=\"sample.jpeg\"");
                return response.build();
              
            }

}


web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">

    <display-name>HelloWorld Application</display-name>
    <description>
        This is a simple web application with a source code organization
        based on the recommendations of the Application Developer's Guide.
    </description>

    <servlet>
        <servlet-name>Jersey Rest Services </servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Jersey Rest Services</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>    

i can use restului-client in order to test restful url's .i will write how to test restful web service into the next session.

for any query or improvement in blog ping me on pathak.nisarg@yahoo.com


Thanks













Testing JAX-WS

Hello friends it's very easy to test soap url's.you should download SOAP-UI plugin from official site of  soap-ui .you can implementation of soap web service as well as restful web service using soap-ui plugin.
(Note: i am using glashfish as an application server)


Steps to follow :
(1) Create new project  from file->new
(2)  Enter name of project & location of wsdl document
(3) select webmethod which you want to test


(4) supply parameters  & test outcome of web method.




thanks
for query ping me on pathak.nisarg@yahoo.com

Sunday 15 December 2013

JAX-WS


JAX-WS

Hello Friends i hope you all are aware of web -services.i am going to demonstrate you simple example of soap web service using glashfish server. before going into details of JAX-ws you need to have understanding of wsdl docuement.when client sends Request it will be soap request & soap response will be returned by container.however in case of Glashfish ,it autogenerates wsdl document.

i personally advice you to go through elements of wsdl document  prior to going into the JAX-WS. some of the elements of WSDL document are <definations>,<operation>,<service>,<porttype>,<binding>,<type> etc.

If i want to make web service than i will simply mark class as @WebService. by default all methods defined in the class will be  exposed as web methods.for detail understanding of JAX-WS go to http://oak.cs.ucla.edu/cs144/reference/WSDL/

i am going to demonstrate you product Catalog Web Service.

Sample Code:
//Model Data
package org.demo.model;

public class Product
{
    private String name;
    private String sku;
    private double price;
   
    public String getName() {
        return name;
    }

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

    public String getSku() {
        return sku;
    }

    public void setSku(String sku) {
        this.sku = sku;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

   
    public Product() { }
   
    public Product(String name,String sku,double price)
    {
        this.name=name;
        this.sku=sku;
        this.price=price;
       
    }
   
   

}

//Service Implementation consisting of bussiness logic

package org.demo.bussiness;

import java.util.*;

import javax.jws.WebMethod;

public class ProductServiceImpl
{
   
    List<String> booklist =new ArrayList<>();
    List<String> musiclist=new ArrayList<>();
    List<String> movielist= new ArrayList<>();

    public ProductServiceImpl()
    {
    booklist.add("Inferno");
    booklist.add("Joyland");
    booklist.add("The Game Of Thrones");

    musiclist.add("Random Access Memories");
    musiclist.add("Night Visions");
    musiclist.add("Unorthodox Jukebox");

    movielist.add("Oz the Great and Powerful");
    movielist.add("Despicable Me");
    movielist.add("Star Trek Into Darkness");
    }
   
    public List<String> getProductCategories()
    {
        List<String> categories = new ArrayList<>();
       
        categories.add("book list");
        categories.add("Music list");
        categories.add("Movie list");
       
        return categories;
       
       
    }
    public List<String> getProducts(String catname)
    {
        switch (catname.toLowerCase()) {
        case "books":
            return booklist;
        case "music":
            return musiclist;
        case "movies":
            return movielist;
        }
        return null;
    }
   
    public boolean addproduct(String  category,String product)
    {
        switch (category.toLowerCase()) {
        case "books":
            booklist.add(product);
            break;
        case "music":
            musiclist.add(product);
            break;
        case "movies":
            movielist.add(product);
            break;
        default:
            return false;
        }
        return true;
       
       
    }


}


//End Point Interface which client will able to see
package org.demo.nisarg;

import javax.jws.WebMethod;
import javax.jws.WebResult;
import javax.jws.WebService;
import java.util.*;

@WebService(name="TestmartCatalog" ,targetNamespace="nisargpathak.blogspot.in")
public interface ProductCatalogInterface
{
   
    @WebMethod(action="fetch_categories", operationName="fetchCategories")
    public List<String> getProductCategories();
   
   
    @WebMethod
    public List<String> getProducts(String productname);
   
    @WebMethod
    public boolean addproduct(String productname,String category);
   
    @WebMethod
    public List<String> getProductv2(String productname);
   

}

//Service First Approach


package org.demo.nisarg;

import java.util.List;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

import org.demo.bussiness.ProductServiceImpl;


@WebService(endpointInterface="org.demo.nisarg.ProductCatalogInterface", portName="TestMartCatalogPort", serviceName="TestMartCatalogService")
public class ProductCatalog implements ProductCatalogInterface
{

    ProductServiceImpl product= new ProductServiceImpl();
   
    @Override
    @WebMethod
    public List<String> getProductCategories()
    {
       
        return   product.getProductCategories();
    }

    @Override
    @WebMethod
    public List<String> getProducts(@WebParam(partName="pName")String productname)
    {
        // TODO Auto-generated method stub
        return product.getProducts(productname);
    }

    @Override
    @WebMethod
    public boolean addproduct(@WebParam(partName="Product-Name")String productname, @WebParam(partName="Category")String category)
    {
        // TODO Auto-generated method stub
        return  product.addproduct(productname, category);
    }

    @Override
    @WebMethod
    public List<String> getProductv2(String productname)
    {
        // TODO Auto-generated method stub
        return product.getProducts(productname);
    }

}


WSDL Document :
definitions targetNamespace="http://nisarg.demo.org/" name="TestMartCatalogService">
<import namespace="www.testmart.com" location="http://nisarg-pc:8080/jax-ws_demo/TestMartCatalogService?wsdl=1"/>
<binding name="TestMartCatalogPortBinding" type="ns1:TestmartCatalog">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>

<operation name="fetchCategories">
<soap:operation soapAction="fetch_categories"/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
<operation name="getProducts">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
<operation name="addproduct">
<soap:operation soapAction=""/>
<input><soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
<operation name="getProductv2">
<soap:operation soapAction=""/>
<input><soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>
<service name="TestMartCatalogService">
<port name="TestMartCatalogPort" binding="tns:TestMartCatalogPortBinding">
<soap:address location="http://nisarg-pc:8080/jax-ws_demo/TestMartCatalogService"/>
</port>
</service>
</definitions>

Run it on Glashfish you can find tester link as well in order to test functionality of web service.

Thanks
for any query Regarding post ping me on pathak.nisarg@yahoo.com

Friday 13 December 2013

SAX(Simple API For XML) parser

SAX(Simple API For XML) parser


Hello Friends .Today i am going to demonstrate you how to parse xml data using SAX(Simple API for XML) parser. The Basic Differance between sax & dom parser is dom parser loads entire document into memory  where as sax parser do not load entire document into memory.so it is convinient way for parsing large xml data.

SAX parser is Event based parser.it does not create representation of xml tree.it simply parse xml data based on Events.we need to write handler class  inorder to keep track of event such as starting of element,ending of element & when character is encountered.

SAX uses some callback methods to parse and read the xml accordingly. It uses three callback methods listed below :

(1)public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException

(2)public void characters(char[] ch, int start, int length)
            throws SAXException

(3) public void endElement(String uri, String localName, String qName)
            throws SAXException


The Sample code is as given below:


package org.saxdemo;

public class Student
{
   
    private String id;
    private String name;
    private String stream;
   
   
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getStream() {
        return stream;
    }
    public void setStream(String stream) {
        this.stream = stream;
    }
   
   

}

//Handler class
package org.saxdemo;
import java.util.*;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class Handler extends DefaultHandler
{
   
    private Student student;
    public Student getStudent() {
        return student;
    }
    public void setStudent(Student student) {
        this.student = student;
    }
    public List<Student> getStudList() {
        return studList;
    }
    public void setStudList(List<Student> studList) {
        this.studList = studList;
    }
    private List<Student> studList;
   
   
    private boolean  bname;
    private boolean bstream;
   
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException
    {
       
        if(qName.equals("student"))
        {
           
            String id=attributes.getValue("id");
            student=new Student();
           
            student.setId(id);
           
            if(studList==null)
            {
                studList=new ArrayList<>();
               
            }
               
           
           
           
        }
        else if(qName.equalsIgnoreCase("name"))
        {
            bname=true;
        }
        else if(qName.equalsIgnoreCase("stream"))
                {
                    bstream=true;
                }
               
    }
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException
   {
       
        if(qName.equalsIgnoreCase("employee"))
        {
        studList.add(student);
        }
       
    }
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException
    {
       
        if(bname)
        {
            student.setName(new String(ch,start,length));
           
        }
        if(bstream)
        {
            student.setStream(new String(ch,start,length));
           
        }
       
    }
   
   
}



Sax parser Implementation :
package org.saxdemo;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import java.io.*;
import java.util.*;
public class XmlParser
{
    public static void main(String args[])
    {

        //configure sax based parser
        SAXParserFactory saxparserfactory=SAXParserFactory.newInstance();

try
{
   
    //object object for sax based parser
   
       
    SAXParser saxparser=saxparserfactory.newSAXParser();
    Handler handler=new Handler();
//parsing of xml data
    saxparser.parse(new File("D:\\students.xml"), handler);
   
    List<Student> studlist=handler.getStudList();
    for(Student s:studlist)
    {
        System.out.print(s);
       
    }
   
   
}
catch(ParserConfigurationException | SAXException | IOException e)
{
    e.printStackTrace();
   
}
    }

}   

i hope you got my point
for any query & improvement ping me on pathak.nisarg@yahoo.com

Wednesday 11 December 2013

JAXB

JAXB 


Hello Friends.what you will do if you want to marshal /unmarshal java objects ? well,there are 2-3 techniques which comes into your mind that is .(1)Sax Parser,(2)Dom Parser ,(3)JAXB



JAXB is binding api which is used to marshal & unmarshal java objects into/from xml.well the class which is annotated with javax.xml.binding annotations can only be processed by jaxb runtime .so whatever  field you will declare into java class ,that everything is processed by jaxb engine. i am going to show you simple annotations which will be used in code:


@XmlRootElement=> Root Element of xml File

@XmlType(propOrder={"countryname","CountryPopulation","listofStates"}) => Used to specify ordering of xml elements.

@XmlElement=> used to specify xml element .

 JAXB Architecture:

Sample Code :
 package org.demo;

import java.io.File;
import org.apache.commons.logging.log4j.*;
import java.util.*;
import java.util.logging.Logger;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JavatoXml
{
    public static void main(String args[])
    {
      
         //Logger log = Logger.getLogger(
                //JavatoXml.class.getName());
      
            Country india=new Country();
          
            india.setCountryName("India");
            india.setCountryPopulation(5000000);
          
            List<State> states= new ArrayList<State>();
   
            State gujarat=new State();
          
            gujarat.setStatePopluation(6000000);
          
            states.add(gujarat);
          
            //india.setListofstates(states);
            try
            {
                JAXBContext jaxbcontext = JAXBContext.newInstance(Country.class);
              
                    Marshaller  jaxbmarsheller= jaxbcontext.createMarshaller();
                  
                    File f = new File("d:\\ocjp\\CountryRecord.xml");
                  
                    jaxbmarsheller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
                  
                jaxbmarsheller.marshal(india, f);
              
                System.out.println("Xml file created Successfully...!!!");
                  
            }
            catch(JAXBException  e)
            {
              
            }
          
          
    }

}

How Marshelling is done:
(1)
JAXBContext-> It provides an abstractinon for managing infomration necessary to 
implement the jaxb.it informs JAXB runtime that this object or class will be bind into
xml
 
(2) 
Marsheller->it tells JAXB runtime to marshell given instance of class.
 
 
Sample Code:
 

package org.demo;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.util.*;


@XmlRootElement

@XmlType(propOrder={"countryname","CountryPopulation","listofStates"})




public class Country
{
 
 
 @XmlElement
 private String countryName;
 @XmlElement
 private double countryPopulation;
 @XmlElement
 private ArrayList<State> listofstates;
 
 public Country() { }
 
 public String getCountryName() {
  return countryName;
 }

 @XmlElement
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 }

 public double getCountryPopulation() {
  return countryPopulation;
 }

 @XmlElement
 public void setCountryPopulation(double countryPopulation) {
  this.countryPopulation = countryPopulation;
 }

 public ArrayList<State> getListofstates() 
 {
  return listofstates;
 }

 @XmlElementWrapper(name="stateList")
 @XmlElement(name="state")
 public void setListofstates(ArrayList<State> listofstates) {
  this.listofstates = listofstates;
 }

 
 
 
 
 

}
package org.demo;

import javax.xml.bind.annotation.XmlRootElement;



@XmlRootElement(namespace="org.demo.Country")
public class State
{
 
 private String statename;
 private long statePopluation;
 
 
 public State() { }
 public String getStatename() {
  return statename;
 }
 public void setStatename(String statename) {
  this.statename = statename;
 }
 public long getStatePopluation() {
  return statePopluation;
 }
 public void setStatePopluation(long statePopluation) {
  this.statePopluation = statePopluation;
 }

 
 

}


package org.demo;

import java.io.File;
import org.apache.commons.logging.log4j.*;
import java.util.*;
import java.util.logging.Logger;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JavatoXml 
{
 public static void main(String args[])
 {
  
   Country india=new Country();
   
   india.setCountryName("India");
   india.setCountryPopulation(5000000);
   
   List<State> states= new ArrayList<State>();
 
   State gujarat=new State();
   
   gujarat.setStatePopluation(6000000);
   
   states.add(gujarat);
   
   //india.setListofstates(states);
   try
   {
    JAXBContext jaxbcontext = JAXBContext.newInstance(Country.class);
    
     Marshaller  jaxbmarsheller= jaxbcontext.createMarshaller();
     
     File f = new File("d:\\ocjp\\CountryRecord.xml");
     
     jaxbmarsheller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
     
    jaxbmarsheller.marshal(india, f);
    
    System.out.println("Xml file created Successfully...!!!");
     
   }
   catch(JAXBException  e)
   {
    
   }
   
   
 }

}

this is how java object is marshaled into xml .

thanks
for any query ping me on pathak.nisarg@yahoo.com
 
 
 
 
 
 
 
 
 

Spring Boot SSL configuration -Tomcat Server

Hi Friends hope you all are doing well. Today I am going to demonstrate about how to configure SSL in Spring boot web Application. Need o...