Wednesday, July 15, 2009

Eclipse RCP : Single instance of RCP Application

There are methods of maintaining a single instance of an application. Most often the application creates a lock file and holds on to it during the lifecycle of the application.

A new instance of the application will try to find this file and if it exists, the application will try to show the existing instance to the user, preventing from creating whole new instance of the application. One drawback of this approach will be if the application crashes leaving the lock file. The user has to manually delete the file (or application can try deleting this file )
The same can be achieved via opening a server socket when the application is opened. Now how do we do it for a simple RCP Application.



/*
* (non-Javadoc)
* @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
*/
public Object start(final IApplicationContext context)
{
if (!checkServerPort())
{
try
{
final ServerSocket server = new ServerSocket(5000);

serverThread = new Thread(new Runnable()
{
@Override
public void run()
{
boolean socketClosed = false;
while (!socketClosed)
{
if (server.isClosed())
{
socketClosed = true;
}
else
{
try
{
Socket client = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(client
.getInputStream()));
new UIJob("Reopening the app...")
{
@Override
public IStatus runInUIThread(IProgressMonitor monitor)
{
advisor.getWindowAdvisor().handleEvent(null);
return null;
}
}.schedule();

/**
* if (SINGLE_INSTANCE_SHARED_KEY.trim().equals(message.trim())) {
* System.out.println("Receiving message"); }
*/
in.close();
client.close();
}
catch (IOException ex)
{
socketClosed = false;
}
}
}
}
});
serverThread.start();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
else
{
try
{
Socket clientSocket = new Socket(InetAddress.getLocalHost(), 5000);
OutputStream out = clientSocket.getOutputStream();
out.write(SINGLE_INSTANCE_SHARED_KEY.getBytes());
out.close();
clientSocket.close();
}
catch (UnknownHostException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
return IApplication.EXIT_OK;
}
final Display display = PlatformUI.createDisplay();
try
{

final int returnCode = PlatformUI.createAndRunWorkbench(display, advisor);
if (returnCode == PlatformUI.RETURN_RESTART)
{
return IApplication.EXIT_RESTART;
}
return IApplication.EXIT_OK;
}
finally
{
display.dispose();
}
}

private boolean checkServerPort()
{
try
{
new Socket("localhost", 5000);
}
catch (IOException ex)
{
return false;
}
return true;
}

/*
* (non-Javadoc)
* @see org.eclipse.equinox.app.IApplication#stop()
*/
public void stop()
{
final IWorkbench workbench = PlatformUI.getWorkbench();
if (workbench == null)
{
return;
}
final Display display = workbench.getDisplay();
display.syncExec(new Runnable()
{
public void run()
{
if (!display.isDisposed())
{
workbench.close();
}
}
});
}



Now when the application is launched for the first time, it will open a server socket 5000 and will start listening on it. The next instance of the application will check the server port and if it is used already, it will create a client for that server socket and send a message to the server.

When the server receives any message from the client, it will reopen the instance which created the server socket.

The handleEvent method on the WorkbenchWindowAdvisor will have to have the following code..


/*
* (non-Javadoc)
* @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
*/
@Override
public void handleEvent(Event event)
{
Shell workbenchWindowShell = getWindowConfigurer().getWindow().getShell();
workbenchWindowShell.setVisible(true);
workbenchWindowShell.setActive();
workbenchWindowShell.setFocus();
workbenchWindowShell.setMinimized(false);
}


Now enjoy the single instance of the RCP application. This approach can be used for any java application.

Friday, July 10, 2009

Eclipse RCP : Redirecting eclipse errors to log4j

Its sometimes tedious to find the real exception occured when using an eclipse based application. Since it goes under the workspace/.metadata/.log file. It takes a while to figure this out. But most of the desktop application do write to a log file of its own. So when using eclipse using two log files to know about the application is kind of not nice.

But still eclipse provides a way to listen to the log messages of its own. So if the application uses its own logging , it can listen to the eclipse log and add it to its own logger. Here we will look at connecting eclipse log messages to the log4j logger.

Eclipse Platform provides a method to add listeners Platform.addLogListener(ILogListener);

So how do we add the listener to the Platform. In the Activator of the application plugin's start method, add the following.


public class Activator extends AbstractUIPlugin {

private ILogListener listener;


@Override
public void start(final BundleContext context) throws Exception {
super.start(context);
plugin = this;
listener = new Listener();
Platform.addLogListener(listener);
}

@Override
public void stop(final BundleContext context) throws Exception {
Platform.removeLogListener(listener);
listener = null;
plugin = null;
super.stop(context);
}

}


Now every error/warning eclipse logs to its .log file under .metadata directory will be sent to the log listener. How does the log listener handle the events from the eclipse?


package com.logging;
public class Listener implements ILogListener {
private static final Logger LOGGER = Logger.getLogger(Listener.class.getName());

@Override
public void logging(final IStatus status, final String plugin) {
if (status.getSeverity() == IStatus.WARNING) {
if (status.getException() == null) {
LOGGER.warn(status.getMessage());
} else {
LOGGER.warn(status.getMessage() + status.getException());
}
} else if (status.getSeverity() == IStatus.ERROR) {
if (status.getException() == null) {
LOGGER.error(status.getMessage());
} else {
LOGGER.error(status.getMessage()+status.getException());
}
}
}
}


Now all the eclipse errors and warnings will go to the logger which is configured for Listener.class.getName().

To get all the log messages from the eclipse. the log4j.properties

log4j.category.com.logging.Listener=all

This will log all the errors and warnings from the eclipse application to the log4j's log file or console as configured.

Monday, July 6, 2009

Eclipse RAP : Custom Widget development

It took a while to understand and create a custom widget but finally i could do it. I wanted to create a custom widget to draw sequence of svg graphics. I followed the Custom widget development at the RAP help site. It helped me to get a good start but since i was trying to do SVG it didnt really work at my first attempt..(i know... nothing works at the first attempt).

The SVG support i wanted to create was something like below.

video

Here is what i did to create a custom widget.

1. Create a new plugin project and name it like com.xyz.project.mywidget
This is not mandatory but its good to call the plugin as the widget name.

2. Create a package com.xyz.project.mywidget
This package will contain the server side, client side and API resource classes. Just follow as explained in the RAP help.

3. Create the server side Widget class , i wanted a widget to send events to the server and also behave as a selection provider when a image is clicked. So i extended SWT Composite and implemented ISelectionProvider.


public class MyWidget extends Composite implements ISelectionProvider {

/**
* for showing multiple images on the widget
*/
private String[] images;

/**
* To get the selection back from the client.
*/
int selectionIndex;

/**
* Listeners
*/
private ListenerList listeners = new ListenerList();

/**
* Selection.
*/
private ISelection selection;

private String selectedImage;

public MyWidget(Composite parent) {
super(parent, SWT.NONE);
}

public String[] getImages() {
return images;
}

public void setImages(String[] parts) {
this.images = parts;
}

@Override
public void setLayout(Layout layout) {
super.setLayout(new FillLayout());
}

public String getSelectedImage() {
return selectedImage;
}

public void setSelectedImage(String selectedPart) {
this.selectedImage = selectedPart;
if (selectedPart != null) {
selectionIndex = Integer.parseInt(selectedPart);
setSelection(new StructuredSelection(images[selectionIndex / 2]));
}
}

public void addSelectionChangedListener(ISelectionChangedListener listener) {
listeners.add(listener);
}

public ISelection getSelection() {
return selection;
}

public void removeSelectionChangedListener(
ISelectionChangedListener listener) {
listeners.remove(listener);
}

public void setSelection(ISelection selection) {
this.selection = selection;
Object[] list = listeners.getListeners();
for (int i = 0; i < list.length; i++) {
((ISelectionChangedListener) list[i])
.selectionChanged(new SelectionChangedEvent(this, selection));
}
}
}



Follow this post for how to implement ISelectionProvider - http://random-eclipse-tips.blogspot.com/2009/02/eclipse-how-to-implement.html

Now that the server side, widget is ready, we need the client side widget code, the qooxdoo javascript code. Read the qooxdoo explanation in RAP custom widget tutorial and follow it, it gives you a basic idea of what to do.


    qx.Class.define( "com.xyz.project.MyWidget", {
extend: qx.ui.layout.CanvasLayout,

construct: function( id ) {
this.base( arguments );
this.setHtmlAttribute("id",id);
this._id = id;
},

properties : {
images : {
init : "",
apply : "load"
},

members : {
load : function() {
var current = this.getParts()[0];
if( current != null && current != "" ) {
qx.ui.core.Widget.flushGlobalQueues();
var id = document.getElementById( this._id );
var wm = org.eclipse.swt.WidgetManager.getInstance();
var designWidgetId = wm.findIdByWidget( this);
var newParts = this.getParts();
var current = null;
var image = 1;
if(this.__paper == null ) {
this.__paper = Raphael(id, newParts.length*100, 480);
startx = 10;
starty = 10;
width = 100;
height=25;
curve=10;
var part=0, colorhue = .6 || Math.random(),
color = "hsb(" + [colorhue, 1, .75] + ")";
var selectionColor = "#d54";
var currentSelection = null;
var detail = this.__paper.rect(startx, starty+height+5, 200, 100, 5).attr({fill: "#d54" , stroke: "#474", "stroke-width": 2}).hide();
label0 = this.__paper.text(startx+20,starty+height+10,"ID : ").hide();
label1 = this.__paper.text(startx+20,starty+height+25,"Other : ").hide();
for (part=0;part<newParts.length;part++)
{
(function(paper,part,type){
var c = "#ccc";
if(image==0) {
if(type == "image1") {
paper.image("./Part_icon_image1.png", startx, starty, width, height);
}else if(type == "image2") {
image("./Part_icon_image2.png", startx, starty, width, height);
}
}
var label = paper.text(startx+25,starty+10,part).hide();
paper.rect(startx,starty,width,height,curve).attr({stroke: c, fill: c, "fill-opacity": .4}).
mouseover(
function(){
this.animate({"fill-opacity": .75}, 500);
detail.show().animate({x: 10+(width*part), y: starty+height+5}, 200 );
label0.attr({text: "ID : "+newParts[part]}).show().animate({x: 40+(width*part), y: starty+height+10}, 200);
label1.attr({text: "Other : "}).show().animate({x: 40+(width*part), y: starty+height+25}, 200);
paper.safari();
}).
mouseout(
function(){
this.animate({"fill-opacity": .25}, 500);
detail.hide();
label0.hide();
label1.hide();
paper.safari();
}).
click(
function(){
if(currentSelection != null ) {
currentSelection.attr({fill:c});
}
currentSelection = this;
currentSelection.attr({fill:selectionColor});
var req = org.eclipse.swt.Request.getInstance();
req.addParameter( designWidgetId +".selectedImage", part );
req.send();
});
})(this.__paper,part,newParts[part]);
startx+=width;
}
}}

},
}
});


Now that, whenever the setImages method is called on the server side widget, the client has to update the browser. But how does it interact, the server side widget and the client side widget get connected through two main classes, the API resource class and the LCA class. There are different ways of defining the LCA class but here i would just follow the simple approach as explained in the RAP help.

First to create the API resource, we need to create a IResource implementation , In our case, MyWidgetResource as follows,


public class DesignWidgetResource implements IResource {
public String getCharset() {
return HTML.CHARSET_NAME_ISO_8859_1;
}

public ClassLoader getLoader() {
return this.getClass().getClassLoader();
}

public RegisterOptions getOptions() {
return RegisterOptions.VERSION_AND_COMPRESS;
}

public String getLocation() {
return "com/xyz/project/mywidget/MyWidget.js";
}

public boolean isJSLibrary() {
return true;
}

public boolean isExternal() {
return false;
}
}

you can just copy and paste the above code and replace the getLocation method to your .js file. Now the LCA, this can either be written in a pre defined package or can be done using getAdapter method in the widget class. I will follow the pre defined package which com.xyz.project.mywidget.internal.mywidgetkit and create MyWidgetLCA.java




public class MyWidgetLCA extends AbstractWidgetLCA {

private static final String PARAM_SELECTED = "selectedImage";

private static final String PROP_IMAGES = "images";

private static final String JS_PROP_IMAGE = "images";

public void preserveValues(final Widget widget) {
ControlLCAUtil.preserveValues((Control) widget);
IWidgetAdapter adapter = WidgetUtil.getAdapter(widget);
adapter.preserve(PROP_IMAGES, ((MyWidget) widget).getImages());
// adapter.preserve(PROP_MOVE_RIGHT, ((DesignWidget) widget)
// .getMoveRight());
// only needed for custom variants (theming)
WidgetLCAUtil.preserveCustomVariant(widget);
}

/*
* Read the parameters transfered from the client
*/
public void readData(final Widget widget) {
MyWidget myWidget = (MyWidget) widget;
String location = WidgetLCAUtil.readPropertyValue(myWidget,
PARAM_SELECTED);
myWidget.setSelectedImage(location);
}

/*
* Initial creation procedure of the widget
*/
public void renderInitialization(final Widget widget) throws IOException {
JSWriter writer = JSWriter.getWriterFor(widget);
String id = WidgetUtil.getId(widget);
writer.newWidget("com.xyz.project.mywidget.MyWidget",
new Object[] { id });
writer.set("appearance", "composite");
writer.set("overflow", "hidden");
ControlLCAUtil.writeStyleFlags((MyWidget) widget);
}

public void renderChanges(final Widget widget) throws IOException {
MyWidget gmap = (MyWidget) widget;
ControlLCAUtil.writeChanges(gmap);
JSWriter writer = JSWriter.getWriterFor(widget);
writer.set(PROP_IMAGES, JS_PROP_IMAGE, gmap.getImages());
// only needed for custom variants (theming)
WidgetLCAUtil.writeCustomVariant(widget);
}

public void renderDispose(final Widget widget) throws IOException {
JSWriter writer = JSWriter.getWriterFor(widget);
writer.dispose();
}

public void createResetHandlerCalls(String typePoolId) throws IOException {
}

public String getTypePoolId(Widget widget) {
return null;
}

}


Here, the LCA class is the important class which communicates between the server code and client script. The selection on the client sends an event to the server through the LCA in the readData method. The client code will use org.eclipse.swt.Request.getInstance() to send the request to the server when an image is clicked on the Widget.

Now we got the both the resource and LCA ready. we need to create an resources extension point and add the MyWidgetResource classes.
   <extension
point="org.eclipse.rap.ui.resources">
<resource
class="com.xyz.project.mywidget.MyWidgetResource">
</resource>
</extension>


ok..we have a basic setup ready, what is the Raphael stuff on the Qooxdoo javascript. Raphael is a Javascript based SVG library which helps creating different SVG based graphics. For more details on that visit http://raphaeljs.com/. The demos explain a lot about the library. How do we add an external javascript resource into the myWidget implementation.

1. Create a RaphaelAPIResource similar to the one we created for MyWidget as MyWidgetResource.

public class RaphaelAPIResource implements IResource {

private String location;

public String getCharset() {
return HTML.CHARSET_NAME_ISO_8859_1;
}

public ClassLoader getLoader() {
return this.getClass().getClassLoader();
}

public String getLocation() {
location = "http://raphaeljs.com/raphael.js";
return location;
}

public RegisterOptions getOptions() {
return RegisterOptions.VERSION;
}

public boolean isExternal() {
return true;
}

public boolean isJSLibrary() {
return true;
}

}


and add the resources extension to the existing extension point we used as following.
   <extension
point="org.eclipse.rap.ui.resources">
<resource
class="com.biologistics.gd.design.RaphaelAPIResource">
</resource>
<resource
class="com.biologistics.gd.design.DesignWidgetResource">
</resource>
</extension>


Since we are displaying images on the client side , we need the images also as resources sent to the client. we have to create http.registryresources to use aliases for the images. In this case, we are referring to Part_icon_image1.png and Part_icon_image2.png as alias in the javascript.

 <extension
point="org.eclipse.equinox.http.registry.resources">
<resource
alias="/Part_icon_image1.png"
base-name="branding/Part_icon_image1.png">
</resource>
<resource
alias="/Part_icon_image2.png"
base-name="original/Part_icon_image2.png">
</resource>
</extension>


Now we can create a view with MyWidget as a child and setImages on that.

 public void createPartControl(final Composite parent) {
widget = new MyWidget(parent);
widget.setParts(new String[]{"image1","image2"});
getSite().setSelectionProvider(widget);
}


Will be glad to help !

Thursday, March 5, 2009

Quick Tips: Storing preferences and settings per user in a RCP application

Eclipse RCP applications store the prefrences and settings in the workspace. When a RCP application is exported, the workspace is opened within the application folder unless the workspace location is overridden. This will make every user who uses the application to use the same preferences. To enable the preferences and workbench state to be user specific, the default location of the workspace can be configured in the config.ini file as follows.


osgi.instance.area.default=@user.home/eclipseworkspace


Now the preferences and other dialog settings will be written in the user's own workspaces.

Quick Tip: Save and Restore the perspective layout

To restore the perspctive to the last modified state, eclipse stores the workbench state to a file called workbench.xml. To enable the save and restore layout, the IWorkbenchConfigurer must be set in the ApplicationWorkbenchAdvisor.


public void initialize(IWindowConfigurer configurer)
{
configurer.setSaveAndRestore(true);
}

Monday, March 2, 2009

Eclipse : Writing to the console in a RCP Application

When you want to add console message to the eclipse console view, there is no easiest way to do this. The sysout/syserr messages will go on the console where you have the application if you run it with -consoleLog option.

How do we show the messages on the console view eclipse provides. First of all we have to add the console view to the perspective. The console view is part of the org.eclipse.ui.console plugin, so add it to the dependencies if you dont have it already.

Now add the ConsoleView to the perspective in the createInitialLayout method ( the following snippet is written with the RCP Mail example )


public void createInitialLayout(IPageLayout layout) {
String editorArea = layout.getEditorArea();
layout.setEditorAreaVisible(false);

layout.addStandaloneView(NavigationView.ID, false, IPageLayout.LEFT,
0.25f, editorArea);
IFolderLayout folder = layout.createFolder("messages", IPageLayout.TOP,
0.5f, editorArea);
folder.addPlaceholder(View.ID + ":*");
folder.addView(View.ID);

IFolderLayout consoleFolder = layout.createFolder("console",
IPageLayout.BOTTOM, 0.65f, "messages");
consoleFolder.addView(IConsoleConstants.ID_CONSOLE_VIEW);
layout.getViewLayout(NavigationView.ID).setCloseable(false);
}


Now if you run the application you can see the console view at the bottom of the Messages view of the RCP Mail application. But now there are no open consoles on the console view. Now let us take an example, whenever a Messages view is opened we want to write something to the console.


public class OpenViewAction extends Action {

private final IWorkbenchWindow window;
private int instanceNum = 0;
private final String viewId;
MessageConsole messageConsole;

public OpenViewAction(IWorkbenchWindow window, String label, String viewId) {
this.window = window;
this.viewId = viewId;
setText(label);
// The id is used to refer to the action in a menu or toolbar
setId(ICommandIds.CMD_OPEN);
// Associate the action with a pre-defined command, to allow key
// bindings.
setActionDefinitionId(ICommandIds.CMD_OPEN);
setImageDescriptor(com.blog.sample.Activator
.getImageDescriptor("/icons/sample2.gif"));

}

public void run() {
if (window != null) {
try {
int instance = instanceNum++;
window.getActivePage().showView(viewId,
Integer.toString(instance),
IWorkbenchPage.VIEW_ACTIVATE);

messageConsole = getMessageConsole();
MessageConsoleStream msgConsoleStream = messageConsole
.newMessageStream();

ConsolePlugin.getDefault().getConsoleManager().addConsoles(
new IConsole[] { messageConsole });

msgConsoleStream.println(viewId + Integer.toString(instance));

} catch (PartInitException e) {
MessageDialog.openError(window.getShell(), "Error",
"Error opening view:" + e.getMessage());
}
}
}

private MessageConsole getMessageConsole() {
if (messageConsole == null) {
messageConsole = new MessageConsole("RCPMail", null);
ConsolePlugin.getDefault().getConsoleManager().addConsoles(
new IConsole[] { messageConsole });
}

return messageConsole;
}

}


Now every new view opened will write the ViewID to the RCPMail console we created.

Have fun!

Thursday, February 26, 2009

Quick Tip : Adding SWT controls to the Trim Area

Sometimes RCP applications needs to show a label or some swt control on the trim area (outer boundary of the workbench window ) for example in the status area, after the perspective switch bar area and so on.

org.eclipse.ui.menus extension point allows to places command or control on the toolbar , menubar or on the trim area. For this post, if you want to add a control or command to the status area or the perspective switch area, use the following locationURI.

For placing it on the status area - toolbar:org.eclipse.ui.trim.status this will place the control or command on the status area. ( You have to make sure the status area is made visible in the workbenchwindowadvisors preWindowOpen() method as


public void preWindowOpen() {
IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
configurer.setInitialSize(new Point(600, 400));
configurer.setShowCoolBar(true);
configurer.setShowPerspectiveBar(true);
configurer.setShowStatusLine(true);
}


For placing it on the perspective switch area - toolbar:org.eclipse.ui.trim.command2, this will add the control next to the perspective switch area.

The extension point should create a menuContribution with the correct locationURI, and add the controls/commands to a toolbar.


<extension
point="org.eclipse.ui.menus">
<menuContribution
locationURI="toolbar:org.eclipse.ui.trim.command2">
<toolbar
id="com.blog.sample.toolbar1">
<control
class="com.blog.sample.WorkbenchWindowControlContribution1">
</control>
</toolbar>
</menuContribution>
</extension>


Have fun !

Tuesday, February 24, 2009

Eclipse : Minimizing the RCP App to the system tray.

ApplicationWorkbenchWindowAdvisor of the RCP application can handle preWindowShellClose() and postWindowClose(). If you want the application to be stored to the system tray when closed, the preWindowClose event can be handled as below to add a system tray icon with Open and Exit actions which will open/exit the workbench.


@Override
public boolean preWindowShellClose() {
final TrayItem item = new TrayItem(
Display.getCurrent().getSystemTray(), SWT.NONE);
final Image image = Activator.getImageDescriptor("icons/mail.ico")
.createImage();
item.setImage(image);
item.setToolTipText("RCPMail - Tray Icon");
getWindowConfigurer().getWindow().getShell().setVisible(false);
item.addSelectionListener(new SelectionAdapter() {
public void widgetDefaultSelected(SelectionEvent e) {
Shell workbenchWindowShell = getWindowConfigurer().getWindow()
.getShell();
workbenchWindowShell.setVisible(true);
workbenchWindowShell.setActive();
workbenchWindowShell.setFocus();
workbenchWindowShell.setMinimized(false);
image.dispose();
item.dispose();
}
});

Shell workbenchWindowShell = getWindowConfigurer().getWindow()
.getShell();
// Create a Menu
final Menu menu = new Menu(workbenchWindowShell, SWT.POP_UP);
// Create the exit menu item.
final MenuItem exit = new MenuItem(menu, SWT.PUSH);
exit.setText("Exit");

// Create the open menu item.
final MenuItem open = new MenuItem(menu, SWT.PUSH);
open.setText("Open");
// make the workbench visible in the event handler for exit menu item.
open.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
// Do a workbench close in the event handler for exit menu item.
exit.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
image.dispose();
item.dispose();
open.dispose();
exit.dispose();
menu.dispose();
getWindowConfigurer().getWorkbenchConfigurer().getWorkbench()
.close();
}
}); Shell workbenchWindowShell = getWindowConfigurer().getWindow()
.getShell();
workbenchWindowShell.setVisible(true);
workbenchWindowShell.setActive();
workbenchWindowShell.setFocus();
workbenchWindowShell.setMinimized(false);
image.dispose();
item.dispose();
open.dispose();
exit.dispose();
menu.dispose();
}
});
item.addListener(SWT.MenuDetect, new Listener() {
public void handleEvent(Event event) {
menu.setVisible(true);
}
});
// Do a workbench close in the event handler for exit menu item.
exit.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
image.dispose();
item.dispose();
open.dispose();
exit.dispose();
menu.dispose();
getWindowConfigurer().getWorkbenchConfigurer().getWorkbench()
.close();
}
});
return false;
}

