Friday, April 8, 2011

[Maven] Integrate Maven with Eclipse


To integrate Maven with Eclipse, just follow the steps mentioned below and you're done!

Install Maven (3.0.3)

   1. Download Maven and unzip it.

   2. Create MAVEN_HOME System Variable.

   3. Add %MAVEN_HOME%\bin; to your System Path.

   4. On command prompt, type "mvn -version" to verify the installation, it will display following information

Apache Maven 3.0.3 (r1075438; 2011-02-28 22:31:09+0500)
Maven home: C:\Program Files\apache-maven-3.0.3\bin\..
Java version: 1.6.0_24, vendor: Sun Microsystems Inc.
Java home: C:\Program Files\Java\jdk1.6.0_24\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "x86", family: "windows"

   5. On command prompt, type "mvn clean". This will download some jar files from Maven central repositor, followed by some BUILD FAILURE error indicating missing POM (pom.xml) file in current directory; so dont worry about it.

   6. Go to user home directory (for e.g. C:\Users\<username>), you'll find an .m2 folder with 'repository' subfolder. This is default local Maven repository location. As a result of "mvn clean" command, Maven downloaded maven-clean-plugin-2.4.1.jar file in it which you can see under C:\Users\<username>\.m2\repository\org\apache\maven\plugins\maven-clean-plugin\2.4.1 folder.

Now Maven is installed and ready to use with other projects.


Installing Maven Plugin for Eclipse

   1. After installing eclipse, install M2Eclipse in Eclipse using following update sites:

Maven Integration for Eclipse: http://m2eclipse.sonatype.org/sites/m2e/0.12.1.20110112-1712/
Maven Integration for Eclipse Update Site: http://m2eclipse.sonatype.org/update/

   2. As soon as you're done with all the steps followed by restart of Eclipse, you're now ready to Import your existing Maven projects in it.

   3. But before that, you might see a Maven Integration for Eclipse JDK Warning, stating to verify -vm option in eclipse.ini pointing to a JDK.

   4. To fix this, go to Eclipse installation directory (i.e. ECLIPSE_HOME), you'll see eclipse.ini file which contains command-line options that are added to the command line used to when Eclipse is started up.

   5. Add following lines to eclipse.ini before the -vmargs option, since everything after -vmargs is passed directly to the JVM.

-vm
C:\Java\JDK\1.5\bin\javaw.exe

Please note that the -vm option and its value (the path) must be on separate lines. Also, the value must be the full absolute path to the Java executable, not just to the JAVA_HOME directory. 

This will fix the JDK warning from Maven plugin, and now you can use Maven commands directly from Eclipse.

Saturday, February 19, 2011

[Java] JAXB to create Java Stubs from XML schema

One of the ways to create client stubs in Java is through XML schema. Once we have server side artifacts, we can generate fully annotated Java classes from an XML schema file by using the JAXB schema compiler, i.e. xjc command-line tool. The resulting JAXB objects/Java Stubs can be used in Java applications to manipulate the XML request and response data.

Steps to follow:

1. Copy the XML schema to a file <schema-fileName>.xsd in <source-directory>. Or create XSD schema for web service with .xsd.

2. From <source-directory>, use following command to create java stubs from that xsd

xjc <source-directory>\<schema-fileName>.xsd -p <destination-package> -d <destination-directory>

3. Use the generated JAXB objects within your Java application to manipulate XML content through the generated JAXB classes.

4. Use following command to compile and generate .class files

javac -d <directory-for-classFiles> <destination-directory>\*.java

5. Now to have .jar file for these generated stubs, we can use following command

cd <directory-for-classFiles>
jar cvf <jar-filename>.jar

6. Copy .jar file in lib folder of your application for further access.

Wednesday, February 16, 2011

[Linux - Ubuntu] Creating Shell Script

Below is an easy and simple way to create a shell script for Ubuntu (Linux). 

1. Example is to stop Tomcat, copy some application files and start Tomcat. Write following sample Linux commands in a file and save it as <shell-script>.sh

#!/bin/sh
echo Deploying JAVA Application

echo Stopping Tomcat Service...
cd /usr/local/tomcat/bin
./catalina.sh stop

echo
echo

echo Copying Application Files...
cd <source-directory>
cp -R * <destination-directory>
rm <some-file-name>.<extension>
mv <source-file-name>.<extension>  <destination-file-name>.<extension>

echo
echo

echo Deployment Compelted. Starting Tomcat Service...
cd /usr/local/tomcat/bin
./catalina.sh start

echo
echo

2. Grant permissions to this file:
chmod 777 <shell-script>.sh

3.  Run this shell script as:
./<shell-script>.sh

