Monday, March 30, 2015

Solution for "Initialized java loader error" in mysql Migration toolkit



















Step 1: Open the command prompt. Change to the mysql tools installation path (path will be vary based on the installed Mysql version)

         C:\Documents and Settings\System14>cd C:\Program Files\MySQL\MySQL Tools for 5.0

Step 2: And then type the following command(jvm.dll path will be vary based on the installed java version)

           C:\Program Files\MySQL\MySQL Tools for 5.0>MySQLMigrationTool -verbose 
           -jvm    "C:\Program Files\Java\jre7\bin\client\jvm.dll"

The java loader initialized successfully..

Saturday, March 14, 2015

How to Create Dynamic Web Project using Maven in Eclipse?

Apache Maven Tips
Today I want to talk about Maven. It’s very powerful instrument and if you know how to use it you will make minimum effort to achieve maximum result. In general Maven helps you to manage a project including library dependencies, building process and etc…apacheMaven - Crunchifiy
Here is a simple tutorial which you can go through to create Dynamic Web Project having Maven enabled in Eclipse. This project can be used as base project and can be easily converted to most kind of advanced Java project like Spring MVC based etc. How to create a Web Application Project with Maven?

Tools I’m using:

  • Eclipse EE
  • Maven
  • JSK 1.7
  • M2Eclipse Plugin

Assumption:

You have setup Maven and Apache Tomcat Server successfully in your Eclipse Environment.

Step-1

Create a simple maven Project in Eclipse.
Create Simple Maven Project in Eclipse

Step-2

Select default Workspace location
Use Default Workspace Location

Step-3

Select the maven archetype as: maven-archetype-webapp and click on next.
Select maven-archetype-webapp

Step-4

Fill out below details and click Finish. This step created Maven Project in your Eclipse Environment.
Create Crunchify Maven Project in Eclipse

Step-5

If you see error “The superclass “javax.servlet.http.HttpServlet” was not found on the Java Build Path index.jsp /CrunchifyMavenTutorial/src/main/webapp” then add Apache Tomcat to your Targeted Runtimes.
HTTPServlet Error? Add Target Runtime
Targeted Runtime - Apache Tomcat

Step-6

Your Maven Project should look like this.
CrunchifyMavenTutorial Eclipse Structure

Step-7

Now build project with “Maven Clean Install” to check there isn’t any dependency issue with project. Crunchify - Maven-RunAs-MavenBuild...
Maven Clean Install in Eclipse
Maven Build Successmessage in Eclipse Console

Step-8

Deploy Application on Apache Tomcat Server.
Steps:
  • Right click on Server -> Add and Remove -> Select CrunchifyMavenTutorial -> Click Finish.
  • Start tomcat server.

Step-9

Visit http://localhost:8080/CrunchifyMavenTutorial/index.jsp to see your result.
CrunchifyMavenTutorial Web Result
And you are all set.
Have anything to add to this article? Please chime in and join the conversion.

Friday, March 13, 2015

INSTALLING M2ECLIPSE – MAVEN PLUGIN FOR ECLIPSE

In this tutorial, we will see how to install m2eclipse plugin which provides Maven integration in Eclipse IDE. m2eclipse provides first-class Apache Maven support in the Eclipse IDE, making it easier to edit Maven’s pom.xml, run a build from the IDE and much more.

Environment Used

  • Java SE 6
  • Eclipse Juno for Java EE Developers (4.2) IDE
  • Maven Eclipse Plugin – m2eclipse version 1.2

Installing JDK

JDK should be installed with proper environment set up. Read this page for installing the JDK and setting up the environment.

Installing Eclipse IDE

Make sure you have Eclipse IDE installed. If you need to install Eclipse, you can read this page.

Online Installation (From Update Site) of Maven Plugin m2eclipse

You can install Maven plugin for Eclipse via update site, simply copy the above update site link address and paste it into Eclipse’s “Update” or “Install New Software” manager as explained below.

