Monday, January 13, 2014

Annotations for Ignoring properties In JSON - Jackson

For my reference....

Sometimes POJOs contain properties that you do not want to write out, so you can do:

public class Value {
  public int value;
  @JsonIgnore public int internalValue;
}
and get JSON like:
{ "value" : 42 }

or, you may get properties in JSON that you just want to skip: if so, you can use:

@JsonIgnoreProperties({ "extra", "uselessValue" })
public class Value {
  public int value;
}
which would be able to handle JSON like:
{ "value" : 42, "extra" : "fluffy", "uselessValue" : -13 }

Finally, you may even want to just ignore any "extra" properties from JSON (ones for which there is no counterpart in POJO). This can be done by adding:

@JsonIgnoreProperties(ignoreUnknown=true)
public class PojoWithAny {
  public int value;
}

Reference:
http://jackson.codehaus.org/

Thursday, January 9, 2014

java.lang.OutOfMemoryError: PermGen space with eclipse

By default, Eclipse comes with below PermGen configuration in eclipse.ini file.
--launcher.XXMaxPermSize
256m

But this is not working with some versions. As per eclipse bug, this is not working with Java 1.6_21, but I was facing this issue even in Java 1.6_32 as well.

Anyway,add below parameter in eclipse.ini as a vm argument to resolve the issue.
-XX:MaxPermSize=256M

Even after this, if your eclipse is crashing with PermGen space issue, then try to increase the size.
I would say 512M is a very big size for PermGen space, If some application is taking more than that means, it's a real application issue, developers need to analyze where it's taking so much of space.

Resources:
http://wiki.eclipse.org/FAQ_How_do_I_increase_the_permgen_size_available_to_Eclipse%3F
https://bugs.eclipse.org/bugs/show_bug.cgi?id=319514 

Wednesday, January 8, 2014

Getting Eclipse Workspace file system path

ResourcePlugin is a starting point for workspace initialization. This will hold the all required information about the workspace.

IWorkspace workspace = ResourcesPlugin.getWorkspace();

//Local file system
IPath file = workspace.getRoot().getLocation();

Output path:
D:\Work\KKWorkspaces\runtime-New_configuration


//Remote location 
URI locationURI = workspace.getRoot().getLocationURI();

OutputPath:
file:/D:/Work/KKWorkspaces/runtime-New_configuration

Converting map to JSON String using Jackson API


API libraries can found here @ http://jackson.codehaus.org/

Example:

import java.util.ArrayList;
import java.util.HashMap;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class MapToJSONExample {

public static void main(String[] args) {
               
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("param1", "Hyderabad");
hashMap.put("param2", "Bangalore");

ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("hello1");
arrayList.add("hello2");
arrayList.add("hello3");

Employee employee = new Employee("Kondal", "Kolipaka");

ObjectMapper mapper = new ObjectMapper();
String writeValueAsString;
try {
writeValueAsString = mapper.writeValueAsString(hashMap);
System.out.println(writeValueAsString);

writeValueAsString = mapper.writeValueAsString(arrayList);
System.out.println(writeValueAsString);

writeValueAsString = mapper.writeValueAsString(employee);
System.out.println(writeValueAsString);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}


public class Employee {

private String firstName;
private String lastName;

public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}

/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}

}

Output:
{"param1":"Hyderabad","param2":"Bangalore"}
["hello1","hello2","hello3"]
{"firstName":"Kondal","lastName":"Kolipaka"}


Just to conclude, we can use writeValueAsString(Object obj) method for any bean class which can be serializable.

Say for example, if you remove getters from Employee class, it will be throwing JsonMappingException.

No serializer found for class Employee and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.SerializationFeature.FAIL_ON_EMPTY_BEANS) )

Monday, January 6, 2014

java.lang.IllegalStateException: "Workbench has not been created yet"

As an end user, if you are facing this issue. Please try out the following options.

1. Try to open eclipse in clean mode and select a new workspace.
  eg: eclipse -clean

2. Try to delete workspace .metadata folder and open in clean mode. In this case, you will lose workspace preferences and projects, you need to re-import them.


