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








Wednesday, July 4, 2012

AJAX : GET/POST FORM Submit with Drop Down Menu


Lets start from view:
Drop Down Menu In your JSP/HTML

<select id = "Language" onchange="javascript:AjaxEx.sendAjaxRequest();">

<option value ='en'>EN</option>

<option value ='fr'>FR</option>

</select> 


AJAX code that reqired to be include in the view
(function() {
 AjaxEx = {
  init: function(url, elId) {
   if (!url || !elId) {
    alert("Invalid input!");
    return;
   }
   this.url = url;
   var el = document.getElementById(elId);
   if (!el) {
    alert("Container Element, to place Ajax response doesn't exists!");
    return;
   }
   this.el = el;
   this.sampleHtml = "

This will be replaced with AJAX response!

"; // create xml http request object for AJAX requests this.xmlHttp = this.initXmlHttp(); }, // End of init() initXmlHttp : function () { if (window.XMLHttpRequest) // Firefox, Opera, IE7, etc. return new XMLHttpRequest(); if (window.ActiveXObject) // IE6, IE5 return new ActiveXObject("Microsoft.XMLHTTP"); }, // End of initXmlHttp() resetContent : function () { this.el.innerHTML = this.sampleHtml; }, // End of resetContent() sendAjaxRequest : function () { // initialize XML Http object if not available if (!this.xmlHttp) this.xmlHttp = this.initXmlHttp(); if (this.xmlHttp) { var ajaxObj = this; this.xmlHttp.onreadystatechange = function() { if (ajaxObj.xmlHttp.readyState==4 && ajaxObj.xmlHttp.status==200) { // 4 = "loaded", 200 = "OK" ajaxObj.el.innerHTML = ajaxObj.xmlHttp.responseText; } }; var selBox = document.getElementById("Language"); // prepare parameters var langSalect = selBox.options[selBox.selectedIndex].value; if (langSalect == "") { alert("Please select language!"); return; } var params = "langSalect=" + langSalect; // for multiple parameters separate them by '&' as given below // var params = "empCode=E1001&dept=TestDept" this.makePOSTRequest(params); // this.makeGETRequest(params); } else alert("Your browser does not support AJAX."); }, // End of sendAjaxRequest() makePOSTRequest : function (params) { this.xmlHttp.open("POST", this.url, true); //Send the proper header information along with the request this.xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); this.xmlHttp.setRequestHeader("Content-length", params.length); this.xmlHttp.setRequestHeader("Connection", "close"); this.xmlHttp.send(params); }, // End of makePOSTRequest() makeGETRequest : function (params) { this.xmlHttp.open("GET", this.url + "?" + params, true); this.xmlHttp.send(null); } // End of makeGETRequest() } // End of AjaxEx })();

Create Your AJAX content object as fallows for submission of the perticular url and the tag id whose content need to be set Asynchronously

<script type="text/javascript">

<var url = "...../DBServlet">

<var ajaxObj = document.getElementById('.....')>

<AjaxEx.init(url, "ajaxObj">

</script>


Sunday, July 1, 2012

Apache Lucene : A Smart Guide to Index and Search Text

Apache Lucene(TM) is a high-performance, full-featured text search engine library written entirely in Java. It is a technology suitable for nearly any application that requires full-text search, especially cross-platform.
For adding customized full text search,Lucene is powerful efficient search algo
lets begin to explore it,The Example below is very self explanatory

Step 1: Create java project in eclipse add lucene core jar into the build path of
the project.

Step 2: Create a class LuceneIndexnSearch as shown below
package com.test;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;

@SuppressWarnings("deprecation")
public class LuceneIndexnSearch {

 public static final String SOURCE_FILE = "sourceFileToIndex";
 public static final String INDEX_DIR = "indexDir";

 public static final String FIELD_PATH = "path";
 public static final String FIELD_CONTENTS = "contents";

 

 public  void createIndex() throws CorruptIndexException, LockObtainFailedException, IOException {
  Analyzer analyzer = new StandardAnalyzer();
  boolean recreateIndexIfExists = true;
  IndexWriter indexWriter = new IndexWriter(INDEX_DIR, analyzer, recreateIndexIfExists);
  File dir = new File(SOURCE_FILE);
  File[] files = dir.listFiles();
  for (File file : files) {
   Document document = new Document();

   String path = file.getCanonicalPath();
   document.add(new Field(FIELD_PATH, path, Field.Store.YES, Field.Index.UN_TOKENIZED));

   Reader reader = new FileReader(file);
   document.add(new Field(FIELD_CONTENTS, reader));

   indexWriter.addDocument(document);
  }
  indexWriter.optimize();
  indexWriter.close();
 }

 public static void searchIndex(String searchString) throws IOException, ParseException {
  System.out.println("Searching for '" + searchString + "'");
  Directory directory = FSDirectory.getDirectory(INDEX_DIR);
  IndexReader indexReader = IndexReader.open(directory);
  IndexSearcher indexSearcher = new IndexSearcher(indexReader);

  Analyzer analyzer = new StandardAnalyzer();
  QueryParser queryParser = new QueryParser(FIELD_CONTENTS, analyzer);
  Query query = queryParser.parse(searchString);
  TopDocCollector collector = new TopDocCollector(5); 

  indexSearcher.search(query, collector); 

  int numTotalHits = collector.getTotalHits(); 

  collector = new TopDocCollector(numTotalHits); 

  indexSearcher.search(query, collector); 

  ScoreDoc[] hits = collector.topDocs().scoreDocs; 
  
  for(ScoreDoc sd : hits){
   int docId = sd.doc;
   Document document = indexSearcher.doc(docId);
   System.out.println("Number of matches(Hits) in the document "+document.get(FIELD_PATH)+" of the given string "+searchString+" is "+sd.doc);
  }
 }

}
Step 3: create to folder to contain files to index and to contain the indexed document:
In the source folder I have copied the to documents(text files) vehicleOwnedByABC.txt the content of the file is as:

Maruti
mahindra
vento
honda city
honda accord
hyundai



The other file name is vehicleOwnedByDEF.txt with content

swaraj
renault
polo
nissan
maruti
hyundai


Step 4: Create your main class to test the searching and indexing as fallows
package com.test;

public class Main {
 public static void main(String[] args) {
  LuceneIndexnSearch lins = new LuceneIndexnSearch();
  try{
  lins.createIndex();
  lins.searchIndex("Hyundai");
  lins.searchIndex("Maruti");
  lins.searchIndex("Mahindra");
  lins.searchIndex("Honda city");
  lins.searchIndex("Honda accord");
  }catch(Exception e){
   e.printStackTrace();
  }
 }

}

Step 5: Here is the output at console:
Searching for 'Hyundai'
Number of matches(Hits) in the document F:\SpringExamples\LuceneExample\sourceFileToIndex\vehicleOwnedByDEF.txt of the given string Hyundai is 1
Number of matches(Hits) in the document F:\SpringExamples\LuceneExample\sourceFileToIndex\vehicleOwnedByABC.txt of the given string Hyundai is 0
Searching for 'Maruti'
Number of matches(Hits) in the document F:\SpringExamples\LuceneExample\sourceFileToIndex\vehicleOwnedByDEF.txt of the given string Maruti is 1
Number of matches(Hits) in the document F:\SpringExamples\LuceneExample\sourceFileToIndex\vehicleOwnedByABC.txt of the given string Maruti is 0
Searching for 'Mahindra'
Number of matches(Hits) in the document F:\SpringExamples\LuceneExample\sourceFileToIndex\vehicleOwnedByABC.txt of the given string Mahindra is 0
Searching for 'Honda city'
Number of matches(Hits) in the document F:\SpringExamples\LuceneExample\sourceFileToIndex\vehicleOwnedByABC.txt of the given string Honda city is 0
Searching for 'Honda accord'
Number of matches(Hits) in the document F:\SpringExamples\LuceneExample\sourceFileToIndex\vehicleOwnedByABC.txt of the given string Honda accord is 0