Wednesday, January 8, 2014

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


JSON Schema to Model Converter


JSON schema/Example to model converter
http://www.jsonschema2pojo.org/

This supports Jackson and Google gson JSON libraries.

JSON Viewer
http://jsonviewer.stack.hu/


Example: for my project JSON example
{
  "projectName":"TestProject",

  "properties": {
    "createdBy": "Kondal Kolipaka",
    "createdTime": "21-01-2013",
    "lastModifiedTime":"21-02-2013"
  }
}


Generated Model for above Project JSON example:

package com.kk;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("com.googlecode.jsonschema2pojo")
@JsonPropertyOrder({
"projectName",
"properties"
})
public class Project {

@JsonProperty("projectName")
private String projectName;
@JsonProperty("properties")
private Properties properties;
private Map<StringObject> additionalProperties = newHashMap<StringObject>();

@JsonProperty("projectName")
public String getProjectName() {
return projectName;
}

@JsonProperty("projectName")
public void setProjectName(String projectName) {
this.projectName = projectName;
}

@JsonProperty("properties")
public Properties getProperties() {
return properties;
}

@JsonProperty("properties")
public void setProperties(Properties properties) {
this.properties = properties;
}

@JsonAnyGetter
public Map<StringObject> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperties(String nameObject value) {
this.additionalProperties.put(namevalue);
}

}
-----------------------------------com.kk.Properties.java-----------------------------------

package com.kk;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("com.googlecode.jsonschema2pojo")
@JsonPropertyOrder({
"createdBy",
"createdTime",
"lastModifiedTime"
})
public class Properties {

@JsonProperty("createdBy")
private String createdBy;
@JsonProperty("createdTime")
private String createdTime;
@JsonProperty("lastModifiedTime")
private String lastModifiedTime;
private Map<StringObject> additionalProperties = newHashMap<StringObject>();

@JsonProperty("createdBy")
public String getCreatedBy() {
return createdBy;
}

@JsonProperty("createdBy")
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}

@JsonProperty("createdTime")
public String getCreatedTime() {
return createdTime;
}

@JsonProperty("createdTime")
public void setCreatedTime(String createdTime) {
this.createdTime = createdTime;
}

@JsonProperty("lastModifiedTime")
public String getLastModifiedTime() {
return lastModifiedTime;
}

@JsonProperty("lastModifiedTime")
public void setLastModifiedTime(String lastModifiedTime) {
this.lastModifiedTime = lastModifiedTime;
}

@JsonAnyGetter
public Map<StringObject> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperties(String nameObject value) {
this.additionalProperties.put(namevalue);
}

}

As we can see it also generates getAdditionalProperties(), this would be very much useful later point of time if we wanted to send some additional information without really modifying the existing structure.