Monday 30 April 2012

Configure HTTPS in local server(Tomcat)

The below instructions explain how to configure Tomcat for SSL/TLS. After following below instructions, users may access web applications securely through port 8443.  


The instructions show how to generate a self-signed certificate that browsers can use to authenticate the server. Consequently, browsers will not be able verify the authenticity of the certificate because it will not have been signed by a trusted third party whose certificates are pre-installed in the client system or added to the client system but still you can use HTTPS without doing any of the above procedures, but your users will need to accept an un-trusted certificate each time they visit your site.


Create Keystore with Self-Signed Certificate


You need to generate a self-signed certificate and store it in a file called keystore under the conf folder within the Tomcat. To do this, run the keytool command as shown below, leaving the storepass and keypass values both equal to changeit. This command may take a long time to complete, so be patient. After generating the keystore file, move it into the conf folder.
 
To run the command, you need to be at an operating system command prompt.  The keytool command is part of the Java SDK. If your system only contains the Java JRE, then you will need to install the JDK to get access to this command. 

Running keytool under Windows
keytool -genkey ^
        -keystore keystore ^
        -alias tomcat ^
        -keyalg RSA ^
        -keysize 2048 ^
        -dname CN=localhost ^
        -storepass changeit ^
        -keypass changeit
If you get a message that the command is unknown, then you need to provide the
full pathname to the keytool executable 
(or add the bin folder in your jdk installation to the path variable in your environment).

The keystore file will be created at the level where you are running the above command. eg. if you are running the command from C:/ then search the file in c:/ itself. This file then you need to copy inside the tomcat conf folder.

Running keytool under Linux and Mac OS X

keytool -genkey \
        -keystore keystore \
        -alias tomcat \
        -keyalg RSA \
        -keysize 2048 \
        -dname CN=localhost \
        -storepass changeit \
        -keypass changeit
The CN variable in the certificate should contain the domain name of your server.Because you are running Tomcat and your browser from the same machine,setting theCN variable to localhost as done above is OK.However, if you wanted to access Tomcat from a remote machine, you would need to replace localhost with the domain name of the machine on which Tomcat is running. 
Once you have moved the file keystore under the apache-tomcat-7.0.23/conf folder then you need to modify the server.xml file under the apache-tomcat-7.0.23/conf folder. Now edit the file and uncomment the Connector element with the port 8443. for your connivence i am pasting the commented code in my server.xml file which you need to uncomment it.

   <!--
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

then add the below attribute to the above element 
keystoreFile="conf/keystore"
The following is an example Connector element that sets up HTTPS on port 8443.

<Connector port="8443"
           maxThreads="200" 
           minSpareThreads="5" 
           maxSpareThreads="75"
           enableLookups="true" 
           disableUploadTimeout="true"
           acceptCount="100"
           scheme="https"
           secure="true"
           SSLEnabled="true"
           clientAuth="false"
           sslProtocol="TLS"
           keystorePass="changeit"
           keystoreFile="conf/keystore" />
 
If you are running Windows Vista, regular users may not have the privileges to modify server.xml. In this case, you need to edit server.xml as adminstrator. To do this, right click on wordpad in the Windows start menu and select run as adminstrator.

once you are done the above procedure then you need to run your application and test it using 8443 port.

https://localhost:8443/<ServletContest>


A Simple News Feed Application

We will be using RSS for achieving the simple news feed application. People interpret the acronym RSS in several ways. For example, you may hear that RSS stands for Rich Site Summary, or Really Simple Syndication, or even RDF Site Summary. Most people simply refer to the technology as RSS. RSS is an XML-based format that allows the syndication of lists of hyperlinks, along with other information, or metadata, that helps viewers decide whether they want to follow the link.


RSS allows peoples’ computers to fetch and understand the information, so that all of the lists they’re interested in can be tracked and personalized for them. It is a format that’s intended for use by computers on behalf of people, rather than being directly presented to them (like HTML). To enable this, a Web site will make a feed, or channel, available, just like any other file or resource on the server. Once a feed is available, computers can regularly fetch the file to get the most recent items on the list.


 FEED


A feed contains a list of items or entries, each of which is identified by a link. Each item can have any amount of other metadata associated with it as well. A simple example of feed


<item>
  <title>test</title>
  <link>any site which provide data in RSS</link>
  <description>description goes here</description>
</item>
---------------------------------------------------------------

Flow of information for RSS
---------------------------------------------------------------

---------------------------------------------------------------
Create the simple news feed application
-----------------------------------------


Create a simple dynamic web project using the eclipse. Now create a new servlet by name RSSServlet


