Pages

Tuesday, December 31, 2013

Memory leak issue in tomcat [ "java.lang.OutOfMemoryError: PermGen space" error ]

Hi Guys,

While working with tomcat web application server with your J2EE web application, many times you come across the error as follows:

"java.lang.OutOfMemoryError: PermGen space" error

This error is because, the memory/space allocated to your tomcat process is not enough.
You can get rid of this problem by increasing JVM heap size.
To do so, here are the steps:

1. Go to CATALINE_BASE/bin/catalina.sh or CATALINE_BASE/bin/catalina.bat file.
2. make following entry in catalina.sh\catalina.bat file for JAVA_OPTS:

In Windows:

set JAVA_OPTS = -Xms1024m -Xmx10246m -XX:NewSize=256m -XX:MaxNewSize=356m -XX:PermSize=256m -XX:MaxPermSize=356m

In Linux:

export JAVA_OPTS="-Xms1024m -Xmx10246m -XX:NewSize=256m -XX:MaxNewSize=356m -XX:PermSize=256m -XX:MaxPermSize=356m"

You can change the actual heap size and PermGen Space as per your requirement.

Each of the otions are explained below.
•    Server – Run the tomcat in server mode. (the default is developer mode)
•    Xms – Minimum java heap space
•    Xmx – Maximum java heap space. While running on dedicated servers for production instances, keep both these options the same to ensure better utilization of available memory.
•    PermSize – The initial permSize. (default is 64MB)
•    Max PermSize – The maxPermSize. (even here, it may be a good idea to keep the intial and the max value the same).


3. Now, Restart your tomcat.

That's it...!!!
I hope this solutions works for you..
Please let me know, if you are still facing any issue even after following these steps.

Happy Coding...!!!
:)










Wednesday, December 11, 2013

Create J2EE MAVEN Project in Eclipse on Linux/Fedora/Unix

 Hi Guys,

Here I am going to show you the steps to configure J2EE maven project in Eclipse on Linux system:
I hope you are little bit aware of Maven and how to create a simple J2EE project in Maven.

1. Install jdk in your system.
2. Install maven in your system.
3. To configure maven, download maven tar ball and extract it in /usr/local folder.
4. set JAVA_HOME & MAVEN_HOME environment variables in your .bash_profile file.
  Steps:
1. login as root user
2. vi ~/.bash_profile
3. add following lines in it:
export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0
export PATH=$JAVA_HOME/bin:$PATH
export M2_HOME=/usr/local/apache-maven-3.1.1
export PATH=$M2_HOME/bin:$PATH
4. After adding the .bash_profile file, save and execute it to take it effect.
                   COMMAND:  source ~/.bash_profile
5. Add Maven plugIn in your eclipse IDE.
6. Go to Windows > Preferences > Maven Installation.
7. Add your local maven installation path over there. After that, it will update indexes. Let it finish.
8. Now, you are ready with maven installation.
9. To create new Maven project, Go to File> New> Maven> Maven Project. Create J2EE project with following artifact Id an group Id:
    artifact id: webapp-j2ee14
    group id: org.codehaus.mojo.archetypes

OR import existing project as maven project.

10. If you are deploying your web application on Tomcat and if you want to debug your project then refer:
        http://opensourcetechno.blogspot.in/2013/08/war-file-hot-deployment-issue-with.html
        http://opensourcetechno.blogspot.in/2012/11/remote-debug-on-tomcat-server-with-ant.html

11. When you deploy your web application, you may come accross "Permgen Space" exception on Tomcat Console. To resolve this, open your catalina.sh file (location:  <tomcat_home>/bin/) and make this entry for JAVA_OPTS.

JAVA_OPTS="-Dfile.encoding=UTF-8 -server -Xms512m -Xmx1024m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"

That's it...!!!
Please let me know if you face any issue while following this steps.

Happy Coding..!!
:)


Friday, November 15, 2013

Configure JBoss 5.1.GA server with MySql 5.1 Database as a default datasource


Hi All,

Here I am going to show you the steps to configure JBoss 5.1.GA Application Server with mysql 5.1 Database as a default data source. When you download JBoss Application Server at that time the default database is hsql. So, here are the step to configure mysql database instead of hsql:

1. create database schema in your mysql server. i.e jboss_as

2. Before proceed with mysql configuration, copy mysql jar file to <JBOSS_HOME>\server\default\lib
location.

3. Now, make mysql-ds.xml file and copy following contents in it. But before doing it you need to disable hsql-ds.xml file. Don't delete it. Just change it to hsql-ds.xml.sample by giving it .sample extension.



<?xml version="1.0" encoding="UTF-8"?>
<datasources>
	<local-tx-datasource>
		<jndi-name>DefaultDS</jndi-name>
		<connection-url>jdbc:mysql://localhost:3306/schema_name</connection-url>
		<driver-class>com.mysql.jdbc.Driver</driver-class>
		<user-name>root</user-name>
		<password>XXXXXXX</password>
		<min-pool-size>5</min-pool-size>
		<max-pool-size>20</max-pool-size>
		<transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation>
		<exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
		<valid-connection-checker-classname>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-classname>
		<metadata>
			<type-mapping>mySQL</type-mapping>
		</metadata>
	</local-tx-datasource>
</datasources>

4. Now, you also need to add mysql-persistence-service.xml file to <JBOSS_HOME>\server\default\deploy\messaging location. You will find this file at <JBOSS_HOME>\docs\examples\jms location. Just copy this file and paste it in messaging folder. One thing you need to do over here is disable the hsql-persistence-service.xml file by making it hsql-persistence-service.xml.sample

Once you are done with the above steps, just restart the JBoss.
After successful start up, you will see the tables to be created under your defined schema in mysql-ds.xml file.




That's it..!!!!
Happy Coding..!!!

Wednesday, November 13, 2013

Alfresco 4: Map network drive with any alfresco space On Windows 7 or Later

Hi All,

We all know alfresco is a very useful ECM.
It provides support to map alfresco repository as network drive.
But, I found that many developers is facing the problems to map network drive on windows machine.
Here I follow this steps and I am able to connect with alfresco repository with any folder/space.

1)
First step to connect with alfresco repository as a network drive, you need to do entry in your windows host file which resides in (windows\system32\etc\host). Edit this file with following entry and save it:

               <fake IP address>   <computerName><any letter>

              i.e. 13.13.13.13     WorkStationA

2)
Now, open alfresco-global.properties (\Alfresco\tomcat\shared\classes\alfresco-global.properties) and search for the property "protocols.rootPath".

This property is an xPath expression. From alfresco 4.0+, this location is pointing to site space in company home. Now, if you want to map your network drive with your custom space other then site, you need to modify this property.

i.e. 
protocols.rootPath=/${spaces.company_home.childname}/app:user_homes

Here, I have changed my path to "user homes" space. this way you can map any space with network drive in alfresco.

3)
After that, Go To My Computer and then click on Map Network Drive. Choose any drive letter and give folder path as \\WorkStationA\Alfresco\, here WorkStationA is the name which is defined in host file as discussed above in step 1. When you click next, you will be asked for the login credentials. Enter your alfresco login credentials.(Default login credential for admin is username: admin and password: admin).

4)
Now, if everything would be fine, you will find a network drive in My Computer. From here, you can directly do bulk upload of documents in alfresco repository as well as download them.

That's it !!!

I hope this will solve your problem.
Happy Coding !!!

Wednesday, August 7, 2013

WAR file hot deployment issue with Maven[Solved]

Hi guys,

In this blog, I am going to show you how to deploy your war file automatically when you are working with J2EE project using maven build tool.
To make J2EE project with Maven build tool, you should use

Group Id: org.codehaus.mojo.archetypes
Artifact Id: webapp-j2ee14

To build your project, you definitely run this two targets:
Maven Clean
Maven Install

After running "Maven Install", maven tool will compile your project and generate a WAR file under the target folder in your package structure. To deploy this WAR file, you need to manually copy-paste this WAR in tomcat/ webapps folder.

But It seems very tedious task to build WAR file, do copy-paste....

So here are some settings that you need to do in your pom.xml file to make it automated.

1. Do right click on your pom.xml in Eclipse, and select option for "add plugin".(DO NOT SELECT "Add Dependency" )
2. add plugin with artifact id: tomcat7-maven-plugin
3. add plugin with artiface id: maven-war-plugin
4. now, add following configuration for artifact id: maven-war-plugin

