Tuesday, 19 May 2015

Where and how-much Java technology used

What’s going on in Java these days?

Last year, we tackled two particular challenges that really matter to productive software organizations: software quality (got bugs?) and the predictability of delivery (last week or next year?). We learned a lot from that one!

But now we feel like it’s time to revisit the broader tools & technologies landscape in Java these days, collect some data, crunch some numbers and see what’s going on in the market at large. And what better way than  a huge leaderboard of tools and technologies currently running the show as of May 2014!!

JUnit - 82.5% - Top testing framework used by developers  Jenkins - 70% - Most used CI server in the industry Git - 69% - #1 version control technology out there Hibernate - 67.5% - The top ORM framework used Java 7 - 65% - The industry leader for SE development Maven - 64% - Most used build tool in Java Nexus - 64% - The main repository used by developers  MongoDB - 56% - The NoSQL technology of choice FindBugs - 55% - Most-used static code analysis tool in Java  Tomcat - 50% - The most popular application server on the market  Java EE 6 - 49% - Found in the most enterprise Java environments  Eclipse - 48% - The IDE used more than any other Spring MVC - 40% - The most commonly used web framework  MySQL - 32% - The most popular SQL technology

As you can guess, in some categories multiple tools are often used in conjunction, so we allowed for multiple selections (denoted by *). For answers where a statistically significant portion (over 5%) of respondents selected “Do not use”, the responses have been normalized (denoted by ยบ) to exclude non-user groups.

It probably comes as no surprise that among the 2164 developers we surveyed, Java SE 7 (65%) is used by two-thirds of developers, but even more are using JUnit (82.5%), the most-used single technology across the entire Java landscape. And a good thing too: unit testing is key for making sure your app gets out the door. Next is Jenkins (70%), our favorite Lord of the Butlers, which is used by nearly 3 out of 4 developers that use Continuous Integration tools (1 in 5 does not). We've seen distributed VCS come a long way in recent years, and Git (69%) is now non-exclusively used by over two-thirds of developers – often alongside Subversion (57%).

Taking in the next set of tech leaders really completes the Enterprise Java picture – Hibernate (67.5%), Maven and Nexus (64%), Tomcat (50%) and Eclipse (48%) gives you more or less a decent foundation of a basic, no frills enterprise development stack.

But don't think the last words have been had yet…because in this report we asked a few questions that directly highlight the feelings of developers towards certain technologies.

Thursday, 30 April 2015

How to resolve tomcat – java.lang.OutOfMemoryError: PermGen space

Often time, Tomcat may hits the following java.lang.OutOfMemoryError: PermGen space error.
java.lang.OutOfMemoryError: PermGen space
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
It’s usually happened after the Tomcat restarts a few times.

1. Solution

By default, Tomcat is assigned a very little PermGen memory for the running process. To fix it, increase the PermGen memory settings by using the following Java VM options.
In eclipse by default it is 256 MB. You can increase it by your need. If you are use eclipse then set this value in "eclipse.ini" initialization file.
-XX:PermSize<size> - Set initial PermGen Size.
-XX:MaxPermSize<size> - Set the maximum PermGen Size.
In the next step, we will show you how to set the VM options in Tomcat, under Windows and Linux environment.

2. Windows

Tomcat is managed by this script file catalina.bat, dive inside the script, you will find out thatcatalina.bat always find and run the setenv.bat file to set the environment variables.
{$tomcat-folder}\bin\catalina.bat
//...
rem Get standard environment variables
if not exist "%CATALINA_BASE%\bin\setenv.bat" goto checkSetenvHome
call "%CATALINA_BASE%\bin\setenv.bat"
goto setenvDone
:checkSetenvHome
if exist "%CATALINA_HOME%\bin\setenv.bat" call "%CATALINA_HOME%\bin\setenv.bat"
:setenvDone
//...
2.1 To set the environment variable on Windows, create a setenv.bat manually, and put it into the${tomcat-folder}\bin folder.
${tomcat-folder}\bin\setenv.bat
set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m
P.S No double quotes, set JAVA_OPTS={value}.
2.2 Restart Tomcat, it will call the setenv.bat file to set the environment variable automatically.
{$tomcat-folder}\bin\catalina.bat restart

3. Linux

On Linux, the process is same, just Tomcat is using catalina.sh and setenv.sh instead.
3.1 Find out where is catalina.sh :
catalina.sh
$ sudo find / -name "catalina.sh"
Password:
find: /dev/fd/3: Not a directory
find: /dev/fd/4: Not a directory
/Users/mkyong/Downloads/apache-tomcat-6.0.35/bin/catalina.sh
3.2 Review the catalina.sh, script, it behaves like Windows, but use setenv.sh instead.
//...
# Ensure that any user defined CLASSPATH variables are not used on startup,
# but allow them to be specified in setenv.sh, in rare case when it is needed.
CLASSPATH=
 