Equinox : Authenticate with Database Login using Equinox Security

Most of the desktop applications require a authentication step when the application is started. Eclipse does not yet provide a login mechanism to authenticate the user. But the equinox security has it on the proposal to support login dialog based authentication. Till then, what would be the best way to do the authentication with existing equinox security features. Lets have a look at RCP Mail Template with a login dialog during start up.

Equinox implements the standard Java Authentication and Authorization Service ( JAAS ) to authenticate and authorize. We will look at some realtime examples of how to do the authentication.

Equinox supports extension login modules which can be configured via the loginmodule extension. The extension can be configured with nt login module, LDAP login modules from the sun security modules or can be configured with custom written LoginModules like RDBMSLoginModule, SecureStorage Logins and so on.

The example from the org.eclipse.equinox.security.sample from the equinox cvs (org.eclipse.equinox/incubator/security/bundles/org.eclipse.equinox.security.sample ) /cvsroot/rt explains adding LDAP, WIN32 and other login modules to the application. Here in this example we will write a custom LoginModule which authenticates against a database connection.

RDBMSLoginModule - The login modules has to implement LoginModule interface from javax security. The LoginModule contains initialize, login, logout, commit and abort methods. The initialize method gives the CallbackHanlder and other options.

The Login Method which does the authentication has to be implemented against a database for this example.