As an eclipse developer, we need to understand more about this issue to provide a solution.

When do we get this issue ?

If your plug-in is trying to access PlatformUI.getWorkbench() before workbench is created fully.

Example: This is my code in the MyActivator.start()


Display.getDefault().syncExec(new Runnable() {
          @Override
          public void run() {
                                                                                PlatformUI.getWorkbench().getActiveWorkbenchWindow().addPerspectiveListener(pHandler);
                                         }
                                           });


As a result of this, I might face java.lang.IllegalStateException: "Workbench has not been created yet" error.

If we look at the implementation of a workbench class.

  /**
     * Returns the workbench. Fails if the workbench has not been created yet.
     *
     * @return the workbench
     */
    public static IWorkbench getWorkbench() {
        if (Workbench.getInstance() == null) {
            // app forgot to call createAndRunWorkbench beforehand
            throw new IllegalStateException(WorkbenchMessages.PlatformUI_NoWorkbench);  //here it’s throwing exception
        }
        return Workbench.getInstance();
    }


So how do we address this issue then ?

Let’s try out this.

while(!PlatformUI.isWorkbenchRunning() ) { //If workbench is not running keep checking for it.
                               
}

//Do your actual work here


But there is a problem with it, as per the Eclipse workbench documentation, Note that this method may return true while the workbench is still being initialized, so it may not be safe to call workbench API methods even if this method returns true.

That means, even though workbench is not fully initialized it will return true, that is something which we don't want.

How do I stop activator.start() execution until workbench is fully created ?

Below is the way which was discussed @ https://bugs.eclipse.org/bugs/show_bug.cgi?id=49316

 public class WorkbenchState implements IStartup
  {
    private static boolean started = false;
    public void earlyStartup ()
    {
        Display.getDefault ().asyncExec (new Runnable ()
        {
            public void run ()
            {
                started = true;
            }
        });
    }
   
    public static boolean isStarted ()
    {
        return started;
    }
  }


Now, in my MyActivator.start(), I will try to invoke in the following way.

While (WorkbenchState.isStarted()) {
   //do your actual work here
}


As we can understand one thing from above code is, IStartup earlyStartup () will be invoked after workbench is initialized completely.

Above approach suits for standard eclipse plug-ins, if you guys are developing Eclipse RCP. You can do the following.

WorkbenchAdvisor has a postStartup() method, this will be invoked only after workbench is initialized completely.

Example:

MyApplicationWorkbenchAdvisor extends WorkbenchAdvisor
{
    public static isStarted = false;
      public void postStartup() {
                                isStarted = true;
                }
               
 public static boolean isStarted ()
    {
        return isStarted;
    }

}


//In your plug-in access in the following way.
While (MyApplicationWorkbenchAdvisor.isStarted()) {
   //do your actual work here

}


OSGI and start levels

Eclipse Plug-in start levels are there to simply determine the start order of bundles.
But as a developer or end user, we should never treat or code based on the order of OSGI start levels, it's completely managed by OSGI framework.

At least as of now, I have never come across the situation where I need to modify the plugin start level to launch an eclipse or develop Eclipse RCP Applications.

References:
http://eclipsesource.com/blogs/2009/06/10/osgi-and-start-levels/

http://aaronz-sakai.blogspot.in/2009/05/osgi-system-and-bundle-start-levels.html

http://www.osgi.org/download/r4v41/r4.core.pdf

http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fruntime-options.html

From eclipse run time options:
The start-level indicates the OSGi start level at which the bundle should run. If the start-level (>0 integer) is omitted then the framework will use the default start level for the bundle.

If they do not specify a startlevel then they default to the value of osgi.bundles.defaultStartLevel. The default value of osgi.bundles.defaultStartLevel is 4

Friday, January 3, 2014

Reading an icon from icons folder in eclipse plugin project

 To access an icon from your plugin project /icons folder, you can use below code.

 Image addImage = AbstractUIPlugin.imageDescriptorFromPlugin(MyPluginActivator.PLUGIN_ID,"$nl$/icons/add.gif").createImage();


MyPluginProject
 --src
 --icons
    -add.gif