if [ -r "$CATALINA_BASE/bin/setenv.sh" ]; then
  . "$CATALINA_BASE/bin/setenv.sh"
elif [ -r "$CATALINA_HOME/bin/setenv.sh" ]; then
  . "$CATALINA_HOME/bin/setenv.sh"
fi
//...
3.3 Create a setenv.sh manually, and put it into the ${tomcat-folder}\bin\ folder.
${tomcat-folder}\bin\setenv.sh
export JAVA_OPTS="-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m"
P.S With double quotes, export JAVA_OPTS=”{value}”.
3.4 Restart Tomcat.
Note
The heap size and non-heap size (perm gen) value is just an example, you should change the value accordingly to suit your project needs.
* Original post on mkyong.com

Tuesday, 31 March 2015

Basic Introduction Of Apache JMeter


What is JMeter ?

The Apache JMeterTM is pure Java open source software, which was first developed by Stefano Mazzocchi of the Apache Software Foundation, designed to load test functional behavior and measure performance. You can use JMeter to analyze and measure the performance of web application or variety of services. Performance testing means testing a web application against heavy load, multiple and concurrent user traffic. JMeter originally is used for testing Web Application or FTP application. Nowadays, it is used for functional test, database server test etc.

Why JMeter ?



  • Open source license: JMeter is totally free,  allows developer use the source code for the development
  • Friendly GUI: JMeter is extremely easy to use and doesn't take time to get familiar with it
  • Platform independent: JMeter is 100% pure Java desktop application. So it can run on multiple platforms
  • Full multi-threading framework. JMeter allows concurrent and simultaneous sampling of different functions by a separate thread group
  • Visualize Test Result: Test result can be display in a different format such as chart, table, tree and log file
  • Easy installation: You just copy and run the *.bat file to run JMeter. No installation needed.
  • Highly Extensible: You can write your own tests. JMeter also supports visualization plugins allow you extend your testing
  • Multiple testing strategy: JMeter supports many testing strategies such as Load Testing, Distributed Testing, and Functional Testing.
  • Simulation: JMeter can simulate multiple users with concurrent threads, create a heavy load against web application under test
  • Support multi-protocol: JMeter does not only support web application testing, but also evaluate database server performance. All basic protocols such as HTTP, JDBC, LDAP, SOAP, JMS, and FTP are supported by JMeter
  • Record & Playback Record the user activity on the browser and simulate them in  web application using JMeter
  • Script Test: Jmeter can be integrated with Bean Shell & Selenium for automated testing.

How does JMeter work ?

JMeter simulates a group of users sending requests to a target server, and return statistics information of target server through graphical diagrams

The completed workflow of JMeter as show in figure below


KEEP WATCHING FOR MORE TUTORIALS.

Thursday, 12 March 2015

Hibernate Issue – Initial SessionFactory Creation Failed.Java.Lang.NoClassDefFoundError: Org/Dom4j/DocumentException

A common Hibernate’s error, this is caused by the missing dependency library – dom4j.
Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/dom4j/DocumentException
Exception in thread "main" java.lang.ExceptionInInitializerError
 at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:18)
 at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8)
 at com.mkyong.common.App.main(App.java:17)
Caused by: java.lang.NoClassDefFoundError: org/dom4j/DocumentException
 at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
 ... 2 more
Caused by: java.lang.ClassNotFoundException: org.dom4j.DocumentException
 at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
 at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
 ... 3 more

Solution

You can download the library here – http://sourceforge.net/projects/dom4j/files/dom4j/
Or
Add the dependency in Maven’s pom.xml
       <dependency>
  <groupId>dom4j</groupId>
  <artifactId>dom4j</artifactId>
  <version>1.6.1</version>
 </dependency>

Hibernate Issue – An AnnotationConfiguration Instance Is Required To Use

The Hibernate annotation is required “AnnotationConfiguration” instead of normal “Configuration()” to build the session factory.
INFO: Configuration resource: /hibernate.cfg.xml
Initial SessionFactory creation failed.org.hibernate.MappingException: 
An AnnotationConfiguration instance is required to use <mapping class="com.mkyong.common.Stock"/>
Exception in thread "main" java.lang.ExceptionInInitializerError
 at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:19)
 at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8)
 at com.mkyong.common.App.main(App.java:11)