RSSServlet



package com.lnt.web;
 
import java.io.IOException;
import java.net.URL;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

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 RSSServlet extends HttpServlet {

 private Logger logger = Logger.getLogger(this.getClass());
 private RequestDispatcher homeJsp;
 
 @Override
 public void init(ServletConfig config) throws ServletException {
  ServletContext context = config.getServletContext();
  homeJsp = context.getRequestDispatcher("/WEB-INF/jsp/home.jsp");
 }

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  logger.debug("Retrieving yahoo news feed");
  URL url = new URL("http://rss.news.yahoo.com/rss/tech");
  SyndFeedInput syndFeedInput = new SyndFeedInput();
  SyndFeed syndFeed = null;
  XmlReader xmlReader = new XmlReader(url);
  try {
   syndFeed = syndFeedInput.build(xmlReader);
  } catch (IllegalArgumentException e) {
   logger.error("", e);
  } catch (FeedException e) {
   logger.error("", e);
  }
  logger.debug("Forwarding to home.jsp");
  req.setAttribute("syndFeed", syndFeed);
  homeJsp.forward(req, resp);
 }
}

you need to add the below mentioned library to your project.

1. jdom-1.1.3.jar
2. log4j-1.2.14.jar
3. rome-1.0.jar
---------------------------------------------------------------

Create a jsp inside the WEB-INF/jsp folder of the project.

home.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="com.sun.syndication.feed.synd.SyndFeed" %> 
<%@ page import="com.sun.syndication.feed.synd.SyndEntry" %> 
<%@ page import="java.util.Iterator" %> 
<jsp:useBean id="syndFeed" scope="request" type="SyndFeed" />
<html>
   <head>
      <title>website</title>
   </head>
   <body>
      <h1>Home</h1>
      <h2><%=syndFeed.getTitle()%></h2>
      <ul>
         <% 
           Iterator it = syndFeed.getEntries().iterator();
           while (it.hasNext())
           {
              SyndEntry entry = (SyndEntry) it.next();
         %>
            <li>
               <a href="<%=entry.getLink()%>"><%=entry.getTitle()%></a>
            </li>
         <% } %>
      </ul>
   </body>
</html>

Some times the above jsp may show error as undefined type Syndfeed, please ignore the same.

In the deployment Descriptor add the mapping as below.
---------------------------------------------------------------


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>RSStest</display-name>
    <servlet>
      <servlet-name>home</servlet-name>
      <servlet-class>com.lnt.web.RSSServlet</servlet-class>
   </servlet>
   <servlet-mapping>
      <servlet-name>home</servlet-name>
      <url-pattern>/home</url-pattern>
   </servlet-mapping>
  
</web-app>


---------------------------------------------------------------



Required library


1. jdom-1.1.3.jar
2. log4j-1.2.14.jar
3. rome-1.0.jar



---------------------------------------------------------------

now run the project you should be able to see the news links in your page.

Monday 23 April 2012

Spring hibernate integration

In Spring the hibernate integration becomes easy and you need not to create separate hibernate.cfg.xml for the project. You can configure the hibernate settings in the spring web application context itself. Please find the simple project using the spring hibernate configuration.

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>CaptionContest</display-name>
<welcome-file-list>
<welcome-file>/home.html</welcome-file>
</welcome-file-list>

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

</servlet>

<servlet-mapping>
<servlet-name>SpringHibernate</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>


<session-config>
<session-timeout>30</session-timeout>
</session-config>

</web-app>

----------------------------------------------------------------------------

SpringHibernate-servlet.xml

Please replace your username, password and database name of the database in the below file in the respective positions.


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

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp"></property>
</bean>


<bean id="myDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/YourDatabasename" />
<property name="username" value="YourUsername" />
<property name="password" value="YourPassword" />
</bean>

<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>com.lnt.spring.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<prop key="hibernate.c3p0.minPoolSize">5</prop>
<prop key="hibernate.c3p0.maxPoolSize">20</prop>
<prop key="hibernate.c3p0.timeout">600</prop>
<prop key="hibernate.c3p0.max_statement">50</prop>
<prop key="hibernate.c3p0.testConnectionOnCheckout">false</prop>
</props>
</property>
</bean>
<bean id="user" class="com.lnt.spring.User" />
<bean name="/home.html" class="com.lnt.spring.TestController" >
<property name="user" ref="user" />
<property name="testDAO" ref="testDAO"></property>
</bean>

<bean id="testDAO" class="com.lnt.spring.TestDAO">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>

</beans>

-------------------------------------------------------------------------

TestController.java



package com.lnt.spring;

