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
















 

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




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