Caused by: org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="com.mkyong.common.Stock"/>
 at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1600)
 at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1555)
 at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1534)
 at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1508)
 at org.hibernate.cfg.Configuration.configure(Configuration.java:1428)
 at org.hibernate.cfg.Configuration.configure(Configuration.java:1414)
 at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
 ... 2 more

Solution

1. Download the Hibernate annotation library

You can download the library from Hibernate official website
Or
Add the dependency in Maven’s pom.xml
        <!-- Hibernate annotation -->
 <dependency>
  <groupId>hibernate-annotations</groupId>
  <artifactId>hibernate-annotations</artifactId>
  <version>3.3.0.GA</version>
 </dependency>
P.S You may need to include the JBoss repository in order to download the Hibernate annotation library.
<repositories>
    <repository>
      <id>JBoss repository</id>
      <url>http://repository.jboss.com/maven2/</url>
    </repository>
  </repositories>

2. Use AnnotationConfiguration to build session factory

Normal Hibernate XML file mapping is using Configuration()
          return new Configuration().configure().buildSessionFactory();
For Hibernate annotation, you have to change it to “AnnotationConfiguration”
          return new AnnotationConfiguration().configure().buildSessionFactory();
HibernateUtil.java
A full example of “HibernateUtil.java” of using “AnnotationConfiguration” for Hibernate annotation applacation.
package com.mkyong.persistence;
 
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
 
public class HibernateUtil {
 
    private static final SessionFactory sessionFactory = buildSessionFactory();
 
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new AnnotationConfiguration().configure().buildSessionFactory();
 
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
 
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
 
    public static void shutdown() {
     // Close caches and connection pools
     getSessionFactory().close();
    }
 
}

Hibernate Issue - Org.Hibernate.AnnotationException: Unknown Id.Generator

Problem

Runing the following Hibernate’s annotation sequence generator with PostgreSQL database.
        @Id 
 @Column(name="user_id", nullable=false) 
 @GeneratedValue(strategy = GenerationType.SEQUENCE ,generator="account_user_id_seq")
 private Integer userId;
Hits the following Unknown Id.generator exception.
Caused by: org.hibernate.AnnotationException: Unknown Id.generator: account_user_id_seq
 at org.hibernate.cfg.BinderHelper.makeIdGenerator(BinderHelper.java:413)
 at org.hibernate.cfg.AnnotationBinder.bindId(AnnotationBinder.java:1795)
 at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:1229)
 at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:733)
The sequence “account_user_id_seq” is created in PostgreSQL database, what caused the above exception?

Solution

When declaring the Hibernate’s annotation strategy to use “Sequences” as Id generator, try specify the @SequenceGenerator as well, as following
        @Id 
 @Column(name="user_id", nullable=false) 
 @SequenceGenerator(name="my_seq", sequenceName="account_user_id_seq")
 @GeneratedValue(strategy = GenerationType.SEQUENCE ,generator="my_seq")
 private Integer userId;

Hibernate Issue - Remember That Ordinal Parameters Are 1-Based!...

Problem

HibernateTemplate code …
getHibernateTemplate().find("from Domain d 
where d.domainName = :domainName", domainName);
When i execute the above code, i hit the following error message
java.lang.IndexOutOfBoundsException: Remember that ordinal parameters are 1-based!
 ...
 at org.hibernate.impl.AbstractQueryImpl.determineType(AbstractQueryImpl.java:397)
 at org.hibernate.impl.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:369)

Solution

I go inside and study HibernateTemplate.java file and find below code
public List find(final String queryString, final Object[] values) throws DataAccessException {
 return (List) executeWithNativeSession(new HibernateCallback() {
  public Object doInHibernate(Session session) throws HibernateException {
   Query queryObject = session.createQuery(queryString);
   prepareQuery(queryObject);
   if (values != null) {
    for (int i = 0; i < values.length; i++) {
     queryObject.setParameter(i, values[i]);
    }
   }
   return queryObject.list();
  }
 });
}
From code above, the HibernateTemplete is using 0-based instead of 1-based. Is this a spring or hibernate library problem? Since error message stated parameters need to start at 1-based. I tried some solution like change spring or hibernate library, however it’s not working…
It’s seem I’m on a wrong direction, i have to start finding solution at beginning again, first i study my own code…………!!! I cant imaging how careless i am, i made a stupid mistake on my code, this is not spring or hibernate problem, it is my syntax error.
Change from
getHibernateTemplate().find("
    from Domain d where d.domainName = :domainName", domainName);
To
getHibernateTemplate().find("
    from Domain d where d.domainName = ?", domainName);
Problem solved, code execute without error anymore.
Note
The error message generated by HibernateTemplate is really misleading !!!