public boolean login() throws LoginException
{

if (callbackHandler == null)
throw new LoginException("Error: no CallbackHandler available "
+ "to garner authentication information from the user");

try
{
// Setup default callback handlers.
Callback[] callbacks = new Callback[] { new NameCallback("Username: "),
new PasswordCallback("Password: ", false), new NameCallback("Database: ") };

callbackHandler.handle(callbacks);

String username = ((NameCallback) callbacks[0]).getName();
String password = new String(((PasswordCallback) callbacks[1]).getPassword());
String dbname = ((NameCallback) callbacks[2]).getName();

((PasswordCallback) callbacks[1]).clearPassword();

success = rdbmsValidate(username, password,dbname); // This method should try to connect
//to the database with the given username,password, url and return true on success.

callbacks[0] = null;
callbacks[1] = null;

if (!success)
throw new LoginException("Authentication failed: Password does not match");

return (true);
}
catch (LoginException ex)
{
throw ex;
}
catch (Exception ex)
{
success = false;
throw new LoginException(ex.getMessage());
}
}
The LoginModule is declared with org.eclipse.equinox.security.loginModule extension point.


<extension
id="com.sample.login.RdbmsLoginModule"
point="org.eclipse.equinox.security.loginModule">
<loginModule
class="com.sample.login.RdbmsLoginModule">
</loginModule>
</extension>