Step 1:

Installing m2eclipse is fairly simple. Start Eclipse then go to:
Help -> Install New Software…
Copy this link http://download.eclipse.org/technology/m2e/releases for the latest Stable Release into Eclipse and hit Enter.
When the site loads, select the features to install, or click the Select All button. For our requirement select “Maven Integration for Eclipse” as shown above.
Checking [x] Contact all update sites during install to find required software might take sometime and this is optional.

Step 2:

  • Click Next to view Installation Details.
  • Click Next to agree the license terms, and click Finish.

Step 3:

If you get any warning message when installing, click OK to continue.
This will take few minutes to install the Maven plugin and once done restart the Eclipse.

Creating New Maven Project in Eclipse

After installing the Maven plugin for Eclipse, you can check if the installation is successful by creating a new Maven project.
You should see a Maven folder in the New project wizard as shown below.
Now you have successfully installed “Maven plugin – m2eclipse” in Eclipse IDE.

Thursday, March 12, 2015

How to automatically deploy maven project from eclipse to tomcat

There are two plugins that combined together in Eclipse work quite well together to perform what you want:
  1. M2E: M2Eclipse which handles everything related to Maven.
  2. Eclipse Web Tool Platform (WTP): which handles everything Java EE related (Tomcat, JBoss, etc...)
For M2E to work properly with WTP, you need to add m2e-wtp. You may find several useful information as well as some good links here.
I would start from the Eclipse Java EE distribution (it includes already Eclipse-WTP) and then add M2E (either with their update site or through eclipse market place: look for M2E and M2E-WTP).
From there, you create a Web Project and you can run it on a Tomcat server. The first time you try to run you project on a server, you will install Tomcat and it will appear in view named "Server". Double click on the server to configure ports, automatic deployment etc...

Monday, February 23, 2015

How to create a maven project

mvn -X  archetype:generate -DarchetypeArtifactId=maven-archetype-quickstart -DgroupId=com.hordine  -DartifactId=hordineCmdTwitter
 
 
mvn eclipse:eclipse
 
 
mvn package
 
mvn clean install  


Thursday, February 12, 2015

Parsing JSON string in Java

Here is the fully working and tested corrected code:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ShowActivity {


  private final static String JSON_DATA =
     "{" 
   + "  \"geodata\": [" 
   + "    {" 
   + "      \"id\": \"1\"," 
   + "      \"name\": \"Julie Sherman\","                  
   + "      \"gender\" : \"female\"," 
   + "      \"latitude\" : \"37.33774833333334\"," 
   + "      \"longitude\" : \"-121.88670166666667\""
   + "    }," 
   + "    {" 
   + "      \"id\": \"2\"," 
   + "      \"name\": \"Johnny Depp\","          
   + "      \"gender\" : \"male\"," 
   + "      \"latitude\" : \"37.336453\"," 
   + "      \"longitude\" : \"-121.884985\""
   + "    }" 
   + "  ]" 
   + "}"; 

  public static void main(final String[] argv) throws JSONException {
    final JSONObject obj = new JSONObject(JSON_DATA);
    final JSONArray geodata = obj.getJSONArray("geodata");
    final int n = geodata.length();
    for (int i = 0; i < n; ++i) {
      final JSONObject person = geodata.getJSONObject(i);
      System.out.println(person.getInt("id"));
      System.out.println(person.getString("name"));
      System.out.println(person.getString("gender"));
      System.out.println(person.getDouble("latitude"));
      System.out.println(person.getDouble("longitude"));
    }
  }
}
 
 
 
 
Here's the output:
C:\dev\scrap>java -cp json.jar;. ShowActivity 1 Julie Sherman female 37.33774833333334 -121.88670166666667 2 Johnny Depp male 37.336453 -121.884985
 

Wednesday, February 11, 2015

Parse JavaScript with jsoup

Document doc = Jsoup.parse(html);

Element script = doc.select("script").first();

