Thursday, July 31, 2014

struts example






Struts example

Below post shows how to build simple application with struts.

open eclipse -> project -> create dynamic Webproject->

provide name as - struts_sample [As you like]

select Dynamic web module version as 2.5

Then click on Finish button.

-> open the web.xml , which available inside WEB-INF folder

copy the below code and paste in side web.xml .
      
             action 
              org.apache.struts.action.ActionServlet     
               
                   config                   /WEB-INF/struts-config.xml              
              1
  
     
		       action   
		       *.do
    


-> Create xml and name it as struts-config.xml inside WEB-INF.
->open the struts-config.xml and paste the below code inside the struts-config.xml

	  
  


		 
		
			 
		
											
		 
		 
			
				
				
			
			
				
				
			
		
	
	


-> Now it's time to start our work like creating jsp files, form classes, action classes and need to add required jars.

-> first we will write jsp page. Here i am writting 4 jsp pages
1. login.jsp
2. welcome.jsp
3. adduser.jsp
4. success.jsp

-> create one folder inside WebContent with name jsp [WebContent/jsp/login.jsp] -- this is for login details which will have user name and password along with validation.
paste the below code inside login.jsp

	<%@taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%><%@taglib
	uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>



Login page



Login


-> create welcome.jsp [WebContent/jsp/welcome.jsp] -- this is for after successful login details .
paste the below code inside welcome.jsp
	
	<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>



Welcome page


	<%        String message = (String)request.getAttribute("message");    %>
	

Welcome User : <%= message %>

You have successfully logged in.

-> create adduser.jsp [WebContent/jsp/adduser.jsp] -- this contains user details along with required validation.
paste the below code inside adduser.jsp

	<%@taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%><%@taglib
	uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>



Add User























-> create success.jsp [WebContent/jsp/success.jsp] -- this page will display after successful user details.
paste the below code inside success.jsp
	<%@taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%><%@taglib
	uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>



Login page


	

success

successfully Added.
-> We need to create java classes.
-> create a package -> com.siva.form
-> com.siva.action

->create LoginForm.java inside com.siva.form package and paste the below code.
package com.siva.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
 * 
 * @author sivaraju
 *
 */
public class LoginForm extends ActionForm {
	/**
	 * 
	 */
	private static final long serialVersionUID = -1743531020254647308L;
	private String userName;
	private String password;