The login method calls the callback handler which is configured in the plugin.xml via the extension org.eclipse.equinox.security.callbackHandler

<extension
id="com.sample.login.LoginDialogCallbackHandler"
point="org.eclipse.equinox.security.callbackHandler">
<callbackHandler
class="com.sample.login.LoginDialogCallbackHandler">
</callbackhandler>
</extension>


The call back handler is mapped to a configName in this case say RDBMS to a Dialog which takes username, password and the db url.

The CallBackHandlerMapping is done as follows

<extension
point="org.eclipse.equinox.security.callbackHandlerMapping">
<callbackHandlerMapping
callbackHandlerId="com.sample.login.LoginDialogCallbackHandler"
configName="RDBMS">
</callbackHandlerMapping>
</extension>

Once the rdbmsValidate method successfully connects to the database with the given values , a javax.security.auth.Subject can be constructed with the Credentials and Principals as an authenticated user.

private boolean rdbmsValidate(String user, String pass) throws Exception
{

Connection con;
boolean passwordMatch = true;

try
{
Class.forName(driverClass);
}
catch (java.lang.ClassNotFoundException e)
{
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
throw new LoginException("Database driver class not found: " + driverClass);
}

try
{
if (debug)
System.out.println("\t\t[RdbmsLoginModule] Trying to connect...");

con = DriverManager.getConnection(url, user, pass);
if(con == null )
passwordMatch = false;
else
//Construct a subject.
} catch(Exception ex) {
}
return (passwordMatch)'
}

