Friday, March 25, 2011

Insert LONGTEXT in Database using Hibernate

I would like to share my experience while inserting a Big XML file to the Database, The column dataType is LONGTEXT. The XML File sine is about 1.2MB, when i tried to insert in database using the following Hibernate Code i got the Exception as follows.
Code

Transaction transaction =  sessionFactory.getCurrentSession().beginTransaction();
transaction.begin();
sessionFactory.getCurrentSession().persist(xmlData);
transaction.commit();


Where xmlData is as follows

public class XMLData {
 private int id;
 private String xml;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getXml() {
  return xml;
 }

 public void setXml(String xml) {
  this.xml = xml;
 }
}
I got the following Exception.

Exception in thread "main" org.hibernate.exception.GenericJDBCException: could not insert: [org.cgi.model.Server]
 at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
 at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
 at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
 at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:40)
 at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2093)
 at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2573)
 at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:47)
 at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248)
 at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:290)
 at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:180)
 at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:108)
 at org.hibernate.event.def.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:131)
 at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:87)
 at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:38)
 at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:618)
 at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:592)
 at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:596)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:597)
 at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:301)
 at $Proxy0.persist(Unknown Source)
 at org.cgi.dao.manager.ServerDAO.persist(ServerDAO.java:44)
 at org.cgi.dao.manager.test.TestManager.main(TestManager.java:23)
Caused by: com.mysql.jdbc.PacketTooBigException: Packet for query is too large (1094608 > 177152). You can change this value on the server by setting the max_allowed_packet' variable.
 at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3285)
 at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1970)
 at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2150)
 at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2626)
 at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
 at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415)
 at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2333)
 at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2318)
 at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:73)
 at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:33)
 ... 21 more

Solution:
As it is mentioned in the Exception we need to increase the max_allowed_packet variable of MySQL server.
By Default MySQL provides the size of 1 MB. you can read the value by the following Command in MySQL Command Prompt.

show variables like '%max_allowed_packet';
Now you can Set the Value by using the following Command.
set global max_allowed_packet=16777216;

For Reference
The maximum allowed packet size is 1GB.



Monday, March 7, 2011

Create Executable JAR File Using Eclipse

We all are aware of the main part of an Executable JAR file is keeping the MANIFEST.MF in META-INF Folder. Also inside the MANIFEST.MF we need to provide the following Details.

Manifest-Version: 1.0
  Main-Class: com.example.Example
  Class-Path: dependent.jar
Classpath will be required in case you have more dependent jars are there, also we create the Same jar using the JAR Command provided by Java as follows.
jar cvfm myFile.jar myManifestFile *.class
I found that some of the executable jars will through ClassNotFound Exception.
Hence i recommend to follow the Eclipse Jar Export Option.

The test Project i am going through have a Sample Java file to open a Window using the Java Swing.
Once I execute the project the Output is as Follows.
Now lets Create the JAR to run the Application.
Step 1: Right Click on the Project and Select Export.
Step 2: Select teh Export Destination as Runnable JAR File, and click Next.
Step 3: Select the Class with main method, which need to be executed initially and teh Destination Folder where the Jar need to be saved. Here i selected "C:\test.jar"
Step 4: Click Finish, Now your Executable Jar is ready @ C:\test.jar.
Hope you enjoyed the work through.

Wednesday, January 19, 2011

Best Tutorial for SVN Installation on Windows

http://www.codinghorror.com/blog/2008/04/setting-up-subversion-on-windows.html

This is the best Tutorial I found on the Net For Installing SVN on Windows.
The following Link help you to Download SVN svn-1.4.6-setup.

Once you have Installed in Program files it provides the Tutorials, Which resolves most of u r concerns.

How to Configure SVN Server as a Windows Service: Best Article

    Configuring svnserve to Run as a Windows Service


http://svn.spears.at/ : The complete Tutorials.

Thursday, January 6, 2011

Conversion between Array and java.util.List

While dealing with Autogenerated Classes Like JAXB or any other framework we need to convert from Array to List or vice versa..

Object[] --> java.util.List
or
java.util.List --> Object[].

Array to List
    public static void main(String[] args) {
           String[] names= {"Name 1","Name 3","Name 4"};
           List nameList=Arrays.asList(names);
           System.out.println("List Size is :"+nameList.size());
           System.out.println("Names are :"+nameList);
    }
It will give the Output as
   List Size is :3
   Names are :[Name 1, Name 3, Name 4]

We know how to insert the data in some position in List, But the insertion will not be allowed in the List provided by Arrays.asList,

