Wednesday, August 22, 2012

JAXB Tutorial with Eclipse

Java Architecture for XML Binding:

















Create JAXB Project in Eclipse as Shown in the image





















Copy some .xsd file to your Jaxb Project as shown





















Create Java Classes from the Scema look into the figures






















Click on Finish After Providing the package name




















The Fallowing Classes are Populated after finish
















Create your main Class As Fallows



















Now Run Your Main Class as Java Project


After running the project you will find the xml named as status.xml in the project








Tuesday, August 14, 2012

AJAX JQuery Tutorial

Step 1: Configure your dynamic web project,start with 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>CMIS_NEW</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>LanguageServlet</servlet-name>
<servlet-class>com.cims.LanguageServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>LanguageServlet</servlet-name>
<url-pattern>/LanguageServlet</url-pattern>
</servlet-mapping>


</web-app>

Step 2: create your index.jsp which have jquery script as shown

<%@ 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>AJAX JQUERY EXAMPLE</title>
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#getLanguage").click(function(){
$countryName = document.getElementById("countryName").value;
$.post("LanguageServlet", {countryName:$countryName}, function(languageReturned) {
alert(languageReturned);
$("#language").html(languageReturned);
});
});
});
</script>
<form method="post">
Enter Country :
<input id="countryName" name="countryName" type="text" />
<input id="getLanguage" name="getLanguage" type="button" value="Get Language" />
</form>
<div id="language" class="outputTextArea"></div>
</body>

Step 3: Create your LanguageServlet which got hit when you post the request.

package com.cims;

import java.io.IOException;
import java.io.PrintWriter;

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

public class LanguageServlet extends HttpServlet {

public void doPost(HttpServletRequest req,HttpServletResponse res) 
throws ServletException,IOException{

PrintWriter out = res.getWriter();
res.setContentType("text/html");
String countryName = req.getParameter("countryName");
String languageReturned = "";
if(countryName.equals("india")){
languageReturned = "Hindi";
}else if(countryName.equalsIgnoreCase("USA")){
languageReturned = "English";
}else if(countryName.equalsIgnoreCase("france")){
languageReturned = "French"; 
}else
languageReturned = "Unknown";
out.println(languageReturned);
out.flush();
out.close();



}

}


Step 4: Look at response on your JSP.



Monday, August 13, 2012

Log4j Tutorial : How to send log messages to different log file (Module wise)

Create your Dynamic Web project as fallows:




web.xml
package com.cims;

import java.io.IOException;
import java.io.PrintWriter;

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

import org.apache.log4j.Logger;


public class TestLog4jServlet extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 1L;
static Logger logger = Logger.getLogger(TestLog4jServlet.class);

public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
logger.info("Starting the "+this.getClass().getName()+" doGet() Method");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("Log4j Debugger Example");
logger.info("Exiting the "+this.getClass().getName()+" doGet() Method");
logger.debug("Debug Logs");
logger.warn("Warn Messages");
logger.error("Error Logs");
logger.fatal("Fatal logs");

}

}


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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Log4j MultiAppender Example</title>
</head>
<body>
<a href="test"> Test MultiAppender</a>
</body>
</html>


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>

<appender name="Test2Servlet" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="D:/Test2Servlet.log" />
<param name="Append" value="false" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n" />
</layout>
</appender>

<appender name="TestLog4jServlet" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="D:/TestLog4jServlet.log" />
<param name="Append" value="false" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n" />
</layout>
</appender>

<category name="com.test">
<priority value="info" />
<appender-ref ref="Test2Servlet" />
</category>

<category name="com.cims">
<priority value="ERROR" />
<appender-ref ref="TestLog4jServlet" />
</category>

<root>
<level value="DEBUG" />

</root>

</log4j:configuration>


Log4JServlet
package com.cims;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.xml.DOMConfigurator;

public class Log4JServlet extends HttpServlet {

public void init() throws ServletException{

String log4jfile = getInitParameter("log4j-init-file");
if(log4jfile != null){
String propfile = getServletContext().getRealPath(log4jfile);
//PropertyConfigurator.configure(propfile);
DOMConfigurator.configure(propfile);
}

}

}


com.test.Test2Servlet
package com.test;

import java.io.IOException;
import java.io.PrintWriter;

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

import org.apache.log4j.Logger;

