Thursday 16 January 2014

Xml Marshalling/Unmarshaling using Spring Castor

 Spring Castor

Hello Friends hope you are fine .there are two ways using which we can perform Marshalling of java objects into xml and unmarshalling of xml element into tree of java object using spring framework.

there are two ways of unmarshalling/marshalling using spring:
(1)Spring Xstream
(2) Spring Castor

i am going to demonstrate Spring Castor.The Key differance between spring castor and oxm is that in cse of Spring castor one extra configuration file is required inorder to map java object with xml.

You need to add castor-1.3 jar and other core spring jars required to run spring base  application:

Project Structure :

sample code is given below :


Pojo Class
package org.castor.pojo;
//object that we want to marshal
public class Student
{
    private int id;
    private String name;
    private String college;
   
    public Student() { }
    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 getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }
   

}

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" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">


<bean id="CastorMarshelingBean" class="org.springframework.oxm.castor.CastorMarshaller">
<property name="targetClass" value="org.castor.pojo.Student"></property>
<property name="mappingLocation"  value="mapping.xml"></property>
</bean>



</beans>



mapping.xml : to map java objets with corresponding xml element
<?xml version="1.0" encoding="UTF-8"?>
      
    <mapping> 
        <class name="org.castor.pojo.Student"> 
          <map-to xml="Student"/> 
          <field name="id" type="integer"> 
             <bind-xml name="id" node="element"/> 
          </field> 
          <field name="name" type="string"> 
             <bind-xml name="name" node="element"/> 
          </field> 
          <field name="college" type="string"> 
             <bind-xml name="college" node="element"/> 
          </field> 
            </class> 
    </mapping>

Client Class

package org.castor.client;

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

import javax.xml.transform.stream.StreamResult;

import org.castor.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.XmlMappingException;

public class Client
{
    public static void main(String args[]) throws XmlMappingException, IOException
    {
   
        ApplicationContext context= new ClassPathXmlApplicationContext("applicationcontext.xml");
        Marshaller m=(Marshaller) context.getBean("CastorMarshelingBean");
       
        Student s=new Student();
        s.setId(1);
        s.setName("nirali");
        s.setCollege("Semcom");
       
        m.marshal(s,new StreamResult(new FileWriter("D:\\Student.xml")));
       
       
        System.out.println("Task Completed!!!");
       
    }

}

 the console will look like given below:





Thanks for reading this artilcle  for any query ping me  related to this post ping me on pathak.nisarg@yahoo.com
Regards
 


 




Monday 13 January 2014

ContentNagotiationViewResolver example using Spring MVC

ContentNagotiationViewResolver  using Spring MVC

Hello Friends.hope you are doing well.today i am going to demonstrate you ContentNagotiationViewResolver .suppose i want to access the same resource with differant media types.than client can access the resource using ContentNagotiationViewResolver.suppose client want xml form of resouce than he can get it using ContentNagotiationViewResolver  feature of spring mvc.

Spring oxm and jackson Api should be on classpath for execution of above code:

Sample code i am going to demonstrate is given below:

Model Class (jaxb annotated)


package org.demo.model;

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

@XmlRootElement
public class Student
{
   
    int id;
   
    String name;
   

    public Student() { }
    public Student(int id,String name)
    {
        this.id=id;
        this.name=name;
    }
    public int getId() {
        return id;
    }
   
    @XmlElement
    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }
    @XmlElement
    public void setName(String name) {
        this.name = name;
    }


}

StudentController.java

package org.demo.controller;

import org.demo.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value="/Student")
public class StudentController
{

@RequestMapping(value="{id}/{name}",method=RequestMethod.GET,produces="application/json")
public String getStudent(@PathVariable int id,@PathVariable String name,ModelMap model)
{
        Student s=new Student(id,name);
    model.addAttribute("student", s);
       
    return "Data";
   
}
}
 

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>SpringContentNagotioationViewResolver</display-name>
  <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
  <servlet-name>ContentNagotiation</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  <servlet-name>ContentNagotiation</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

ContentNagotiation-servlet.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">


 <context:component-scan base-package="org.demo.controller"></context:component-scan>
 <mvc:annotation-driven/>
 <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
 <property name="order" value="1"></property>

 <property name="mediaTypes">
 <map>
         <entry key="json" value="application/json"></entry>
         <entry key="xml" value="application/xml"></entry>
   </map>
 </property>

 <property name="defaultViews">
        <list>
          <!-- JSON View -->
          <bean
            class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
          </bean>

       

          <!-- JAXB XML View -->
          <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
            <constructor-arg>
                <bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
                   <property name="classesToBeBound">
                    <list>
                       <value>org.demo.model.Student</value>
                    </list>
                   </property>
                </bean>
            </constructor-arg>
          </bean>
         </list>
      </property>
      <property name="ignoreAcceptHeader" value="true" />

    </bean>

   
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="order" value="2" />
        <property name="prefix">
            <value>/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

 </beans>


Data.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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

