Wednesday, 10 June 2015

How to convert Java object to / from JSON (Jackson)

Jackson is a High-performance JSON processor Java library. In this tutorial, we show you how to use Jackson’s data binding to convert Java object to / from JSON.
For object/json conversion, you need to know following two methods :
//1. Convert Java object to JSON format
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("c:\\user.json"), user);
//2. Convert JSON to Java object
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("c:\\user.json"), User.class);
Note
Both writeValue() and readValue() has many overloaded methods to support different type of inputs and outputs. Make sure check it out.

1. Jackson Dependency

Jackson contains 6 separate jars for different purpose, check here. In this case, you only need “jackson-mapper-asl” to handle the conversion, just declares following dependency in your pom.xml
  <repositories>
 <repository>
  <id>codehaus</id>
  <url>http://repository.codehaus.org/org/codehaus</url>
 </repository>
  </repositories>
 
  <dependencies>
 <dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-mapper-asl</artifactId>
  <version>1.8.5</version>
 </dependency>
  </dependencies>
For non-maven user, just get the Jackson library here.

2. POJO

An user object, initialized with some values. Later use Jackson to convert this object to / from JSON.
import java.util.ArrayList;
import java.util.List;
 
public class User {
 
 private int age = 29;
 private String name = "mkyong";
 private List<String> messages = new ArrayList<String>() {
  {
   add("msg 1");
   add("msg 2");
   add("msg 3");
  }
 };
 
 //getter and setter methods
 
 @Override
 public String toString() {
  return "User [age=" + age + ", name=" + name + ", " +
    "messages=" + messages + "]";
 }
}

3. Java Object to JSON

Convert an “user” object into JSON formatted string, and save it into a file “user.json“.
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
 
public class JacksonExample {
    public static void main(String[] args) {
 
 User user = new User();
 ObjectMapper mapper = new ObjectMapper();
 
 try {
 
  // convert user object to json string, and save to a file
  mapper.writeValue(new File("c:\\user.json"), user);
 
  // display to console
  System.out.println(mapper.writeValueAsString(user));
 
 } catch (JsonGenerationException e) {
 
  e.printStackTrace();
 
 } catch (JsonMappingException e) {
 
  e.printStackTrace();
 
 } catch (IOException e) {
 
  e.printStackTrace();
 
 }
 
  }
 
}
Output
{"age":29,"messages":["msg 1","msg 2","msg 3"],"name":"mkyong"}
Note
Above JSON output is hard to read. You can enhance it by enable the pretty print feature.

4. JSON to Java Object

Read JSON string from file “user.json“, and convert it back to Java object.
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
 
public class JacksonExample {
    public static void main(String[] args) {
 
 ObjectMapper mapper = new ObjectMapper();
 
 try {
 
  // read from file, convert it to user class
  User user = mapper.readValue(new File("c:\\user.json"), User.class);
 
  // display to console
  System.out.println(user);
 
 } catch (JsonGenerationException e) {
 
  e.printStackTrace();
 
 } catch (JsonMappingException e) {
 
  e.printStackTrace();
 
 } catch (IOException e) {
 
  e.printStackTrace();
 
 }
 
  }
 
}
User [age=29, name=mkyong, messages=[msg 1, msg 2, msg 3]]

Wednesday, 27 May 2015

Eclipse: Add the javax.servlet package to a project?

Some time in eclipse project we have exception in all the .java file where we use any servlet package this is because of we do not include servlet file in system jdk path.

To solve the error please follow bellow steps :

  1. Right click your project folder, select Properties at the bottom of the context menu.
  2. Select "Java Build Path"
  3. Click Libraries" tab
  4. Click "Add Library..." button on right (about halfway down)
  5. Select "Server Runtime" click "Next"
  6. Select your Tomcat version from the list
  7. Click Finish

KEEP READING FOR MORE POST

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