Now that all the extension points are made for the authentication. We need to call the LoginModule at the appropriate place on the application. Usually the Eclipse Application start method is a good place to keep the Authentication process.

Create the LoginContext from the RDBMS callback handler defined in the plugin.xml.

public Object start(final IApplicationContext context) throws Exception
{
String configName = Activator.getConfigurationName();
URL configUrl = Activator.getBundleContext().getBundle().getEntry("jaas_config.txt");
ILoginContext secureContext = LoginContextFactory.createContext(configName, configUrl);
secureContext.registerListener(new ProgressMonitorListener());
Integer result = null;
final Display display = PlatformUI.createDisplay();
try
{
result = (Integer) Subject.doAs(secureContext.getSubject(), getRunAction(display));
}
finally
{
display.dispose();
secureContext.logout();
}
// TBD handle javax.security.auth.login.LoginException

if (result != null && PlatformUI.RETURN_RESTART == result.intValue())
return EXIT_RESTART;
return EXIT_OK;
}


Add the following methods to the Activator class of the plugin.


private static final String CONFIG_PREF = "loginConfiguration";//$NON-NLS-1$

private static final String CONFIG_DEFAULT = "other";

public static BundleContext getBundleContext()
{
return bundleContext;
}

public static String getConfigurationName()
{
return new DefaultScope().getNode(PLUGIN_ID).get(CONFIG_PREF, CONFIG_DEFAULT);
}

Finally the jaas_config.txt file which defines the RDBMS callback Handler name with the Login Module extension ( RDBMSLoginModule ) should be placed in the plugin's root folder.


RDBMS {
org.eclipse.equinox.security.auth.module.ExtensionLoginModule required
extensionId="com.sample.login.RdbmsLoginModule"
debug=true;
};

Wednesday, February 18, 2009

Quick Tips : Opening the Eclipse Preferences with a specfic Preference Page.

When we create PreferencePages in a Eclipse RCP applications, the window->Preferences menu item opens the preferences dialog and all the preferneces are shown in the Preferences window. How about showing a particular preference page from a toolbar button in a view / application.

Before the command framework we can do it using the PreferenceUtil class like belore


PreferencesUtil.createPreferenceDialogOn(shell, preferencePageId, displayedIds, data)


But with the help of the command framework,it is way easy to do this task.


point="org.eclipse.ui.menus">
locationURI="toolbar:com.blog.sample.ui.ButtonView">
commandId="org.eclipse.ui.window.preferences"
label="Preferences"
style="push">
name="preferencePageId"
value="com.blog.sample.ui.CorePreferencePage">






The commandID opens the org.eclipse.ui.window.preferences with all the preferences. The parameter passed to the command tells the Preferences to open the preference window with the page that we want.

Have fun !.

Eclipse : How to Implement ISelectionProvider

ISelectionProvider interface provides a way to send selection events to the the ISelectionService which is received by all the ISelectionListener implementing views. All the JFace Structured viewers implements the ISelectionProvider and provide a StructuredSelection.

There are scenarios where we have a custom view which might want to fire a Selectionto the listeners. Let us look at how to do that.

Say you have a view with a Button and on clicking the button you want to send a selection event.



import org.eclipse.core.runtime.ListenerList;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;

public class ButtonView extends ViewPart implements ISelectionProvider {

private String selection;

ListenerList listeners = new ListenerList();

Button button = null;

@Override
public void createPartControl(Composite parent) {
parent.setLayout(new GridLayout(2, false));
button = new Button(parent, SWT.BORDER);
button.setText("Press Me");
getSite().setSelectionProvider(this);
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
setSelection(new StructuredSelection(button.getText()));
}
});
}

@Override
public void setFocus() {
}

public void addSelectionChangedListener(ISelectionChangedListener listener) {
listeners.add(listener);
}