<warName>MyApplication</warName>
<outputDirectory>../../apache-tomcat-7.0.32/webapps</outputDirectory>


5. in step4, the <outputDirectory> is the path to your webapps folder of your tomcat. Path is with respect to your pom.xml file.
6. Run Maven Clean.
7. Run Maven Install.

Your war will be hot deployed on the running tomcat.
To test hot deployment, do some changes in your JSP files and run Maven Clean and Install again. The war will be reloaded.

Here is the entry of my pom.xml file:

        <build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.4</source>
<target>1.4</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.0</version>
<configuration></configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warName>MyApplication</warName>
<outputDirectory>../../apache-tomcat-7.0.32/webapps</outputDirectory>
</configuration>
</plugin>
</plugins>
</build>

That's it..!!!
Enjoy...!!!
Happy Coding...!!!

Saturday, February 2, 2013

Decode QR Code using Java


As in earlier post we had learn what is QR code and how can we generate QR code in java and servlet.
Now here I will show you how can we read QR Code in java.
Here again i had use same jar file as we had previous. ZXing- Zibra Corossing
Here is code to read/decode QR Code.
file: QRReader.java
import java.io.FileInputStream;
import javax.imageio.ImageIO;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

public class QRReader {

public static void main(String args[]){

Result result = null;
BinaryBitmap binaryBitmap;

try{

binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream("D:/Generated_QR.PNG")))));
result = new MultiFormatReader().decode(binaryBitmap);
System.out.println("QR Code : "+result.getText());

}catch(Exception ex){
ex.printStackTrace();
}
}
}

I hope, now you are clear with QR Code generation and decoding using Java.

Generate QR Code using Java and Servlet Integration


Nowadays, Quick Response (QR) Codes are becoming more and more useful as they have gone mainstream, thanks to the smart phones. Right from the bus shelter, product packaging, home improvement store, automobile, a lot of internet websites are integrating QR Codes on their pages to let people quickly reach them. With increase in number of users of smart phones day by day, the QR codes usage is going up exponentially.QR codes are a type of two-dimensional barcode. They are also known as hardlinks or physical world hyperlinks. QR Codes store up to 4,296 alphanumeric characters of arbitrary text. This text can be anything, for example URL, contact information, a telephone number etc.
Let us see a quick overview of Quick Response (QR) codes and also how to generate these codes in Java.
What is QR Code?
A QR code (abbreviated from Quick Response code) is a type of matrix barcode (or two-dimensional code) first designed for the automotive industry. More recently, the system has become popular outside of the industry due to its fast readability and comparatively large storage capacity. The code consists of black modules arranged in a square pattern on a white background. The information encoded can be made up of four standardized kinds (“modes”) of data (numeric, alphanumeric, byte/binary, Kanji), or by supported extensions virtually any kind of data.
Created by Toyota subsidiary Denso Wave in 1994 to track vehicles during the manufacturing process, the QR code is one of the most popular types of two-dimensional barcodes. It was designed to allow its contents to be decoded at high speed.


Let’s Create QR Code in JAVA


Zebra Crossing (ZXing) is an awesome open source library that one can use to generate / parse QR Codes in almost all the platforms (Android, JavaSE, IPhone, RIM, Symbian etc). But if you have to generate simple QR Codes, I found it a bit clumsy to implement.
However QRGen is a good library that creates a layer on top of ZXing and makes QR Code generation in Java a piece of cake. It has a dependency on ZXing, so you would need ZXing jar files along with QRGen to create QR Codes in Java.
Download this three files and rename it with .doc to .jar & put in lib to generate QR.
  • zxing-j2se-1.7.jar
  • zxing-core-1.7.jar
  • qrgen-1.0.jar

Include these JAR files in your Classpath and execute following Java code to generate QR Code

package com.opensourcetechno.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;

public class GenerateQR {
public static void main(String[] args) {

ByteArrayOutputStream out=QRCode.from("Dhaval Shah").to(ImageType.PNG).stream();

try {

FileOutputStream fout = new FileOutputStream(new File("D:\\Generated_QR.PNG"));

fout.write(out.toByteArray());

fout.flush();
fout.close();

} catch (FileNotFoundException e) {
// Do Logging
e.printStackTrace();
} catch (IOException e) {
// Do Logging
e.printStackTrace();
}
}
}


