Posts

Showing posts from June, 2012

The Externalizable Interface

Before you start exploring Externalization in Java, I would recommend you to gather some knowledge of Serialization in Java because Externalizable is an alternative to Serializable interface.


Externalizable interface allows you to customize how serialization is done. By implementing Externalizable you are controlling what gets serialized and what does not get serialized. Externalizable interface  extends Serializable interface and defines two methods to be overridden by the implementing class.  public void readExternal(ObjectInput in) throws IOException, ClassNotFoundExceptionpublic void writeExternal(ObjectOutput out) throws IOExceptionJava class implementing Externalizable interface

package learn.java.serialization;


import java.io.Externalizable;
importjava.io.IOException;
importjava.io.ObjectInput;
importjava.io.ObjectOutput;
importjava.util.Date;


public class ExternalizableObject implements Externalizable{
   private String name;
   private Date dob;
   private int age;

public String getName()…

How to scale image using Java

In this post we will see how can we scale an image to a desired dimension. 


In the following code snippet the scaleImage method is responsible for scaling the source image to the given height & width. Instead of overwriting the original file the code creates a new file for the scaled image version.


public static String  scaleImage(String imgSrc, int width, int height, String dest){
try{
File f = new File(imgSrc);

//Reads the Image from the given URL
BufferedImage img = ImageIO.read(f);

//Scales the BufferedImage to the desired dimensions
   Image scaledImg = img.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);

//'coz the Image object cannot be written to disk directly 
   //We have to recreate a new BufferedImage instance from the scaled Image instance
   BufferedImage biScaledImg = toBufferedImage(scaledImg, BufferedImage.TYPE_INT_RGB);

//Writes the file on to the disk at the given destination
   ImageIO.write(biScaledImg, "jpeg", new File(dest));
}
catch(IOException …

How to delete Solr Index

To delete all documents from my Solr index, we have to issue an update request with the  stream.body parameter set to <delete><query>*:*</query></delete>, as with the following URL: 


http://<host>:<port>/solr/update?stream.body=<delete><query>*:*</query></delete>&commit=true


Just replace the placeholder with the correct details. If executed successfully the it will return a response with status = 0 and query execution time.
<response>

<lstname="responseHeader"> <intname="status">0</int> <intname="QTime">3693</int> </lst> </response>

If you want to remove indexes of a particular field then specify the field name in the delete query
<delete><query>desc:*</query></delete>


You can also delete a wrongly indexed value from a particular field, just by adding the value in the delete query
<delete><query>desc:wrold</query>&l…

Using Solr Spellchecker from Java

Continuing from my prevoius post Implementing Spellchecker in Solr, we'll now see how to use SorlJ API to fetch spellcheck suggestions through a Java program.


public static Map<String, List<String>> getSuggestions(String queryStr){
if (queryStr != null &&  !queryStr.isEmpty()) {

try {

SolrServer server = new HttpSolrServer("http://localhost:8983/solr");


   ModifiableSolrParams params = new ModifiableSolrParams();
   params.set("qt", "/spell");
   params.set("q", queryStr);
   params.set("spellcheck", "true");
   params.set("spellcheck.collate", "true");


   QueryResponse response = server.query(params);
   System.out.println("response = " + response);

   if(response != null){
SpellCheckResponse scr = response.getSpellCheckResponse();
if(scr != null){
List<Suggestion> suggLst = scr.getSuggestions();
for(Suggestion sugg : suggLst){
System.out.println("Suggestion fo…

Implementing Spellchecker in Solr

A common need in search applications is suggesting correct word/ phrase for a misspelled word / phrase. These suggestions may come from a dictionary that is based upon some field or upon any other arbitrary dictionary. 

Implementing a spell-check suggester in Apace Solr is a piece of cake. All you need is to follow the given steps and you are done.
Step 1: Open <SOLR_HOME>/example/solr/conf/solrconfig.xml and search for  <lst name="spellchecker"> under this tag make changes to  <str name="field">name</str>  in place of namedefine your field which will be referred for spell checking
Now we have to update the spell requestHandler settings, to do so search for  <requestHandler name="/spell" class="solr.SearchHandler" startup="lazy"> and under this tag make changes to <str name="df">text</str>  in place of textdefine your field which will be referred for spell checking, also increase the <str name…

Importing / Indexing MySQL data into Solr

Apache Solr is a fast, full featured, open-source Java search server. It enables you to easily create search engines which index, search & analyze data from websites, databases or files.

Before we proceed further I presume that you have already configured Solr server without data or refer to Solr in 5 minutes tutorial to configure your Solr server first.

Configure your Solr server
Step 1:
To index your data firstly you need to define schema by editing file called schema.xml present at <SOLR_HOME>/example/solr/conf/ Schema.xml in solr serves the similar purpose that table does in mysql
In schema.xml file you have to define the
Fields with there field typeField which should be used as unique keyWhich fields are required, indexedDefault search field (deprecated in new versions)Default search operator (AND | OR deprecated in new versions)**indexed fields are fields which undergo an analysis phase, and are added to the index.
Search for <fields> tag and define your fields und…

serialVerionUID in Java Object Serialization

What is serialVersionUID?The purpose of the "serialVersionUID"  is to keep track of different versions of a class in order to perform valid deserialization of objects. This SUID should be unique to a certain version of a class, and should be changed when there are any details change to the class, such as a new field, which would affect the structure of the serialized object.


The serialization process associates a serialVersionUID(default if not explicitly defined) with each serialized instance of a class. This serialVersionUID is validated at the time of deserialization from the loaded class serialVersionUID, and in case of a mismatch InvalidClassException is thrown.


Default serialVersionUIDIf a serializable class does not define serialVersionUID explicitly then the serialization process automatically calculates a default serialVersionUID (by invoking computeDefaultSUID() method of java.io.ObjectStreamClass) value for that class viz usually the hash value of class details…

Serialization in Java

Serialization is the process of converting an object's state into byte sequence (to persist it on to a file), and to rebuild (deserialize) those bytes into an object.
To make an object serializable, the object should implement java.io.Serializableinterface. Lets take an example to understand Serialization in Java.
Firstly lets define a serializable object
###############################################################
package learn.java.serialization;
import java.io.Serializable;
public class SerializableObject implements Serializable{
private String message; public SerializableObject(){ }
public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; } }
###############################################################
As you must have noticed the only special thing that we have done  to the class is implement Serializable. The java.io.Serializable is a markup or marker interface, it allows the serialization mechanism to check object's ability to…