public ISelection getSelection() {
return new StructuredSelection(selection);
}

public void removeSelectionChangedListener(
ISelectionChangedListener listener) {
listeners.remove(listener);
}

public void setSelection(ISelection select) {

Object[] list = listeners.getListeners();
for (int i = 0; i < list.length; i++) {
((ISelectionChangedListener) list[i])
.selectionChanged(new SelectionChangedEvent(this, select));
}
}

}




Now the ButtonView is implementing the ISelectionProvider and registered itself as a SelectionProvider to the workbench site. Now lets add the view to the views extension point. We will also create a ButtonListenerView which behaves as a SelectionListener by implementing ISelectionListener.



import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.part.ViewPart;

public class ButtonListenerView extends ViewPart implements ISelectionListener {

Button button;

@Override
public void createPartControl(Composite parent) {
getSite().getPage().addSelectionListener(this);
button = new Button(parent, SWT.BORDER);
button.setText("Before Selection Happened");
}

@Override
public void setFocus() {


}

public void selectionChanged(IWorkbenchPart part, ISelection selection) {
if (part instanceof ButtonView) {
String text = ((StructuredSelection) selection).getFirstElement()
.toString();
button.setText(text);
}
}

}




Now ButtonView sends the selection event to the selection service and the ButtonListenerView listens for the Selection events from the workbench. There is one more step to add the views to the views extension.


<extension
point="org.eclipse.ui.views">
<view
class="com.blog.sample.ui.ButtonView"
id="com.blog.sample.ui.ButtonView"
name="Button View"
restorable="true">
</view>
<view
class="com.blog.sample.ui.ButtonListenerView"
id="com.blog.sample.ui.ButtonListenerView"
name="Button Listener"
restorable="true">
</view>
</extension>



Lets see the screenshot before and after the button is clicked on the ButtonView.

Before the ButtonView send the ISelection,


Now clicking the Press Me button sends a selection event to all the listeners. ButtonListenerView processes the selection in the selectionChanged method.

Saturday, February 14, 2009

Eclipse : Keeping Preferences and Preferences UI separate

Eclipse Preferences and PreferenceStore does not connect well with each other. When we have a Core plugin which handles the preferences and the initial values, keeping the UI in a separate plugin becomes difficult. The core plugin does not have access to the PreferenceStore since it is a not UI plugin. The UI Plugin with PreferencePage cannot populate using the Preferences from the core plugin.

So how do we couple these together. The UI Plugin can create a PreferenceStore using the bundle id of the Core Plugin.



public class CorePreferencePage extends FieldEditorPreferencePage implements
IWorkbenchPreferencePage {

public CorePreferencePage() {
IPreferenceStore store = new ScopedPreferenceStore(new InstanceScope(),
""com.blog.sample.core"");
setPreferenceStore(store);
}

@Override
protected void createFieldEditors() {
BooleanFieldEditor formatOnSave = new BooleanFieldEditor("ABC", "ABC",
getFieldEditorParent());
addField(formatOnSave);

}

public void init(IWorkbench workbench) {

}

}



Now we can see the preferences of the Core Plugin in the UI Plugin's preference Page. But what if the preferences are not overridden and they are initialized from the Core Plugin using the Preference Initializer.


public class CorePreferenceInitializer extends AbstractPreferenceInitializer {

public CorePreferenceInitializer() {

}

@Override
public void initializeDefaultPreferences() {
Preferences node = new DefaultScope().getNode("com.blog.sample.core");
node.put("ABC", "true");
}
}


and the core plugin declares an extension point to initialize the value when the preference node is accessed. But the initializer will be only invoked only if it is invoked from the bundle which is initialized.








Now the initializer is invoked when it is accessed from the Core Plugin getPreferences. Now the UI Plugin does not know about the default values from the initializer. Whats the workaround?

Add a duplicate extension point on the UI Plugin with the same initializer from the Core Plugin. Now when you open the prefernece page the initializer on the Core Plugin is invoked and the values are set to default.

Have fun !

Friday, February 13, 2009

Eclipse : Adding a Static text to the toolbar

There are situations you need to show a static text on the toolbar with a user name or some sort of text. This can be done using the ControlContribution.

JFace provides ControlContribution which can be added to the toolbar.




public class LabelControlContribution extends ControlContribution
{

protected LabelControlContribution(String id)
{
super(id);
}

@Override
protected Control createControl(Composite parent)
{
final Label b = new Label(parent, SWT.LEFT);
b.setText("Label: <Your User Name>");
return b;
}

}



Add the ControlContribution to the coolbar in the ApplicationActionBarAdvisors fillCoolbar method.


IToolBarManager toolbar1 = new ToolBarManager(SWT.FLAT
| SWT.RIGHT_TO_LEFT);
coolBar.add(new ToolBarContributionItem(toolbar1, "label"));
toolbar1.add(new LabelContribution("Label"));


Now the toolbar with the ControlContribution gets added to the Toolbar.

Quick Tip : Multiple Target Platform support from 3.5M5

Eclipse now supports adding multiple target platforms. The Target platform preference page in Plugin-Development allows adding multiple target platforms and assigning one of them as default.

This feature is still experimental. More details at http://download.eclipse.org/eclipse/downloads/drops/S-3.5M5-200902021535/eclipse-news-M5.html

Quick Tip : Eclipse-BundleShape header - Package plugins as directory

Eclipse MANIFEST.MF with a '.' for the Bundle-classpath packages the plugin as a jar file when the plugin is exported. But there are many cases where the plugin needs to be directory to read the files inside the plugin.

From 3.5 , eclipse supports a new header in the MANIFEST.MF called Eclipse-BundleShape. The header allows two types 'dir' and 'jar'.

Wednesday, February 11, 2009

Eclipse : How to create Wizards

Eclipse provides easy ways to create wizards and connect them to standard eclipse actions like New, Import,Export and so on. If you want to add a Wizard to file->New menu, you can use the newWizards extension point.


point="org.eclipse.ui.newWizards">
class="com.blog.sample.loginapp.SampleWizard"
id="com.blog.sample.loginApp.wizard3"
name="Sample Wizard">




This adds a Sample Wizard to the File New action. Now the SampleWizard has to include all the pages in the wizard. First of all, the SampleWizard has to implement the IWizard interface ( can extend the abstract implementation Wizard ).


import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;

public class SampleWizard extends Wizard implements INewWizard {

public SampleWizard() {

}

@Override
public boolean performFinish() {

return false;
}

public void init(IWorkbench workbench, IStructuredSelection selection) {


}

}