public class Test2Servlet extends HttpServlet{

/**
* 
*/
private static final long serialVersionUID = 1L;
static Logger logger = Logger.getLogger(Test2Servlet.class);


public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{

res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("inside the "+this.getClass().getName());
logger.info("Starting "+this.getClass().getName()+".doGet() method");
logger.debug("Debug logs");
logger.warn("warn log");
logger.error("Error logs");
logger.fatal("fatal logs");
logger.info("Exiting "+this.getClass().getName()+".doGet() method");
}


}


com.cims.TestLog4jServlet
package com.cims;

import java.io.IOException;
import java.io.PrintWriter;

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

import org.apache.log4j.Logger;


public class TestLog4jServlet extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 1L;
static Logger logger = Logger.getLogger(TestLog4jServlet.class);

public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
logger.info("Starting the "+this.getClass().getName()+" doGet() Method");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("Log4j Debugger Example");
logger.info("Exiting the "+this.getClass().getName()+" doGet() Method");
logger.debug("Debug Logs");
logger.warn("Warn Messages");
logger.error("Error Logs");
logger.fatal("Fatal logs");
RequestDispatcher rd = getServletContext().getRequestDispatcher("/test2");
rd.forward(req, res);

}

}

Output









Log4j Tutorial : How to Create Multiple Appenders

Step 1: Create a dynamic web application in eclipse
Step 2: Create web.xml file as fallows:

<?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>CMIS_NEW</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>TestLog4j</servlet-name>
<servlet-class>com.cims.TestLog4jServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>TestLog4j</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>



</web-app>

Step 3 :Create Servlet to initialize the Log4j properties through xml file

package com.cims;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.xml.DOMConfigurator;

public class Log4JServlet extends HttpServlet {

public void init() throws ServletException{

String log4jfile = getInitParameter("log4j-init-file");
if(log4jfile != null){
String propfile = getServletContext().getRealPath(log4jfile);
//PropertyConfigurator.configure(propfile);
DOMConfigurator.configure(propfile);
}

}

}

Step 4: Create your Log4j configuratioin xml and place into the classpath