4. Now, use following command to get the Catalina Logs to assure everything is working fine:
tail -f /usr/local/tomcat/logs/catalina.out

... and that's it.

Thursday, December 23, 2010

[SQL Server] Paging with Total Record Count in SQL Server 2005


In professional business, developers are usually required to query database and fetch results. With huge datasets, it downgrades the application performance. One of the solutions to this problem is paging which allows the user to fetch small chunks of data and traverse the entire dataset through forward/backward navigations.

While paging, developers do a big mistake. They fetch the entire dataset and filter out required data chunk at application level. This works pretty well with small datasets, but doesn’t suit well for huge datasets. The good approach is to request only the required chunk of data and improve the application response time. This is how we’ll do it:

Java Code:

private static final int DEFAULT_PAGE_SIZE = 10;
int totalRecords = -1, recordShowing = 0, pageIndex = 0, pageSize = DEFAULT_PAGE_SIZE;

String action = request.getParameter("action");
pageIndex = StringUtils.isBlank( request.getParameter("pageIndex") ) ? 0 : Integer.valueOf(request.getParameter("pageIndex")) ;   
pageIndex = (pageIndex <= 0) ? 0 : pageIndex;

if ( action.equalsIgnoreCase("showNone") ) {
    // Some code to display default page, when no action is set (if required)...
}
else {
    // Set page Index and page Size, based on user action
    if ( action.equalsIgnoreCase("showAll") ) {    // for Show All records
        pageSize = -1;
        pageIndex = 0;
    }
    else if ( action.equalsIgnoreCase("showPrev") ) { // for Backward navigation
        pageIndex = (pageIndex <= 0) ? 0 : (pageIndex - 1);   
    }
    else if ( action.equals("showNext") ) { // for Forward Navigation
        pageIndex = pageIndex < 0 ? 0 : (pageIndex + 1);
    }
   
    int startIndex = (pageSize < 0) ? -1 : (pageIndex * pageSize) + 1;
    int endIndex = (pageSize < 0) ? -1 : (pageIndex * pageSize) + pageSize;

    /**
    *    Call your DAO method to fetch the required result set...
    *     Here I'm assuming that result set is returned in following fashion:
    *
    *    Map<Object, Object> serachResult = new HashMap<Object, Object>();
    *    serachResult.put("totalRecords", totalRecords);
    *    serachResult.put("resultList", resultList);
    */
   
    // Set variables based on the result set 
    // to display proper pagination info to the user
    totalRecords = Integer.valueOf( resultSet.get("totalRecords").toString() );
    pageSize = (pageSize == -1) ? totalRecords : pageSize;
   
    if ( action.equalsIgnoreCase("showAll") ) {
        recordShowing = resultList.size();
    }
    else {
        recordShowing = resultList.size() < DEFAULT_PAGE_SIZE ? totalRecords : (pageIndex + 1) * DEFAULT_PAGE_SIZE;
    }   
}

 
SQL Query:

In SQL, we can achieve this through temp. tables and CTE (Common Table Expressions) as well. But what if these are not the options for us. Below is how we can do it through select query. 

SELECT *  FROM (
    SELECT *, ROW_NUMBER() OVER (ORDER BY <column-name>) AS ROWNUM
    , COUNT(1) OVER () AS TOTALRECORDS
    FROM <table-name>
    WHERE <conditions>
) recSet
WHERE ((@startIndex = -1 AND @endIndex = -1) OR (ROWNUM BETWEEN @startIndex AND @endIndex ))
ORDER BY <column-name>

Friday, December 17, 2010

[Java] Error: Method getBindStatus threw exception for reference $springMacroRequestContext

Recently, I came across a problem while working on Spring framework and Velocity; the exception appears to be "ERROR [velocity.app.VelocityEngine] Method getBindStatus threw exception for reference $springMacroRequestContext in template <xyz.vm>". Apparently, it seems like velocity was unable to call the macro or unable to bind some variable in the template.

Actually, I used macro to display tree structure, defined on two different velocity templates, both macro have the same name but different variables were bind with respect to each template requirement. This caused the first visited page to be loaded properly, and on visiting next page, the same macro (from the first page) is called at back end, hence was throwing above mentioned exception. The exception occured because JVM was unable to find the variables used in first template macro, while loading the macro in second template with same macro name.

The solution, is quite simple to this problem. To use different macro name in each template, IF it has any variable or form controls specific to that particualar template.

Another useful information: Changes done in velocity macros do not appear until we restart Tomcat. To have macros changes appear on browser without restarting Tomcat, just change the macro name and refresh the browser.

Enjoy working with Velocity templates. :)