Sunday, February 8, 2015

how to extract zip file in linux

Use unzip command:


Code:
unzip file.zip
many time unzip is not installed by default so install it before using it, use rpm or apt-get/yum command to install unzip

How to open link in new tab on html?

Set the 'target' attribute of the link to _blank:

<a href="#" target="_blank">Link</a>
 
Edit: for other examples, see here: http://www.w3schools.com/tags/att_a_target.asp

(Note: I previously suggested blank instead of _blank because, if used, it'll open a new tab and then use the same tab if the link is clicked again. However, this is only because, as GolezTrol pointed out, it refers to the name a of a frame/window, which would be set and used when the link is pressed again to open it in the same tab).

First Login: HTTP Status 500 - Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException

It appears that MySQL or a firewall is killing off your inactive connections that are hanging around in your jdbc connection pool for long periods of time:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure 
The last packet successfully received from the server was 4,665,488 milliseconds ago.

Check the value of wait_timeout on MySQL.

You can play around with DBCP settings e.g. validationQuery, testOnBorrow and testWhileIdle.

A a confuguration that is 'belt and braces', and will probably solve your problem at the expense of performance is:
 
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
  <property name="driverClassName" value="${jdbc.driverClassName}"/>
  <property name="url" value="${jdbc.url}"/>
  <property name="username" value="${jdbc.username}"/>
  <property name="password" value="${jdbc.password}"/>
  <property name="validationQuery" value="SELECT 1"/>
  <property name="testOnBorrow" value="true"/>
</bean>
The above will test connections every time you borrow from the pool.

Thursday, February 5, 2015

Solving the mySQL “The security settings could not be applied” error

Yesterday I got this error message during the last step of the MySQL Windows installer: “The security settings could not be applied to the database because the connection has failed with the following error”.

The issue can be solved issue this procedure from the MySQL website.

First, cancel the wizard and make sure that the MySQL service is stopped.

Then, create a text file using a SQL query that will reset the root password.

1
2
UPDATE mysql.user SET Password=PASSWORD('admin') WHERE User='root';
FLUSH PRIVILEGES;

Then, launch mySQL using the following command line:

1
mysqld --defaults-file="C:\Program Files\MySQL\MySQL Server 5.5\my.ini" --init-file="C:\mysql-init.txt" --console

Note: it’s better to use the ”–console” option so that error messages are correctly displayed.

Finally, open a new DOS shell and execute the following command line to shutdown mySQL:

1
mysqladmin -u root -p shutdown

You can now restart the mySQL installer and choose the “Repair” option:


2 solution of java.lang.OutOfMemoryError in Java

ava.lang.OutOfMemoryError now and then, OutOfMemoryError in Java is one problem which is more due to system's limitation (memory) rather than due to programming mistakes in most cases though in certain cases you could have memory leak which causing OutOfMemoryError. I have found that even though java.lang.OutOfMemoryError is quite common basic knowledge of its cause and solution is largely unknown among junior developers. In this article we will explore what is java.lang.OutOfMemoryError; Why OutOfMemoryError comes in Java application, different type of OutOfMemoryError and How to fix OutOfMemoryError in Java. This article is purely meant to provide basic knowledge of java.lang.OutMemoryError and won't discuss profiling in detail.


What is java.lang.OutOfMemoryError in Java

java.lang.OutOfMemoryError in Java, PermGen space or heap spaceOutOfMemoryError in Java is a subclass of java.lang.VirtualMachineError and JVM throws java.lang.OutOfMemoryError when it ran out of memory in heap. OutOfMemoryError in Java can come any time in heap mostly while you try to create an object and there is not enough space in heap to allocate that object. javavdoc of OutOfMemoryError is not very informative about this though.

Types of OutOfMemoryError in Java

I have seen mainly two types of OutOfMemoryError in Java:

1) Java.lang.OutOfMemoryError: Java heap space
2) Java.lang.OutOfMemoryError: PermGen space