It throws the following Exception when we do
   nameList.add(2,"Name 2");
   or 
   nameList.add("Name 2");

   Exception in thread "main" java.lang.UnsupportedOperationException
           at java.util.AbstractList.add(AbstractList.java:151)
           at java.util.AbstractList.add(AbstractList.java:89)
           at org.work.corejava.collection.ArrayToList.main(ArrayToList.java:12)
Reason: Reference
Arrays.asList Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray.

But as the array supported
    names[1] ="Name 2";
    The same functionality will be supported by List also , as follows.
    nameList.set(1,"Name 2");
List to Array

List to Array can be done using the following Code.
String[] namesArray = nameList.toArray(new String[0]);
      in JDK 1.4 we need to do teh following type casting.
      String[] namesArray = (String[])nameList.toArray(new String[0]);

Monday, January 3, 2011

How you can stop Rumors, a Simple way is here....

Here is something which I thought is an Excellent Stuff to share...



QUOTE

In India around 350 BC in Magadh, Chanakya was widely lauded for his wisdom.

One day an acquaintance ran up to him excitedly and said, "Chanakya ji, do you know what I just heard about Pandit Haridas?"

"Wait a moment," Chanakya replied, "Before you tell me I'd like you to pass a little test. It's called the Triple Filter Test."

'Triple filter?" asked the acquaintance.

"That's right," Chanakya continued, "Before you talk to me about Pandit Haridas, let's take a moment to filter what you're going to say. The first filter is Truth. Have you made absolutely sure that what you are about to tell me is true?"

"No," the man said, "Actually I just heard about it."

"All right," said Chanakya, "So you don't really know if it's true or not. Now let's try the second filter, the filter of Goodness. Is what you are about to tell me about Pandit Haridas something good?"

"No, on the contrary..."

"So," Chanakya continued, "You want to tell me something about Pandit Haridas that may be bad, even though you're not certain it's true?"

The man shrugged, a little embarrassed. Chanakya continued, "You may still pass the test though, because there is a third filter, the filter of Usefulness. Is what you want to tell me about Pandit Haridas going to be useful to me?"

"No, not really."

"Well," concluded Chanakya, "If what you want to tell me is neither True nor Good nor even useful, why tell it to me or anyone at all?"

The man was bewildered and ashamed. This is an example of why Chanakya was a great politician and held in such high esteem.

Tuesday, December 21, 2010

Java Resource Locator. Best practice to open a File

Here I would like to discuss about the Loading of a Resource in a Java Application.For example lets take the Java sample eclipse project Test. Here we have different Package as 1. org.work.corejava, 2. org.work.corejava.file.csvreader also 3.org.work.corejava.xml.parser,
In the above Example if i want to read the InputData.txt file need to be read in the ResouceLocator.java,
Normally we do as follows.

public class ResourceLocator {
 public static void main(String[] args) {
  File fileIn = new File("InputData.TXT");
  FileReader fileReader = null;
  BufferedReader reader = null;
  try {
   fileReader = new FileReader(fileIn);
   reader = new BufferedReader(fileReader);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }finally{
   try{
    reader.close();
   }catch(Exception e){}
  }
 }
}
But It will throw the following Exception 

java.io.FileNotFoundException: InputData.TXT (The system cannot find the file specified)
 at java.io.FileInputStream.open(Native Method)
 at java.io.FileInputStream.(Unknown Source)
 at java.io.FileReader.(Unknown Source)
 at org.work.corejava.ResourceLocator.main(ResourceLocator.java:25)
The reason behind this Exception is the Application is searching the InputData.TXT in the base class path. Basically inside the SRC Folder. But the File is in the src/org/work/corejava folder. To avoid the above exception we can simply copy the InputData.TXT to the src folder and the issue resolved. otherwise provide the Entire path as follows.
File fileIn = new File("D:\\Development\\workspace\\Test\\org\\work\\corejava\\InputData.TXT");

The best way to do this is by using the Class.getResource Method as follows.
URL url=ResourceLocator.class.getResource("InputData.TXT");
fileReader = new FileReader(url.getFile());
Here we will keep the File and the Java FIle in the same package.
The complete program is as follows.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;

/**
 * To find the Resource by using the Java Resource Locator.
 * @author askeralim
 *
 */
public class ResourceLocator {
 public static void main(String[] args) throws IOException {
  FileReader fileReader = null;
  BufferedReader reader = null;
  try {
   URL url=ResourceLocator.class.getResource("InputData.TXT");
   fileReader = new FileReader(url.getFile());
   reader = new BufferedReader(fileReader);
   String data =reader.readLine();
   System.out.println(data);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }finally{
   try{
    reader.close();
   }catch(Exception e){}
  }
 }
}