Student Id: ${student.id}
Student Name: ${student.name}
</body>
</html>

The output of the code is look like below:








i hope you will get my point.for any query ping me on pathak.nisarg@yahoo.com.
Thanks for reading this article.
Regards.

Sunday 12 January 2014

Fetching RSS Feed Data

 Fetching RSS Feed Data 

Hello Friends ,today i am going to demonstrate you how to get RSS Feed using ROME API.in this example i am going to show you feeds from my blogspot.jars required for implementing below code is ROME.jar ,jdom 1.1 jar,purl-org-content-0.3.jar.
 
ROME represents syndication feeds (RSS and Atom) as instances of the com.sun.syndication.synd.SyndFeed interface.

Sample Code:


package org.demo.rssfeed;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;

import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

public class RssDemo
{
    public static void main(String args[]) throws IOException, IllegalArgumentException, FeedException
    {
        //you can define url as per your requirement
         //URL url  = new URL("http://nisargpathak.blogspot.com/feeds/6414895901982451683/comments/default");
        URL url  = new URL("http://nisargpathak.blogspot.com/feeds/5437369693711411335/comments/default");
         XmlReader reader = null;
           
            try {
               
                reader = new XmlReader(url);
                SyndFeed feed = new SyndFeedInput().build(reader);
                System.out.println("Feed Title: "+ feed.getAuthor());
          
               for (Iterator i = feed.getEntries().iterator(); i.hasNext();)
               {
                  SyndEntry entry = (SyndEntry) i.next();
                  System.out.println(entry.getTitle());
                      }
                  } finally {
                      if (reader != null)
                          reader.close();
                  }
    }
 

}
Sample Output is given below:









For any query ping me on pathak.nisarg@yahoo.com
Thanks for reading
Regards

Friday 3 January 2014

Spring MVC Restful Service

Spring MVC Restful Service
 
Hi friends .Today i am going to demonstrate you how spring negotiates with various kinds of content  such as xml,json.however there are two ways through which spring handles content.one is using @ResponseBody and another is using predefined view resolvers. i am going to demonstrate you how internal conversion is hanlded by @ResponseBody.i am showing example of how @ResponseBody converts incoming xml data into xml form.

Here is sample code:

Student.java

package org.demo.model;
import java.util.List;

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


@XmlRootElement(name="student")
public class Student
{
   
   
    private int id;
   
    private String name;
    private List<College> collegeList;
   
    public List<College> getCollegeList()
    {
        return collegeList;
    }
   
    @XmlElementWrapper(name="CollegeList")
   
    public void setCollegeList(List<College> collegeList)
    {
        this.collegeList = collegeList;
    }
    public Student() {}
    public Student(int id,String name)
    { this.id=id; this.name=name; }    
    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;
    }

   
}
 College.java

package org.demo.model;

import javax.xml.bind.annotation.XmlRootElement;


@XmlRootElement(name="org.demo.model.Student")
public class College
{
    private int id;
    private String collegename;

    public College() {}
   

   
    public College(int id,String collegename) {super();this.id=id; this.collegename=collegename;}
    public int getId() {
        return id;
    }

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

    public String getCollegename() {
        return collegename;
    }

    public void setCollegename(String collegename) {
        this.collegename = collegename;
    }

   
}
XmlController.java

package org.demo.controller;

import java.util.ArrayList;
import java.util.List;

import org.demo.model.College;
import org.demo.model.Employee;
import org.demo.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/Student")
public class XmlController
{
//invoke in such a manner : http://localhost:8080/SpringXmlJson/Student/1/nisarg
    @RequestMapping(value="{id}/{name}", method = RequestMethod.GET,produces="application/xml")
    public @ResponseBody Student getStudentInXML(@PathVariable int id,@PathVariable String name)
    {

        Student student1 = new Student(id, name);
        College college1= new College(1,"semcom");
        College college2=new College(2,"NVPAS");
      

        List<College> l1 =new ArrayList<>();
        l1.add(college1);
        l1.add(college2);
        student1.setCollegeList(l1);
      
        return student1;
    }
  
 /*   @RequestMapping(value="/Json/{id}/{name}/{age}", method = RequestMethod.GET,produces="application/json")
    public @ResponseBody Employee getStudentInJson(@PathVariable int id,@PathVariable String name,@PathVariable String age)
    {

        Employee employee1= new Employee(id,name,age);
      
        return employee1;
    }*/
   
}

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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>SpringXmlJson</display-name>

 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
  <servlet>
      <servlet-name>xmltest</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
 
  <servlet-mapping>
      <servlet-name>xmltest</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>


Context File(xmltest-servlet.xml)

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

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="org.demo.controller" />

    <mvc:annotation-driven/>

    </beans>

the output will look like as given below:


however i found one bug here.i can't able to get json data if jackson & jaxb jars are already there in classpath.it still gives me same output in xml format.
Hope you will get  my point for any query ping me on pathak.nisarg@yahoo.com
thanks for reading this article.
regards



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
















 

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...