Though both of them occur because JVM ran out of memory they are quite different to each other and there solutions are independent to each other.

Difference between "java.lang.OutOfMemoryError: Java heap space" and "java.lang.OutOfMemoryError: PermGen space"

If you are familiar with different generations on heap and How garbage collection works in java and aware of new, old and permanent generation of heap space then you would have easily figured out this OutOfMemoryError in Java. Permanent generation of heap is used to store String pool and various Meta data required by JVM related to Class, method and other java primitives. Since in most of JVM default size of Perm Space is around "64MB" you can easily ran out of memory if you have too many classes or huge number of Strings in your project. Important point to remember is that it doesn't depends on –Xmx value so no matter how big your total heap size you can ran OutOfMemory in perm space. Good think is you can specify size of permanent generation using JVM options "-XX:PermSize" and  "-XX:MaxPermSize" based on your project need.

One small thing to remember is that "=" is used to separate parameter and value while specifying size of perm space in heap while "=" is not required while setting maximum heap size in java, as shown in below example.

export JVM_ARGS="-Xmx1024m -XX:MaxPermSize=256m"


Another reason of "java.lang.OutOfMemoryError: PermGen" is memory leak through Classloaders and it’s very often surfaced in WebServer and application server like tomcat, webshere, glassfish or weblogic. In Application server different classloaders are used to load different web application so that you can deploy and undeploy one application without affecting other application on same server, but while undeploying if container some how keeps reference of any class loaded by application class loader than that class and all other related class will not be garbage collected and can quickly fill the PermGen space if you deploy and undeploy your application many times. "java.lang.OutOfMemoryError: PermGen” has been observed many times in tomcat in our last project but solution of this problem are really tricky because first you need to know which class is causing memory leak and then you need to fix that. Another reason of OutOfMemoryError in PermGen space is if any thread started by application doesn't exit when you undeploy your application.
These are just some example of infamous classloader leaks, anybody who is writing code for loading and unloading classes have to be very careful to avoid this. You can also use visualgc for monitoring PermGen space, this tool will show graph of PermGen space and you can see how and when Permanent space getting increased. I suggest using this tool before reaching to any conclusion.
Another rather unknown but interesting cause of "java.lang.OutOfMemoryError: PermGen" we found is introduction of JVM options "-Xnoclassgc". This option sometime used to avoid loading and unloading of classes when there is no further live references of it just to avoid performance hit due to frequent loading and unloading, but using this option is J2EE environment can be very dangerous because many framework e.g. Struts, spring etc uses reflection to create classes and with frequent deployment and undeployment you can easily ran out of space in PermGen if earlier references was not cleaned up. This instance also points out that some time bad JVM arguments or configuration can cause OutOfMemoryError in Java.
So conclusion is avoid using "-Xnoclassgc" in J2EE environment especially with AppServer.


Tomcat to Solve OutOfMemoryError in PermGen Space

From tomcat > 6.0 onward tomcat provides memory leak detection feature which can detect many common memory leaks on web-app perspective e.g ThreadLocal memory leaks, JDBC driver registration, RMI targes, LogFactory and Thread spawned by web-apps. You can check complete details on htp://wiki.apache.org/tomcat/MemoryLeakProtection you can also detect memory leak by accessing manager application which comes with tomcat, in case you are experiencing memory leak on any java web-app its good idea to run it on tomcat.

How to solve java.lang.OutOfMemoryError: Java heap space


1) Easy way to solve OutOfMemoryError in java is to increase the maximum heap size by using JVM options "-Xmx512M", this will immediately solve your OutOfMemoryError. This is my preferred solution when I get OutOfMemoryError in Eclipse, Maven or ANT while building project because based upon size of project you can easily ran out of Memory.here is an example of increasing maximum heap size of JVM, Also its better to keep -Xmx to -Xms ration either 1:1 or 1:1.5 if you are setting heap size in your java application

export JVM_ARGS="-Xms1024m -Xmx1024m"