This creates a Wizard as shown below.



Now to add a Page to the SampleWizard , create a WizardPage and add it.


public class SamplePage extends WizardPage {

Text text = null;

public SamplePage() {
super("SamplePage1");
setTitle("Page1");
setDescription("Page1 Description");
}

public void createControl(Composite parent) {
Composite comp = new Composite(parent, SWT.NONE);
comp.setLayout(new GridLayout(2, false));
Label label = new Label(comp, SWT.NONE);
label.setText("Text ");
text = new Text(comp, SWT.BORDER);
text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
setControl(parent);
}

@Override
public boolean isPageComplete() {
return super.isPageComplete();
}

}


Now the SamplePage has to be added to the SampleWizard via the addPages method as follows.


@Override
public void addPages() {
super.addPages();
addPage(samplePage);
}


This adds the page as below.



The isPageComplete() method from the SamplePage enables/disables the Next button if the page is complete. Once all the data is taken from the page. The isPageComplete returns true to the SampleWizard. At the end, the SampleWizard enables the finish the Button by looking at the canFinish return value. The canFinish can return true if the mandatory values are entered.

Have fun !.

Eclipse : How to save a dirty view

Eclipse has editors and views. When the contents of a editor is modified, the editor's state changes to dirty state and the user is asked to save it when he closes the application.

Editors implement IEditorPart interface which extends ISaveablePart. ISaveablePart has the following methods.



@Override
public void doSave(IProgressMonitor monitor)
{

}

@Override
public void doSaveAs()
{

}

@Override
public boolean isDirty()
{

return false;
}

@Override
public boolean isSaveAsAllowed()
{

return false;
}

@Override
public boolean isSaveOnCloseNeeded()
{

return false;
}



So if you need the ViewPart to behave like a editor when the content is modified, the ISaveablePart should be implemented by the ViewPart class.

More importantly when something is changed on the View, set the dirty flag to true and fire a property change event to the workbench, otherwise the Save menu item will not be enabled on the workbench.


public boolean isDirty()
{
return _dirty;
}

protected void setDirty(boolean value)
{
_dirty = value;
firePropertyChange(PROP_DIRTY);
}

Eclipse : Most useful Eclipse plugins for a developer

There are lot of open source and commercial eclipse plugin available out there. Here are some of the best plugins that i have used during my eclipse based application development.

Subclipse

Checking out code from the version control will be the first step for any developer. CVS, Subversion are two of the mostly used Version control systems. Eclipse IDE provides the CVS Repository access by default. Since we had a Subversion repository for our version control, we needed a Subversion client for eclipse. There are two major SVN Clients for eclispe, Subclipse and Subversive.

We have chosen Subclipse over subversice since we had some performance problem using Subversive.

You can get it from http://subclipse.tigris.org/

Checkstyle

Software development involves the teams writing code properly by following some coding standard. Following the coding standard helps in many ways like, maintainability and readability. Eclipse has plugins which enforces these coding standards during the development. Checkstyle plugin is a freely available plugin which checks coding standards and also some java best practices.

Checkstyle is configurable through the Eclipse preferences where the user can import a predefined checkstyle xml file.

You can get it from http://eclipse-cs.sourceforge.net/

Code Coverage

Softwares need to be tested at different levels like unit testing, system testing , integration testing and so on. The software programmer usually writes unit test code to test an unit of functionality in the software. The unit tests cover a particular portion of the code base developed. The code coverage tools highlights the unit test covered code and gives statistical information about the testing.

Eclipse has a plugin called EclEmma which integrates into the Run Configuration and gives all the coverage details.

you can get it from http://www.eclemma.org/


DBViewer

Most projects has a backend database which holds the application data. The developers writes SQL queries to retrieve the database results or maps the database columns to Object relational mapping tools like Hibernate. DBViewer plugin helps doing all this inside eclipse ide itself rather than using additional java sql tools.

You can configure any number of databases and query them and edit them using a simple table from inside eclipse.

You can get if from http://www.ne.jp/asahi/zigen/home/plugin/dbviewer/about_jp.html

Plugin Builder

Once the plugins are developed in eclipse. The plugins and features needs to be built on a build machine to achieve continuous integration. Pluginbuilder is a eclipse plugin which helps creating build xml files from inside eclipse.

You can get it from http://www.pluginbuilder.org/

Eclipse : Uncloseable ViewPart

There are some cases where view part must not be closed in a perpective. Eclipse RCP provides an easy way to make the viewpart uncloseable.

From the perspective class which defines the layout for the Perspective, the viewpart can be set uncloseable.



public void createInitialLayout(final IPageLayout layout)
{
final String editorArea = layout.getEditorArea();
layout.addView(View.ID, IPageLayout.LEFT, 0.5f, editorArea);
layout.getViewLayout(View.ID).setCloseable(false);
}

Monday, February 2, 2009

Eclipse RCP: Removing unwanted actionSets from menubar

Eclipse provides some default actionSets when you include the plugins like org.eclipse.ui. In many cases, the application does not need these actions.
So how do we remove these actions from the menubar and toolbar? Well, there is this ugly code which removes the unwanted action sets.


final ActionSetRegistry reg = WorkbenchPlugin.getDefault().getActionSetRegistry();
final IActionSetDescriptor[] actionSets = reg.getActionSets();
final String[] removeActionSets = new String[] {
"org.eclipse.search.searchActionSet","org.eclipse.ui.cheatsheets.actionSet",
"org.eclipse.ui.actionSet.keyBindings","org.eclipse.ui.edit.text.actionSet.navigation",
"org.eclipse.ui.edit.text.actionSet.annotationNavigation","org.eclipse.ui.edit.text.actionSet.convertLineDelimitersTo",
"org.eclipse.ui.edit.text.actionSet.openExternalFile","org.eclipse.ui.externaltools.ExternalToolsSet",
"org.eclipse.ui.WorkingSetActionSet","org.eclipse.update.ui.softwareUpdates",
"org.eclipse.ui.actionSet.openFiles","org.eclipse.mylyn.tasks.ui.navigation", };

for (int i = 0; i < actionSets.length; i++) {
boolean found = false;
for (int j = 0; j <; removeActionSets.length; j++) { if(removeActionSets[j].equals(actionSets[i].getId())) { found= true; } } if(!found) { continue; } final IExtension ext = actionSets[i].getConfigurationElement().getDeclaringExtension(); reg.removeExtension(ext, new Object[] { actionSets[i] }); }

