Thursday, October 27, 2011

org.apache.jasper.JasperException: Unable to compile class for JSP

I got this error while working with a complex file  in JBOSS.

If you get below mentioned error, As the compiler suggesting there is some brace mismatch. Just go around and check again. Make sure you close all braces correctly.

09:09:25,282 ERROR [ContainerBase] Servlet.service() for servlet jsp threw exception
org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: 822 in the generated java file
Syntax error, insert "else Statement" to complete IfStatement

An error occurred at line: 822 in the generated java file
Syntax error, insert "}" to complete Block

An error occurred at line: 832 in the generated java file
Syntax error on token "}", delete this token

An error occurred at line: 833 in the generated java file
Syntax error, insert "}" to complete ClassBody

Monday, October 24, 2011

How to install Subversion (SVN) in Eclipse or My Eclipse

Apache Subversion (SVN) is a software versioning and a revision control system distributed under a free license. SVN is also known as Subclipse.

Subclipse 1.8.1 and 1.6.18 and 1.4.8 are now available for Eclipse 3.2+.

Here are the simple steps to install Subclipse (SVN) plugins in your IDE Eclipse or My Eclipse.

Step 1. Go to Site (http://subclipse.tigris.org) and download file latest version of Zipped file (site-1.8.1.zip).

Download Page.

Download URL.

Step 2. Unzip the file (site-1.8.1.zip) in dropins folder

Unzip the downloaded file in below mentioned dropins folder. dropins is where your Eclipse is installed.
Extract files to site-1.8.1

For Example.
C:\Program Files\Genuitec\MyEclipse 7.5\dropins



Step 3. Restart Eclipse and check it.

Restart your IDE (Eclipse or My Eclipse) and check whether it is installed successfully.

How to check whether Subclipse (SVN) is installed successfully or not?

Go to Window -> Preferences



If you can see SVN under Team node then it is installed successfully. If not then try again.

class file has wrong version 49.0, should be 48.0

If you get below mentioned error.

class file has wrong version 49.0, should be 48.0

There could be Java version conflict. Check for correct version of Java for Compiling and Running the .class / .jar file.
You may have complied .java file in higher version of Java and Running it on lower version of Java.

Check for Java version

Command: java -version

Just make sure that you compile and run in same version.

Thursday, October 20, 2011

RA layer request failed

If you get below mentioned SVN error in Eclipse or My Eclipse, possibly there could be two reasons.

RA layer request failed
svn: Server sent unexpected return value (403 Forbidden) in response to OPTIONS request for 'https://svn.example.com/test'

1. Check whether you have access to the SVN repository.

Hit the SVN url https://svn.example.com/test in your browser and check whether you can access it, if required put user name and password. if you do not have access then ask SVN admin to grant access to you.

2. If you have access and still getting above error.

Go to below mentioned folder and Clean up the folder. Take files backup or simply delete those files.

C:\Documents and Settings\Your User Name\Application Data\Subversion\auth

Now try to access your SVN in Eclipse, Hope you may able to access it, if not let us discuss it.

Linux : chmod: WARNING: chmod: could not getcwd OR chown: getcwd: Permission denied

When I tried to do chmod for a bulk of files at once using below mentioned chmod command, I used to get below error.
Below command is used for changing permission for a bulk of files recursively in a single shot.

Command : chmod -R 777 *

Error :
chmod: WARNING: chmod: could not getcwd /home/test

Also when i tried to do chown for a bulk of files at once using below mentioned chown command, I used to get error as shown below.
Below command is used to change owner name for a bulk of files recursively in a single shot.

Command : chown -R UserName:GroupName *

Error :
chown: getcwd: Permission denied

However when I do chmod or chown for one particular folder, it runs without error.

Command : chmod -R 777 FolderName
Command : chown -R UserName:GroupName FolderName

Reason :
On some Unix variants, getcwd() will return FALSE if any one of the parent directories does not have the readable or search mode set, even if the current directory does.

Solution :
Type "groups" command and see which other groups you can access.
Go to the parent folder and change the group name.
And then try the above commands, It worked for me and hope it may even work for you.

If not lets discuss it here.

Tuesday, October 18, 2011

Simple HTML parser in Java

Some time we may require to parse a HTML file. In this example i used jsoup: Java HTML Parser because its simple to configure and easy to understand with lots of feature which can be customize according to our requirement. http://jsoup.org/
We used the jsoup jar (version 1.6.1), To run this example download jsoup-1.6.1.jar and set it in your classpath.

We can either hit a HTTP URL or read from a HTML file according to our requirement.

The parse(File in, String charsetName) method loads and parses a HTML file.
File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input,"UTF-8");

The connect(String url) method creates a new Connection, and get() fetches and parses a HTML file.
Document doc = Jsoup.connect("http://example.com/").get();

Also you can parse a document from a String
String html = "<html><head><title>First parse</title></head>"
  + "<body><p>Parsed HTML into a doc.</p></body></html>";
Document doc = Jsoup.parse(html);


Lets look at API for jsoup. http://jsoup.org/apidocs/

Lets see a sample code, you can customize it according to your requirement. Just set jsoup-1.6.1.jar in your classpath, provide a HTMl file to read and run the program.