2) Second way to resolve OutOfMemoryError in Java is rather hard and  comes when you don't have much memory and even after increase maximum heap size you are still getting java.lang.OutOfMemoryError, in this case you probably want to profile your application and look for any memory leak. You can use Eclipse Memory Analyzer to examine your heap dump or you can use any profiler like Netbeans or JProbe. This is tough solution and requires some time to analyze and find memory leaks.

How to solve java.lang.OutOfMemoryError: PermGen space

As explained in above paragraph this OutOfMemory error in java comes when Permanent generation of heap filled up. To fix this OutOfMemoryError in Java you need to increase heap size of Perm space by using JVM option   "-XX:MaxPermSize". You can also specify initial size of Perm space by using    "-XX:PermSize" and keeping both initial and maximum Perm Space you can prevent some full garbage collection which may occur when Perm Space gets re-sized. Here is how you can specify initial and maximu Perm size in Java:

export JVM_ARGS="-XX:PermSize=64M -XX:MaxPermSize=256m"

Some time java.lang.OutOfMemoryError  in Java gets tricky and on those cases profiling remain ultimate solution.Though you have freedom to increase heap size in java, it’s recommended that to follow memory management practices while coding and setting null to any unused references.
That’s all from me on OutOfMemoryError in Java I will try to write more about finding memory leak in java and using profiler in some other post. Please share what is your approach to solve java.lang.OutOfMemoryError in Java.


Important Note: From Tomcat > 6.0 onward tomcat provides memory leak detection feature which can detect many common memory leaks on Java application e.g ThreadLocal memory leaks, JDBC driver registration, RMI targes, LogFactory and Thread spawned by webapps. You can check complete details on htp://wiki.apache.org/tomcat/MemoryLeakProtection. You can also detect memoy leak by accessing manager application which comes with tomcat, in case you are experiencing memory leak on any java webapp its good idea to run it on tomcat to find out reason of OutOfMemoryError in PermGen space.

Tools to investigate and fix OutOfMemoryError in Java

Java.lang.OutOfMemoryError is a kind of error which needs lot of investigation to find out root cause of problem, which object is taking memory, how much memory it is taking or finding dreaded memory leak and you can't do this without having knowledge of available tools in java space. Here I am listing out some free tools which can be used to analyze heap and will help you to find culprit of OutOfMemoryError
1) Visualgc
Visualgc stands for Visual Garbage Collection Monitoring Tool and you can attach it to your instrumented hostspot JVM. Main strength of visualgc is that it displays all key data graphically including class loader, garbage collection and JVM compiler performance data.
The target JVM is identified by its virtual machine identifier also called as vmid. You can read more about visualgc and vmid options here.
2) Jmap
Jmap is a command line utility comes with JDK6 and allows you to take a memory dump of heap in a file. It’s easy to use as shwon below:
jmap -dump:format=b,file=heapdump 6054
Here file specifies name of memory dump file which is "heapdump" and 6054 is PID of your Java progress. You can find the PDI by using "ps -ef” or windows task manager or by using tool called "jps"(Java Virtual Machine Process Status Tool).
3) Jhat
Jhat was earlier known as hat (heap analyzer tool) but it is now part of JDK6. You can use jhat to analyze heap dump file created by using "jmap". Jhat is also a command line utility and you can rum it from cmd window as shown below:
jhat -J-Xmx256m heapdump
Here it will analyze memory-dump contained in file "heapdump". When you start jhat it will read this heap dump file and then start listening on http port, just point your browser into port where jhat is listening by default 7000 and then you can start analyzing objects present in heap dump.
4) Eclipse memory analyzer
Eclipse memory analyzer (MAT) is a tool from eclipse foundation to analyze java heap dump. It helps to find classloader leaks and memory leaks and helps to minimize memory consumption.you can use MAT to analyze heap dump carrying millions of object and it also helps you to extract suspect of memory leak. See here for more information.