	public ActionErrors validate(ActionMapping mapping,
			HttpServletRequest request) {
		ActionErrors actionErrors = new ActionErrors();
		if (userName == null || userName.trim().equals("")) {
			actionErrors.add("userName", new ActionMessage("error.username"));
		}
		try {
			if (password == null || password.trim().equals("")) {
				actionErrors.add("password",
						new ActionMessage("error.password"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return actionErrors;
	}

	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;
	}
}
->create UserForm.java inside com.siva.form and paste below code

  package com.siva.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
 * 
 * @author sivaraju
 *
 */
public class UserForm extends ActionForm {
	/**
	 * 
	 */
	private static final long serialVersionUID = -2087861874662967982L;
	private String userName;
	private String sex;
	private int age;

	public ActionErrors validate(ActionMapping mapping,
			HttpServletRequest request) {
		ActionErrors actionErrors = new ActionErrors();
		try {
				if (userName == null || userName.trim().equals("")) {
					actionErrors.add("userName", new ActionMessage("error.username"));
				}
				if (sex == null || sex.trim().equals("")) {
					actionErrors.add("sex",new ActionMessage("error.sex"));
				}
				if (age <=0 ) {
					actionErrors.add("age",new ActionMessage("error.age"));
				}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return actionErrors;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	
}
-> create LoginAction.java inside com.siva.action pakage and paste the below code
  package com.siva.action;

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

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.siva.form.LoginForm;

public class LoginAction extends Action {
	private static final String FAILURE = "failure";
	private static final String SUCCESS = "success";

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String target = null;
		LoginForm loginForm = (LoginForm) form;
		if (loginForm.getUserName().equals("admin")
				&& loginForm.getPassword().equals("admin123")) {
			target = SUCCESS;
			request.setAttribute("message", loginForm.getUserName());
		} else {
			target = FAILURE;
		}
		return mapping.findForward(target);
	}
}
-> create AddUserAction.java inside com.siva.action package and paste below code.
package com.siva.action;

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

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.siva.form.UserForm;
/**
 * 
 * @author sivaraju
 *
 */
public class AddUserAction extends Action {
	private static final String SUCCESS = "success";

	/**
	 * 
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UserForm userForm = (UserForm) form;
		System.out.println("username["+userForm.getUserName()+"]");
		System.out.println("Age["+userForm.getAge()+"]");
		System.out.println("Sex["+userForm.getSex()+"]");
		//If this details need to store in db. Then need to get the db details from data source object. Store as per requirement.
		return mapping.findForward(SUCCESS);
	}
	
	
}
->create MessageResource.properties file inside src/resource [src/resource/MessageResource.properties] and paste the below code
label.username = User Name
label.password = Password
label.welcome = Welcome 
error.username =Username is required.
error.password = Password is required.


label.age = Age
label.sex = Sex

label.adduser = Add User


error.age = Age is required field
error.sex=Sex is required field 
-> Add the below jars inside lib folder.(Among below jar's few of the jar's may not be required]
    bcprov-jdk14-121.jar
    commons-digester-2.1.jar
    commons-fileupload-1.1.1.jar
    commons-io-1.2.jar
    commons-lang-2.4.jar
    org-apache-commons-logging.jar
    org.apache.commons.beanutils.jar
    servlet-api.jar
    struts.jar
	
	
-> Right click on the project-> Run As-> Run On Server-> [select the server which ever server you want to run the application]. Tomcat is prefered. -> http://localhost:8080/struts_sample/login.jsp [ after submitting it will redirect to welcome.jsp]- username - admin / password - admin123 -> http://localhost:8080/struts_sample/jsp/adduser.jsp [after submitting it will redirec tto success.jsp]. In this way stuts application will work.

Wednesday, February 27, 2013

Convert word document (.docx) to PDF


This post will describes how to convert word document to PDF using Java.

To convert document to Pdf we will have different type of approaches.
But in this post i am using  docx4j. It is one of the good API for conversion from XSLT to PDF and Word Document to PDF etc..


We can convert from document to Pdf with Simple java program.

Steps to follow.

Step1 :open Eclipse and create new java project- provide name as you like.

Step 2: Create new Java class  which ever you like (ex: ConvertDocToPDF )

Step 3: Paste the below lines of code inside main method of created java class


 try {


long start = System.currentTimeMillis();

// 1) Load DOCX into WordprocessingMLPackage

InputStream is = new FileInputStream(new File("test.docx"));
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(is);
//If your header and body information got over lapped then use the below code
List sections = wordMLPackage.getDocumentModel().getSections();
for (int i = 0; i < sections.size(); i++) {

System.out.println("sections Size" + sections.size());
wordMLPackage.getDocumentModel().getSections().get(i).getPageDimensions().setHeaderExtent(3000);
}

//if you want use any Physical fonts then use the below code.

Mapper fontMapper = new IdentityPlusMapper();

PhysicalFont font = PhysicalFonts.getPhysicalFonts().get("Comic Sans MS");

fontMapper.getFontMappings().put("Algerian", font);

wordMLPackage.setFontMapper(fontMapper);

// 2) Prepare Pdf settings

PdfSettings pdfSettings = new PdfSettings();

// 3) Convert WordprocessingMLPackage to Pdf

org.docx4j.convert.out.pdf.PdfConversion conversion = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(wordMLPackage);

OutputStream out = new FileOutputStream(new File("test.pdf"));
conversion.output(out,pdfSettings);
System.err.println("Time taken to Generate pdf  "+ (System.currentTimeMillis() - start) + "ms");
} catch (Throwable e) {

e.printStackTrace();
}


Step 4: Now you can run the Java program, PDF will be generate for your Document file.

Wednesday, February 13, 2013

spring and xslt example

This post will describe to work with spring and xslt.

1. open Eclipse and create a dynamic webproject - provide name as  spring-xslt(you can give what ever name you want)

2. After that select the target runtime environment(ex: location of tomcat or Jboss or respective server)

3. open web.xml which already created by eclipse for you, modify as mentioned below.

   


<web-app id="WebApp_ID" version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xsi:schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>spring-xslt</display-name>

<welcome-file-list>
   <welcome-file>index.html</welcome-file>
</welcome-file-list>

</div>

<servlet>

<servlet-name>simple</servlet-name>
  <servlet-class>
   org.springframework.web.servlet.DispatcherServlet
  </servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>simple</servlet-name>
  <url-pattern>*.htm</url-pattern>
</servlet-mapping>

</web-app>


4. After that create simple-servlet.xml like mentioned below and put inside WEB-INF

<?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.xsd" >
                 
  <bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver" >
  <property name="order"><value>1</value></property>
  <property name="basename" value="views" />
   </bean>
  <bean id="xsltViewResolver"
  class="org.springframework.web.servlet.view.xslt.XsltViewResolver" >
  <property name="order"><value>2</value></property>
  <property name="viewClass"
  value="org.springframework.web.servlet.view.xslt.XsltView" /> 
  <property name="sourceKey" value="obj" /> 
  <property name="suffix" value=".xsl" />
  <property name="prefix" value="/WEB-INF/xsl/" />
  </bean>
  <bean id="simpleUrlMapping"
  class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" >
  <property name="mappings" >
  <value>
  /login.htm=myxsl
  </value>
  </property>
  </bean>
  <bean id="myxsl"
  class="com.siva.HomePageController" />
  <!--<bean id="myxsl"
  class="com.siva.XsltDisplayController" />
 --></beans>
   
5. Now we have to create xslt file under /WEB-INF/xsl/home.xslt and place the below mentioned code

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" omit-xml-declaration="yes"/>
<xsl:template match="/">
<html>
<head><title>Hello!</title></head>
<body>
<h1>My First Words</h1>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="word">
<xsl:value-of select="."/><br/>
</xsl:template>
</xsl:stylesheet>

6. Now Need to create Contoller class by extending AbstractCommandController.
package com.siva;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class HomePageController extends AbstractController{
protected ModelAndView handleRequestInternal(
HttpServletRequest request,
HttpServletResponse response) throws Exception {

Map map = new HashMap();
List wordList = new ArrayList();

wordList.add("hello");
wordList.add("world");

map.put("wordList", wordList);
return new ModelAndView("home", map);
}
}

7. Need to create xslt view class to iterate the xslt elements.

package com.siva;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import org.springframework.web.servlet.view.xslt.AbstractXsltView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class HomePage extends AbstractXsltView {
protected Source createXsltSource(Map model, String rootName, HttpServletRequest
request, HttpServletResponse response) throws Exception {
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element root = document.createElement(rootName);

List words = (List) model.get("wordList");
for (Iterator it = words.iterator(); it.hasNext();) {
String nextWord = (String) it.next();
Element wordNode = document.createElement("word");
Text textNode = document.createTextNode(nextWord);
wordNode.appendChild(textNode);
root.appendChild(wordNode);
}
return new DOMSource(root);
}
}
8.Create views.properties file under WEB-INF/classes/views.properties

home.(class)=com.siva.HomePage
home.stylesheetLocation=/WEB-INF/xsl/home.xslt
home.root=words

9.finally create one index.html or jsp to submit the form.

<body>
<form action="login.htm" name="login">
Word Id :<input type="text" value="" name="wordId">
Word NAME :<input type="text" value="" name="wordName">
<input type="submit" value="submit">

</form>

</body>

Above mentioned html/jsp is for to submit the form, if we required fileds need to be eneterd by the user then we have to get that values from command object, and then needs to process.

10. Now Everthing is completed. Once you configured and copied the above code into respective places.
We can exceuting the application and can able to see the results.
11. for this project required jars are..

commons-logging-1.1.1.jar
log4j-1.2.15.jar
spring-2.5.6.jar
spring-beans.jar
spring-webmvc.jar
jdom-1.0.jar



Wednesday, February 15, 2012

Axis Webservice implemenation with Eclipse

I get a chance to post small topic related to webservice implementation with eclipse galilio.
This is the easy way to implement webservice.
This example is bottom up approach- from Java - to - WSDL

Step1 : Start Eclipse
Step2 : Open Eclipse-> File -> New Dynamic web project
Step3 : Give project name as you like (ex: test_webservice_server)
Step4 : Select Dynamic web module version as 2.4
Step5 : Select target run time as Apache tomcat version and specify the loaction of
tomcat server installed location.(Ex: c:/tomcat)
Step6 : Click on Finish button.



Before creating webservice we need to write the interface and implementation classes to which methods we need to create webservice.

In this example i created one interface called ArthimeticService, having different methods for doing arthemetic operations.

Then created one Class- ArthimeticServiceImpl which implemnts ,ArthimeticService interface.


Now It's time to create webservice.



Step1 : Right Click on the Created project
Step2 : Select New - Other - Webservice




Step3 : Click On Next button.



Step4 : Select Service Implementation(Which we already created ex:
ArthimeticServiceImpl)
Step5 : Click on Next- Next -(If screen shows the start server button click on that)- Finish


Once we completed above steps our webservice is ready to use by clients.

We need to check whether our webservice is working or not

Open Created wsdl under Webcontent folder
Go to the <wsdlsoap:address location> copy the value and paste in browser address bar with wsdl like the below.

http://localhost:8888/test_webservice_server/services/ArthimeticServiceImpl?wsdl
Please check the port your server is running(most of the cases it will be 8080)
Once this ready then we can create the client from any system.

Now the time for creating webservice client to access the webservice server.


Step1 : create new - project - dynamic web project (ex: test_webservice_client)
Step2 : Select Dynamic web module version as 2.4.
Step3 : Rigth Click on the created project- New - webservice client.



Step4 : Click on Next button.
Step5 : Select the service definition
Step6 : Click on the Browse button




Step7 : Locate the webservice wsdl location
(where wsdl is running : ex http://localhost:8888
/test_webservice_server/services/ArthimeticServiceImpl?wsdl)
Step8: If webservice is running from another system
(instead of localhost mention IP address)

Step9: After Locating WSDL, click on OK- Finish


Step 10: Now we our webservice client also ready.
Step 11: Now we need test this application, wether it is working or not, for that i
am creating simple Test class which will call the Proxy class and
internally it will call the webservice server and will give the response
to us.




Ex:

package com.siva;

import java.rmi.RemoteException;

public class Test {

public static void main(String[] args) {
ArthimeticServiceImplProxy proxy = new ArthimeticServiceImplProxy();
int result = 0;
try {
result = proxy.add(20, 30);
} catch (RemoteException e) {
e.printStackTrace();
}
System.out.println("result is.." + result);
}
}
}


Now you will get result as -- 50

Like this webservices will work.

If you want to call this webservice from JSP and servletes
Then write jsp - with two input paramaters
servlet- will access the two values and return the result after
calling the webservice.
Once everything is completed try this url from your system

http://localhost:8888/test_webservice_client/
then provide input values and click on the Get result then result will display on the screen.

Now you can elaborate what ever ypou like and do modifications for your requirement.

Now you can download the source code from the following link.

DOWNLOAD WEBSERVICE SERVER CODE

DOWNLOAD WEBSERVICE CLIENT CODE












AddToAny

Contact Form

Name

Email *

Message *