The code is pretty straight forward. We used QRCode class to generate QR Code Stream and write the byte stream to a file D:\Generated_QR.PNG.
If you open this JPEG file and scan using your iPhone or Android QR scanner, you’ll find a cool “Dhaval Shah” in it 
Apart from generating Sterams of data using QRGen API, we can also use below APIs to create QR Codes:
// get QR file from text using defaults
File file = QRCode.from("Hello World").file();
// get QR stream from text using defaults
ByteArrayOutputStream stream = QRCode.from("Hello World").stream();

// override the image type to be JPG
QRCode.from("Hello World").to(ImageType.JPG).file();
QRCode.from("Hello World").to(ImageType.JPG).stream();

// override image size to be 250x250
QRCode.from("Hello World").withSize(250, 250).file();
QRCode.from("Hello World").withSize(250, 250).stream();

// override size and image type
QRCode.from("Hello World").to(ImageType.GIF).withSize(250, 250).file();
QRCode.from("Hello World").to(ImageType.GIF).withSize(250, 250).stream();


Website Link (URLs) QR Code in Java
One of the most common use of a QR Code is to bring traffic to a particular webpage or download page of website. Thus QR Code encodes a URL or website address which a user can scan using phone camera and open in their browser. URLs can be straight forward included in QR Codes. In above Java Hello World example, just replace “Dhaval Shah” string with the URL you want to encode in QR Code. Below is the code snippet:
ByteArrayOutputStream out = QRCode.from("https://opensourcetechno.blogspot.com").to(ImageType.PNG).stream();
QR Code in Servlet


Most of the time you would need to generate QR Codes dynamically in some website. We already saw how easy it is to generate QR code in Java. Now we will see how to integrate this QR Code generation in a Java Servlet.
Following is a simple Http Servlet that creates QR Code using QRGen and ZXing library. User provides the text for which QR Code is generated.
The index jsp file contains a simple html form with a textbox and submit button. User can enter the text that user wishes to generate QR code of and presses submit.
file: index.jsp
<html>
<head>
<title>QR Code in Java Servlet</title>
</head>
<body>

<form action="generateQRServlet" method="get">
<p>Enter Text to create QR Code</p>
<input type="text" name="qrtext" />
<input type="submit" value="Generate QR Code" />
</form>
</body>
</html>

The actual logic will be in QRCodeServlet.java. Here we uses QRGen library along with ZXing and generates QR Code for given text (Text we get from request.getParameter). Once the QR Stream is generated, we write this to response and set appropriate content type.

file: GenerateQRCodeServlet.java

package com.opensourcetechno.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;

public class GenerateQRCodeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) 
throws ServletException, IOException {

String qrtext = request.getParameter("qrtext");

ByteArrayOutputStream out = QRCode.from(qrtext).to(
ImageType.PNG).stream();

response.setContentType("image/png");
response.setContentLength(out.size());

OutputStream outStream = response.getOutputStream();

outStream.write(out.toByteArray());

outStream.flush();
outStream.close();
}
}

The below web.xml simply maps GenerateQRCodeServlet.java with /GenerateQR URL.

<?xml version="1.0" encoding="UTF-8"?>
<web-app>

<display-name>QR_Code_Servlet</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>GenerateQRCodeServlet</servlet-name>
<servlet-class>com.opensourcetechno.util.GenerateQRCodeServlet
</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>GenerateQRCodeServlet</servlet-name>
<url-pattern>/GenerateQR</url-pattern>
</servlet-mapping>

</web-app>

Now execute in browser and you will get QR Code of entered text.
Generating QR Codes in Java is not only easy, but quite straight forward. Integrating this functionality with any existing Java based app is just a piece of cake! In this tutorial we saw how to generate these QR codes in Java and also with Servlet.
Happy Codding, guys...!!!



Friday, January 18, 2013

Select Box that loads its content using ajax call using Struts-JQuery Plugins

Hi Guys,

Here, I am going to show you the way to populate three select box using Struts-JQuery plugins via AJAX Call.
Let's take a very common example to populate Country, State and City in select box dynamically.
To do that, you need to call struts action that fetch the list of country/city/state from database or any static array list using AJAX call.
Here are the code snippet to do the same:

index.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<%@ taglib prefix="sj" uri="/struts-jquery-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<sj:head />
<body>
<s:form id="formSelectReload" theme="simple">

<s:url var="remoteurl" action="ajaxdemo" />
<sj:select 
             href="%{remoteurl}" 
             id="echo" 
             name="country"
     list="countryList" 
             onChangeTopics="reloadStateList"
             emptyOption="true" 
             headerKey="-1"
     headerValue="---Please Select Country---" />


<sj:select 
             href="%{remoteurl}" 
             id="selectWithReloadTopicSecond"
     formIds="formSelectReload" 
             reloadTopics="reloadStateList"
             onChangeTopics="reloadCityList" 
             name="state"
     list="stateList" headerKey="-1"
     headerValue="---Please Select State---" />

<sj:select 
             href="%{remoteurl}" 
             id="selectWithReloadTopicThird"
             formIds="formSelectReload"                            
             reloadTopics="reloadCityList" 
             name="city"
     list="cityList" 
             headerKey="-1"
     headerValue="---Please Select City---" />
</s:form>
</body>
</html>


The main thing you should notice here is onChangeTopics attribute.
The value, you provide here should be the same for the reloadTopics attribute of the next select box that you want to populate next. 
This way you can populate as many select box as you want to.
One more thing, I mentioned action="ajaxdemo" in <s:url> (which is common for all the three  select box) that calls struts action class mentioned in the mapping file struts.xml.
Here is the code snippet of sturts.xml

struts.xml


<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="AJAXPackage" extends="json-default">
   <action name="ajaxdemo"  
                class="com.actions.CountryStateCityAction" 
                method="myCustomMethod">
<result name="success" type="json"></result>
   </action>
</package>
</struts>


Here, in struts.xml file, the mentioned action class is CountryStateCityAction.java and method is myCustomMethod().
Here is the code of CountryStateCityAction.java file


CountryStateCityAction.java



import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

public class CountryStateCityAction extends ActionSupport {
private List<String> countryList;
private List<String> stateList;
private List<String> cityList;
private String state;
private String country;
private String city;
private String result;

public String myCustomMethod() {

countryList = new ArrayList<String>();
stateList = new ArrayList<String>();
cityList = new ArrayList<String>();

countryList.add("India");
countryList.add("US");
countryList.add("Japan");

if (country != null) {
if (country.equals("India")) {
stateList.add("Gujarat");
stateList.add("Maharashtra");
stateList.add("Delhi");
} else if (country.equals("US")) {
stateList.add("Washington");
stateList.add("NJ");
stateList.add("NY");
} else if (country.equals("Japan")) {
stateList.add("Tokyo");
stateList.add("Kagoshima");

}
}

if (state != null) {
if (state.equals("Gujarat")) {
cityList.add("Ahmedabad");
cityList.add("Surat");
} else if (state.equals("Maharashtra")) {
cityList.add("Mumbai");
cityList.add("Pune");
}
}
result = "success";
return result;
}

public List<String> getCountryList() {
return countryList;
}

public void setCountryList(List<String> countryList) {
this.countryList = countryList;
}

public String getResult() {
return result;
}

public void setResult(String result) {
this.result = result;
}

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}

public List<String> getStateList() {
return stateList;
}

public void setStateList(List<String> stateList) {
this.stateList = stateList;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public List<String> getCityList() {
return cityList;
}

public void setCityList(List<String> cityList) {
this.cityList = cityList;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}
}


One main important thing, don't forget to add filter entry in your web.xml file. :-p

Here is the entry for filter that you have to add in your web.xml file before running this demo:


<filter>
   <filter-name>Struts2</filter-name>
   <filter-class>
     org.apache.struts2.dispatcher.FilterDispatcher
   </filter-class>
</filter>
<filter-mapping>
   <filter-name>Struts2</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>


And you have to add these two JAR files with other struts JAR files while running this demo:

struts2-jquery-plugin-2.3.1.jar
struts2-json-plugin-2.3.4.jar


Now you are done.Try it yourself. 
You can fill up the list values dynamically using database as well.
Happiee Coding...!!!