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

Sunday, June 10, 2012

Java Decompiler (Jad) : A Smart guide

Jad is a command line Java decompiler written by Pavel Kouznetsov,written for several plateform.
can be downloaded from
1. http://www.kpdus.com/jad.html
2. http://www.varaneckas.com/jad

Installation is very easy,just extract the downloaded zip .
Set the environment variable path for your plateform here I am using windows.
After setting the path variable open the cmd to check the proper installation type jad on
command prompt,if every thing goes fine you will find the fallowing outupt.








To decompile single java class use the command
jad -sjava MyClass.class

To decompile Multiple java class use the command
jad -o -r -sjava -dsrc bin/**/*.class

Jadclipse plugin for Eclipse
Download the Jadclipse for eclipse from http://sourceforge.net/projects/jadclipse/
Copy the extracted jars in the Eclipse plugin folder.
Restart the Eclipse and set the decompliler path as shown









Now your Eclipse is ready to decompile any java class whose source file is not provided with you,just press
F3 on the name of the class and see the magic.

Ant Build File to decompile all the classes inside the jar

<project name="Decompile_jars" default="main" basedir=".">


<taskdef resource="net/sf/antcontrib/antcontrib.properties"/>


<property name="jad" location="c:/program files/jad1.5.8/jad.exe"/>
<property name="unjar.dir" location="loc_unjar"/>

<target name="main">
    <input
        message="Please enter jar file name"
        addproperty="input.file"
        defaultvalue="source"
    />

    <!-- clean temp dir -->
    <delete dir="${unjar.dir}"/>

    <!-- unpack jar file -->    
    <unjar src="${input.file}.jar" dest="${unjar.dir}"/>

    <!-- decompile all class files -->
    <exec executable="cmd.exe">
        <arg line="/c ${jad} -o -r -sjava -d${unjar.dir} ${unjar.dir}/**/*.class"/>
    </exec>     
     
    <!-- create jar file -->
    <jar destfile="${input.file}_decompile.jar">
        <fileset dir="${unjar.dir}"
            excludes="**/*.class"
        />
    </jar>

    <!-- clean temp dir -->
    <delete dir="${unjar.dir}"/>
    
</target>


</project>

Spring Framework and SL4J Integration

The Simple Logging Facade for Java or (SLF4J) serves as a simple facade or abstraction for various logging frameworks, e.g. java.util.logging, log4j and logback, allowing the end user to plug in the desired logging framework at deployment time.

slf4j is actually not a logging library - it's just a facade. You choose a logging framework by yourself. We use slf4j and logback that implements the slf4j API natively.

The SLF4J project has similar goals to commons-logging. It uses quite a different approach, however, which has both benefits and drawbacks. Future versions of commons-logging may adopt some of the concepts of SLF4J.

Spring uses Jakarta Common Library(JCL) and java.util.logging,SL4J has advantages over JCL as it does not suffer
from class loader problem and Memory Leak Problem.SLFJ for logging in java use parametrized version of various log methods they are faster as compared to normal method.


Lests Demonstrate the Integration of SL4J to String framework,in this example we are using SL4J with logback framework

Step 1: Create Java Project.
Step 2: Add Spring Library,SL4J jars and Logback jars in build path as shown





Step 3: Create a class which includes logger as fallows
package com.main;



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloSl4j {
 
 private static final Logger logger = LoggerFactory.getLogger(HelloSl4j.class);
 
 public void sayHello(){
  logger.info("Inside the sayHello Method");
  System.out.println("Say Hello To Spring SL4J Integration");
 }
}




Step 4: create the spring.xml for your application context as shown


 

 



Step 5: create your logger.xml to configure logging as fallows
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
 
 <appender name="STDOUT"
            class="ch.qos.logback.core.ConsoleAppender">
 
    <!-- encoders are assigned by default the type
         ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
    <encoder>
   <pattern>
    %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
   </pattern>
    </encoder>
  </appender>
 
 <root level="INFO">
  <appender-ref ref="STDOUT" />
 </root>
 
</configuration>

Step 6: Create your main class fallows

package com.test;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.main.HelloSl4j;

public class HelloSl4jTest {

 public static void main(String[] args) {
  ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
  HelloSl4j helloSl4j = (HelloSl4j) ctx.getBean("helloSl4j");
  helloSl4j.sayHello();
 }

}


Here is the Logging Console