/* SimpleHTMLParser.java */

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class SimpleHTMLParser {

    public static void main(String[] args) throws IOException {
       
       
        //File htmlFile = new File("C:/temp/VariableDeclarations.html");       
        //Document doc = Jsoup.parse(htmlFile, "UTF-8");
       
        Document doc = Jsoup.connect("http://localhost:8080/temp/VariableDeclarations.html").get();
       
        Element headElement = doc.head();//Accessor to the document's head element.
        Elements allHeadElements =  headElement.children();//Get this element's child elements.
       
        //For formatting output
        String indent = "";
       
        parseElements(allHeadElements,indent);
       
        Element bodyElement = doc.body();//Accessor to the document's body element.
        Elements allBodyElements =  bodyElement.children();//Get this element's child elements.
       
        parseElements(allBodyElements,indent);

    }
   
    public static void parseElements(Elements allElements,String indent) {
       
        //For formatting output
        indent += " ";
       
        if(!allElements.isEmpty()) {
           
                for(int i=0;i<allElements.size();i++) {
               
                Element eachChildrenElement = allElements.get(i);
               
                //If the tag has text values
                if(eachChildrenElement.hasText()) {
                   
                    Elements allChlidElements = eachChildrenElement.children();
                   
                    //If Elements has child nodes, then call parseElements() recursively
                    if(allChlidElements.size() > 0) {
                        System.out.println(indent+eachChildrenElement.tagName());
                        parseElements(allChlidElements,indent);
                    }
                    //Else this is a leaf node, print the values
                    else {
                        System.out.println(indent+eachChildrenElement.tagName()+" : "+eachChildrenElement.text());
                    }
                }
                //Else check for attributes
                else {
                    Attributes attrs = eachChildrenElement.attributes();
                   
                    Iterator<Attribute> itAttrs = attrs.iterator();
                   
                    System.out.print(indent+eachChildrenElement.tagName()+" : Attributes :: ");
                   
                    while(itAttrs.hasNext()) {
                        Attribute attr = itAttrs.next();
                        System.out.print(attr.getKey()+" - "+attr.getValue()+", ");
                    }
                    //For formatting output
                    System.out.println("");
                }
            }//for
           
        }
    }//parseElements

}

Thursday, October 13, 2011

Exception in thread "main" java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

if you get below mentioned exceptions while connecting My SQL using JDBC, Just make sure that password and other login credentials are provided correctly.

Exception in thread "main" java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1056)
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3376)
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3308)
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:894)
        at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3808)
        at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1256)
        at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2032)
        at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:729)
        at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:46)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
        at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
        at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:283)
        at java.sql.DriverManager.getConnection(Unknown Source)
        at java.sql.DriverManager.getConnection(Unknown Source)


Solution :

Just make sure that password you provide is correct, Cross check the password you have provided.

Below is the simple JDBC test program, To run this program make sure you add Jar file like mysql-connector-java-5.1.5.jar to classpath.

Make sure you provide all correct login credentials in Step 2. i.e. port, database name and password.
/* Test.java */

import java.sql.*;
public class Test
{
public static void main(String[] args) throws Exception
{
Connection con;
Statement stat;
Class.forName("com.mysql.jdbc.Driver");//Step 1: Loading Drivers

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/Test","root","password");//Step 2: Making Connection

stat=con.createStatement();//Step 3: Creating JDBC Statement

String query = "select * from table_name;";

ResultSet rset=stat.executeQuery(query);//Step 4: Execute the Ststement

while(rset.next())//Step 5: Looping through the ResultSet
{
    System.out.println(rset.getString(1));
}
stat.close();//step 6: Close the Connection and Statement
con.close();
}
}

Friday, October 7, 2011

org.apache.lucene.store.LockObtainFailedException

While creating index files for Lucene 3.0.2 search engine I got below mentioned error.

Exception:

org.apache.lucene.store.LockObtainFailedException: Lock obtain timed out: NativeFSLock@/export/home/Lucene/indexFiles/write.lock
        at org.apache.lucene.store.Lock.obtain(Lock.java:84)
        at org.apache.lucene.index.IndexWriter.init(IndexWriter.java:1060)
        at org.apache.lucene.index.IndexWriter.(IndexWriter.java:882)


Solution :

Check for IndexWriter object. Make sure you close IndexWriter object after completing index creation.
Check for any exceptions and close IndexWriter object if exception occurs.

Possible reason is there may be any exception occurred and you missed to close the IndexWriter object in catch block.


code snippte:

// Store the index in file
Directory directory = new SimpleFSDirectory(new File(indexLoc));     
IndexWriter iwriter = new IndexWriter(directory, analyzer, isNew,MaxFieldLength.UNLIMITED);

iwriter.optimize();
iwriter.close();

If you need complete tested code for Lucene 3.0.2 example, click here

Saturday, October 1, 2011

Java : File copy program


Simple Java program to copy a file from its source to destination. Simply provide source file and a destination directory in the below function copyFunction(File srcFile,File destDirectory).


/* FileCopyProgram.java */
import java.io.*;
public class FileCopyProgram
{
public void copyFunction(File srcFile,File destDirectory)
{
try
{
String srcFilePath = srcFile.getPath();
String fileName = srcFilePath.substring(srcFilePath.lastIndexOf("\\")+1);
File destFile = new File(destDirectory.getPath()+"\\"+fileName);
InputStream inSrc = new FileInputStream(srcFile);
OutputStream outDest = new FileOutputStream(destFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inSrc.read(buffer)) > 0)
{
outDest.write(buffer, 0, bytesRead);
}
inSrc.close();
outDest.close();
System.out.println("File copy sucessfully : "+fileName);
}
catch (IOException ex)
{
System.out.println("Exception in copy : "+ex);
}
}
public static void main(String[] args) 
{
FileCopyProgram cf = new FileCopyProgram();
cf.copyFunction(new File("C:\\Test\\Noname1.txt"),new File("D:\\Software"));
}
}