import java.util.List;
import java.util.ListIterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public class TestController extends MultiActionController{
private User user;
private TestDAO testDAO;
public void setTestDAO(TestDAO testDAO) {
this.testDAO = testDAO;
}

public void setUser(User user) {
this.user = user;
}

public ModelAndView home(HttpServletRequest request,HttpServletResponse response) throws Exception{
List<User> list=testDAO.loginRequest("prajith", "prajith");
ListIterator<User> itr=list.listIterator();
System.out.println(list.get(0).getFname());
System.out.println("list size :"+list.size());
while(itr.hasNext()){
user=itr.next();
System.out.println("user fname  :"+user.getFname());
}
return new ModelAndView("home","user",user.getFname());
}
}





------------------------------------------------------------------------------------------------------
TestDAO.java


package com.lnt.spring;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;


public class TestDAO {
private HibernateTemplate hibernateTemplate;

public void setSessionFactory(SessionFactory sessionFactory){ 
this.hibernateTemplate = new HibernateTemplate(sessionFactory); 

public List<User> loginRequest(String userName, String password) throws Exception{
List<User> list=hibernateTemplate.find("from User u where u.username = ? and u.password=? ",new Object[] {userName,password});
System.out.println("list size :"+list.size());
return list;
}
}


-------------------------------------------------------------------------

User.java


package com.lnt.spring;


import java.io.Serializable;
import javax.persistence.*;


/**
 * The persistent class for the user database table.
 * 
 */
@Entity
public class User implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

private String fname;

private String password;

private String username;

    public User() {
    }

public int getId() {
return this.id;
}

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

public String getFname() {
return this.fname;
}

public void setFname(String fname) {
this.fname = fname;
}

public String getPassword() {
return this.password;
}

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

public String getUsername() {
return this.username;
}

public void setUsername(String username) {
this.username = username;
}

}
----------------------------------------------------------------------------------------------------
home.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>
<h1>The user First Name "${user}" is coming form the database using spring hibernate</h1>
</body>
</html>

--------------------------------------------------------------------------

Please find the project structure of the project.


--------------------------------------------------------------------------

Please note the required jar list.



1. antlr-2.7.6.jar
2 .commons-collections-3.1.jar
3. commons-logging.jar
4. dom4j-1.6.1.jar
5. hibernate-jpa-2.0-api-1.0.0.Final.jar
6. hibernate3.jar
7. javassist-3.9.0.GA.jar
8. jcl-over-slf4j-1.6.4-sources.jar
9. jstl.jar
10. jta-1.1.jar
11. mysql-connector-java-5.1.18-bin.jar
12. slf4j-api-1.6.4.jar
13. slf4j-jcl-1.6.4.jar
14. slf4j-log4j12-1.6.4-sources.jar
15. spring-webmvc.jar
16. spring.jar
17. standard.jar


Saturday 21 April 2012

Properties file usage in Spring framework

Create a property file with the required messages and keep the file under the project class path. below is a sample property file.

default-message.properties


menu.one=testing property file
report.mainmenu.one=Report one
report.mainmenu.two=Report two
report.mainmenu.three=Report three
report.mainmenu.four=Report four
report.mainmenu.five=Report five
---------------------------------------------------------------------------------


In your web application context xml specify the bean as below



        <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
  <property name="basename" value="/WEB-INF/classes/default-messages"/>
</bean>

When ever you want to use the property value in the backend you can use the Spring injection and inject the property value to the class. Example as below.

<bean name="/propertyFile.html" class="com.lnt.rg.web.ReportController" >
<property name="template" ref="basicTemplate" />
<property name="messages" ref="messageSource" />
</bean>
---------------------------------------------------------------------------------

Usage of the property value in the class. example as below.

ReportController.java


package com.lnt.rg.web;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.MessageSource;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.lnt.rg.common.Template;

public class ReportController extends MultiActionController {
protected final Log logger=LogFactory.getLog(getClass());
private Template template;
private MessageSource messages;

    public void setMessages(MessageSource messages) {
        this.messages = messages;
    }

public void setTemplate(Template template) {
this.template = template;
}
public ModelAndView propertyFile(HttpServletRequest request, HttpServletResponse response){
if(messages!=null){
String str=messages.getMessage("menu.one", null, null);
System.out.println("str    ::::"+str);
}else{
System.out.println("messageSourc is null");
}
return new ModelAndView("test");
}
}



As shown above the we can use the property value in backend(in java code).

------------------------------------------------------------------------------------

Getting the value from the property file to the frontend JSP. below is the code.

test.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>

<h1><spring:message code="menu.one" /></h1>
</body>
</html>