package com.cims;<br/> <br/>import javax.servlet.ServletException;<br/>import javax.servlet.http.HttpServlet;<br/> <br/>import org.apache.log4j.PropertyConfigurator;<br/>import org.apache.log4j.xml.DOMConfigurator;<br/> <br/>public class Log4JServlet extends HttpServlet {<br/>  <br/> public void init() throws ServletException{<br/>   <br/>  String log4jfile = getInitParameter(&quot;log4j-init-file&quot;);<br/>  if(log4jfile != null){<br/>   String propfile = getServletContext().getRealPath(log4jfile);<br/>   //PropertyConfigurator.configure(propfile);<br/>   DOMConfigurator.configure(propfile);<br/>  }<br/>   <br/> }<br/> <br/>}

Step 5:Now create a servlet to test the configuration

package com.cims;

import java.io.IOException;
import java.io.PrintWriter;

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

import org.apache.log4j.Logger;


public class TestLog4jServlet extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 1L;
static Logger logger = Logger.getLogger(TestLog4jServlet.class);

public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
logger.info("Starting the "+this.getClass().getName()+" doGet() Method");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("Log4j Debugger Example");
logger.info("Exiting the "+this.getClass().getName()+" doGet() Method");
logger.debug("Debug Logs");
logger.warn("Warn Messages");
logger.error("Error Logs");
logger.fatal("Fatal logs");

}

}

Here is the output at console




Sunday, August 12, 2012

Log4j Tutorial : Configure Log4j In a web application

Step 1: create your web application in eclipse
Step 2: Create web.xml as fallows

<?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>CMIS_NEW</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
   
   
  <context-param>
  <param-name>log4jConfigLocation</param-name>
  <param-value>/WEB-INF/log4j.properties</param-value>
 </context-param>
  
  <servlet>
  <servlet-name>TestLog4j</servlet-name>
  <servlet-class>com.cims.TestLog4jServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
   <servlet-name>TestLog4j</servlet-name>
   <url-pattern>/test</url-pattern>
  </servlet-mapping>
  
  
  
</web-app>

Step 3: Create servlet which initialized your log4j configuration
package com.cims;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.PropertyConfigurator;

public class Log4JServlet extends HttpServlet {
 
 public void init() throws ServletException{
  
  String log4jfile = getInitParameter("log4j-init-file");
  if(log4jfile != null){
   String propfile = getServletContext().getRealPath(log4jfile);
   PropertyConfigurator.configure(propfile);
  }
  
 }

}

Step 4: Create log4j.properties and place into the classpath
log4j.rootLogger=INFO, CMISAppender
log4j.appender.CMISAppender=org.apache.log4j.ConsoleAppender
log4j.appender.CMISAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.CMISAppender.layout.ConversionPattern=%-4r [%t] %-5p %d %c %x - %m%n

Step 5: Create your tester servlet as fallows
package com.cims;

import java.io.IOException;
import java.io.PrintWriter;

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

import org.apache.log4j.Logger;


public class TestLog4jServlet extends HttpServlet {
 
 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 static Logger logger = Logger.getLogger(TestLog4jServlet.class);
 
 public void doGet(HttpServletRequest req,HttpServletResponse res) 
   throws ServletException,IOException{
  logger.info("Starting the "+this.getClass().getName()+" doGet() Method");
  res.setContentType("text/html");
  PrintWriter out = res.getWriter();
  out.println("Log4j Debugger Example");
  logger.info("Exiting the "+this.getClass().getName()+" doGet() Method");
  
 }

}





Tuesday, August 7, 2012

Quartz Tutorial : Configure Quartz in web Application

This Tutorial will guide you how to configure Quartz Scheduler in J2EE web Application.
To introduce quartz into the web application we need to specify a context listener into the web application which notify the event of context start up as well as shut down to start and stop the quartz scheduler.
Look in the fallowing example to plug qartz in to the web appliction

Step 1: Create the dynamic web application into the eclipse
Step 2: add the fallowing entries inside 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>TestQuartzApi</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<listener>
<listener-class>com.test.QuartzInitializerListener</listener-class>
</listener>
</web-app>

Step 3: Create your Job which implements Quartz's Job as fallows

package com.test;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class MyJob implements Job {

@Override
public void execute(JobExecutionContext ctx) throws JobExecutionException {
System.out.println("Quartz is executing my Job");
}

}

Step4 : Create your QuartzInitializerListener class which implements ServletContextListner and override the contextInitialized method,in the contextInitialized method we are providing the configuration regarding Scheduler and Trigger as fallows

package com.test;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

public class QuartzInitializerListener implements ServletContextListener {

public void contextDestroyed(ServletContextEvent arg0){}



public void contextInitialized(ServletContextEvent arg0)
{


System.out.println("Starting The Application");
try{
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();

long ctime = System.currentTimeMillis();

JobDetail job = new JobDetail();
job.setName("MyJobName");
job.setJobClass(MyJob.class);

CronTrigger crt = new CronTrigger();
crt.setName("MyTriggerName");
crt.setCronExpression("0/30 * * * * ?");

scheduler.start();
scheduler.scheduleJob(job, crt);

}catch (Exception e) {
System.out.println(e);
}

}
}

Step 5: Make sure to include quartz api related jar in the build path and run your application,here you goes




Monday, August 6, 2012

Quartz Tutorial

Quartz is an open source job scheduling framework that provides simple but powerful mechanisms for job scheduling in Java applications. Quartz allows developers to schedule jobs by time interval or by time of day. It implements many-to-many relationships for jobs and triggers and can associate multiple jobs with different triggers.

Here I am providing a simple guide to Quartz API with the help of fallowing example

Step 1: Create a Simple java Application in eclipse.

Step 2: Add the fallowing jars to the classpath
quartz-1.6.0.jar
commons-collections-3.2.jar
commons-logging-1.1.1.jar
jta-1.1.jar


Step 3:Create your job which implements Job interface
package com.test;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class MyJob implements Job {

@Override
public void execute(JobExecutionContext ctx) throws JobExecutionException {
System.out.println("Quartz is executing my Job");
}

}

Step 4: Create Your Schedular and test application
package com.test;

import java.text.ParseException;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;

public class JobSchedular {
public static void main(String[] args) throws ParseException, SchedulerException {
JobDetail job = new JobDetail();
job.setName("MyJobName");
job.setJobClass(MyJob.class);

CronTrigger crt = new CronTrigger();
crt.setName("MyTriggerName");
crt.setCronExpression("0/30 * * * * ");

Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, crt);
}

}

Step 5: Here is the outcome