But this code needs to access restricted API from eclipse internal packages. When the eclipse activities are introduced the above discouraged can be declaratively done inside the plugin.xml file. If you wanted to remove the search menu from the menubar, define an activity and use the pattern org.eclipse.search.* as the activity pattern as below.




<extension point="org.eclipse.ui.activities">
<activity id="com.sequenom.ivd.actitivities.unwantedActionSet1" name="Unwanted Search ActionSet">
<enabledwhen>
<with variable="activePartId">
<equals value="com.sequenom.ivd.actitivities.unwantedActionSet">
</equals>
</with></enabledwhen></activity></extension>

<activitypatternbinding activityid="com.sequenom.ivd.actitivities.unwantedActionSet1" pattern="org.eclipse.search.*">
</activitypatternbinding>

This will remove the search menu from your application. Have fun !

Wednesday, January 21, 2009

Eclipse RCP : Sorting JFace Viewer contents

The JFace viewer contents can be sorted by assigning them a ViewerSorter.


viewer.setSorter(new MyViewerSorter());

public class MyViewerSorter extends ViewerSorter
{
@Override
public int compare(Viewer viewer, Object o1, Object o2)
{
return o1.toString().compareToIgnoreCase(o2.toString());
}
}


This will sort the elements in alphabetical order.

Tuesday, January 20, 2009

Eclipse RCP: Command, Handler enabledWhen with a particular selection object

Command Framework
Command framework allows to add menubar and toolbar actions via handlers. To create a command in the application.

Create an extension of the commands


<extension point="org.eclipse.ui.commands">
<command defaulthandler="com.mycomp.app1.commands.SampleHandler" id="com.mycomp.app1.commands..SampleCommand" name="Add User">
</command>
</extension>

Implement the SampleHandler which is the default handler for the command. The handler should implement the interface IHandler or can simply extend AbstractHandler. Now we can add the Command to application main menubar, toolbar or to a menubar and toolbar of a view.

To add it a to a view's toolbar


<extension point="org.eclipse.ui.menus">
<menucontribution locationuri="toolbar:com.mycomp.app1.SampleView">
<command commandid="com.mycomp.app1.commands.SampleCommand" icon="icons/sample.png" label="Sample" style="">
</command>
</menucontribution>
</extension>

This will add the handler to the SampleView's toolbar. But to activate this, we need to have activeWhen command expression.


<activeWhen>
<equals variable="activePartId">
<value="com.mycomp.app1.SampleView"/>
</with>
</activeWhen>


Now the SampleHandler will be on the toolbar of the view. The handler execute method can get the activepart,selection, and different workbench values from HandlerUtil class.

HandlerUtil.getActiveWorkbenchWindow(event) or HandlerUtil.getCurrentSelection(event).

To enable and disable the action based on selection, enabledWhen needs to be extended, Now lets enable the action only for one selection.


<enabledWhen>
<with variable="selection">
<value="1">
</count>
</with>
</enabledWhen>

Sunday, January 18, 2009

Eclipse RAP: Creatiing a multiuser RAP Application

What is RAP ?

Rich Ajax Platform, a web development platform for RCP Developers. RAP uses the whole plugin architecture of the eclipse platform and provides a SWT port called RWT for the web browsers. RWT uses the qooxdoo java script library to create the User interfaces on the browser side.

Singleton

Singleton pattern is something which is widely used on the eclipse platform. But for a web based application where multiple users will be accessing the application we need session based singleton implementation.

SessionSingletonBase

Eclipse RAP provides a base class called SessionSingletonBase which provides a singleton implementation for each session and avoids the sharing the application state between the users.

so just extends the SessionSingletonBase and create a singleton instance as done below.


SampleAppPlatform extends SessionSingletonBase {

public static final SampleAppPlatform getInstance() {
return (SampleAppPlatform) getInstance(SampleAppPlatform.class);
}
}


and try accessing the RAP web application from multiple browser instances and check the SampleAppPlatform state. It will be different.



Friday, January 16, 2009

Eclipse: Build Product, Coverage and lot of Reports.

Continous Integration

Continuous integration is a practive where developers integrate their work frequently. This help the team increase their productivity by detecting the integrating errors as early as possible during the development. There are a lot of build tools which helps in automating the build process with different reports which helps the developers to increase their work productivity.

Ant, Maven

Ant and Maven are two build tools which are very widely used in the java build process. Though ANT is a old and little complicated tool than the Maven, it gives the flexibility to do the build for any kind of software application.
Maven works great for almost all kinds of java application like web application, desktop applications. Maven also generates a whole lot of reports which helps the team at various levels to see the progress of the development.

Building Eclipse Products

Building eclipse product is always a difficult job if you want to do it outside the Eclipse Environment. And especially building eclipse product with maven not so easy work. Though there are existing plugins which does the product build little easier, they are not as efficient as the ANT counter part.

Since eclipse requires its own run time environment for building and running, the Maven structure does not help a lot. The following maven plugins does help in building eclipse plugins

But running the test cases and generating different reports based on this is a difficult process using the above tools.

Combining ANT and Maven

PluginBuilder is a eclipse plugin which provides an easy mechanism to create the ANT build scripts for building eclipse plugins, running test cases, and building the product. And it works out of the box.

Download it from http://www.pluginbuilder.org/

Create your plugin project with the test cases in a separate fragment project.

Create the build.xml and other supporting files for the ANT Build which creates Product, Test Report and Test Coverage Report.

Configure a ANT build step on the Automated build tool such as Luntbuild.

Now for the usual Maven reports and site generation we can use the Maven PDE plugin without the test option. This should not include the test fragments in build path.

This is it. You get a Product file, Unit Test Reports, Unit Test Coverage and all maven reports deployed as a site.

This tutorial doesnt give you step by step procedure but if you need help doing anything above. Just drop in a comment.

Eclipse: Making Heap Status visible

On eclipse based applications, there is a way to display the heap status on the status bar. The API which enables this feature is internal and the way to make it to visible is to create the plugin customization file.

Add the following property in the plugin.xml under the products extension

And on the plugin_customization.ini

org.eclipse.ui/SHOW_MEMORY_MONITOR=true

The SHOW_MEMORY_MONITOR parameter will be looked when the workbench is created and if it is true it will create the heap status bar.

Thursday, January 15, 2009

Eclipse: Create a file in the runtime workspace

Sometimes you may need to create a file in the runtime workspace temporarily or to store application wide data. This is better than storing the file inside the .metadata/.plugins/ folder since this will require having to have a dependency on plugin which is creating the file.


IPath path = Platform.getLocation();


This gives the path of the runtime workspace.