Wednesday, January 22, 2014

Git: Changing a remote URL


https://help.github.com/articles/changing-a-remote-s-url

Example:

$ git remote -v
origin  ssh://core@1.2.3.197/data/kgit/explorer (fetch)

Currently origin is pointing to  ssh://core@1.2.3.197/data/kgit/explorer


Want to change my remote url to ssh://kondal.kolipaka@gerrit.mycompany.net:29418/explorer.git

$ git remote set-url origin ssh://kondal.kolipaka@gerrit.mycompany.net:29418/explorer.git


Check after change:

$ git remote -v

origin  ssh://kondal.kolipaka@gerrit.mycompany.net:29418/explorer.git (push)

Thursday, January 16, 2014

Java Type Erasure: Cannot perform instanceof check against parameterized type

Can we use something like this ?

public Object[] getElements(Object inputElement) {
if (inputElement instanceof List<Parameter>) {
return ((List<Parameter>) inputElement).toArray();
}
return new Object[] {};
}

No!!!!

Compiler Error message:
Cannot perform instanceof check against parameterized type List<Parameter>. Use the form List<?> instead since further generic type information will be erased at runtime


It's telling us to use List<?> more generic type rather than specific List<Parameter>.

public Object[] getElements(Object inputElement) {
if (inputElement instanceof List<?>) {
return ((List<?>) inputElement).toArray();
}
return new Object[] {};
}


Why?

In simple terms, generic types will be erased at compile time. During the type erasure process, the Java compiler erases all type parameters and replaces each with its first bound if the type parameter is bounded, or Object if the type parameter is unbounded.

It means, the .class file or generated byte code will not have any generic type information.


Below is the code after applying type erasure by compiler.

public Object[] getElements(Object inputElement) {
if (inputElement instanceof List) {
return ((List) inputElement).toArray();
}
return new Object[] {};
}


Other example from SUN docs:

public class Node<T> {

    private T data;
    private Node<T> next;

    public Node(T data, Node<T> next) }
        this.data = data;
        this.next = next;
    }

    public T getData() { return data; }
    // ...
}

Because the type parameter T is unbounded, the Java compiler replaces it with Object:

public class Node {

    private Object data;
    private Node next;

    public Node(Object data, Node next) {
        this.data = data;
        this.next = next;
    }

    public Object getData() { return data; }
    // ...
}


In the following example, the generic Node class uses a bounded type parameter:

public class Node<T extends Comparable<T>> {

    private T data;
    private Node<T> next;

    public Node(T data, Node<T> next) {
        this.data = data;
        this.next = next;
    }

    public T getData() { return data; }
    // ...
}
The Java compiler replaces the bounded type parameter T with the first bound class, Comparable:

public class Node {

    private Comparable data;
    private Node next;

    public Node(Comparable data, Node next) {
        this.data = data;
        this.next = next;
    }

    public Comparable getData() { return data; }
    // ...
}


Resources:
http://docs.oracle.com/javase/tutorial/java/generics/erasure.html

Change Eclipse theme

I am working with eclipse 4.4(Luna), someway I don't like the eclipse new theme!! might be I was so used to the old classic theme.

Eclipse provides the option to change through Preferences.

Window->Preferences->General->Appearance

In Theme drown-down list you can find 'classic' theme, Select and click on 'Apply'. You are done!




Eclipse Error: An API baseline has not been set for the current workspace.

I was getting this error, when I imported eclipse JSDT source code which i have cloned into eclipse workspace.

To resolve this issue, modify the Eclipse workspace preferences.

Windows > Preferences > Plug-in Development > API Baselines > Options > Missing API baseline
Then, change "Error" to "Ignore" in the drop down list.






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


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.