Archive for the ‘java’ Category

Debugging And Logging Java RMI Calls

Tuesday, June 15th, 2010

If you ever need to debug Java RMI, then add these properties to the VM configuration:

-Djava.rmi.server.logCalls=true
-Dsun.rmi.server.logLevel=VERBOSE
-Dsun.rmi.client.logCalls=true
-Dsun.rmi.transport.tcp.logLevel=VERBOSE

Implementing Ajax push with RichFaces

Tuesday, August 18th, 2009

The following snippets illustrates how to implement an ajax push in a JSF application where RichFaces is set up. I am using this with a JSF application with Tomahawk extensions and RichFaces just for Ajax and Menus

Add the following in the XHTML:

<!-- Register an ajax listener on the bean -->
<a4j:push interval="1000" eventProducer="#{bean.addPushListener}"
    reRender="ajaxPanel" enabled="#{bean.pushing}" id="pushLstnr" />
<!-- the panel to be updated -->
<a4j:outputPanel id="ajaxPanel" ajaxRendered="true">
<h:messages layout="table" errorStyle="color:red"
      fatalStyle="color:red" infoStyle="color:blue" showDetail="true"
      showSummary="true" styleClass="loginError" />
</a4j:outputPanel>

Add the following to the Bean:

/**
  * Registers the ajax listener
  *
  * @param listener
  */
public void addPlanStatePushListener(EventListener listener) {
  synchronized (listener) {
    if (this.ajaxPushListener != listener) {
      this.ajaxPushListener = (PushEventListener) listener;
    }
  }
}

Now all you have to do is execute this call in your code where you need to update your browser:

// send event to browser:
ajaxPushListener.onEvent(new EventObject(this));

Have fun
Robert

Creating icons for eclipse applications

Tuesday, February 17th, 2009

I’ve been starting to get quite annoyed with problems surrounding creating icons for use in eclipse applications. Windows needs either alot of icons in 8bit and 32bit or one ico containing all of those images. Anyhow after some trying I found out how I could get this done.

  1. First you create your icon in a large enough size so you don’t loose any information
  2. Then you use gimp and create all the 32bit versions by just resizing the image to 48×48, 32×32 and 16×16. These you can keep in the RGB mode and then save as BMP’s
  3. All the 8-bit images created nearly the same. You just need to change the mode to indexed and then change the maximum number of colours to 255 for 8bit.
  4. You can create an ico file with the imagemagick package in linux with the following command:
    convert image1_16_8bit.bmp image2_16_32bit.bmp.... -channel Alpha -negate image.ico
  5. Then go into the Eclipse product page and choose each icon respectively

Running Task asynchronously in Eclipse RCP and JFace

Tuesday, February 17th, 2009

These code snippets show how it is possible to executes task in Eclipse by showing a progress dialog, which is possible to hide

This is the code to start the job:

// create action to be called after the action is completed
// this action shows a success dialog if the job executed without
// an exception, otherwise it shows an error dialog
final CompletionAction completionAction = new
        CompletionAction(AdminClientActivator.PLUGIN_ID, parent.getShell(), view);
completionAction.setOkTitle("Job sucess");
completionAction.setOkMsg("Sucessfully executed job");
completionAction.setFailTitle("Job failed");
completionAction.setFailMsg("There was an exception while executing job");

RSPClientJob job = new ClientJob("Long job...", completionAction);

// if short action, otherwise is long Job.LONG
job.setPriority(Job.SHORT);
// show a dialog immediately
job.setUser(true);
// start as soon as possible
job.schedule();

This snippet is the Job class:

/**
 * Abstract {@link Job} class for executing tasks with a progress dialog
 * @author Robert von Burg
 */
public class ClientJob extends Job {
  private CompletionAction completedAction;

  /**
   * @param name
   * @param completedAction
   */
  public ClientJob(String name, CompletionAction completedAction) {
    super(name);
    this.completedAction = completedAction;
  }

  protected IStatus run(IProgressMonitor monitor) {
    // activate the progress bar with an unknown amount of task work
    monitor.beginTask("Loading Hibernate configuration", IProgressMonitor.UNKNOWN);
    // perform the job
    try {
      // execute task work...
      Thread.sleep(10000);
      // at the end of the successfully ended work, set the completion
      // task to be ok
      completionAction.setOk(true);
    } catch (Exception e1) {
      logger.error(e1, e1);
      // if the work failed then set the completion
      // task to be NOT ok and set the exception so it
      // can be shown to the user
      completionAction.setThrowable(e1);
      completionAction.setOk(false);
    }
    // stop the monitor
    monitor.done();
    // execute the completion task
    complete();
    return Status.OK_STATUS;
  }

  /**
   * completes the task by showing the user a dialog about the execution
   * state of the job
   */
  protected void complete() {
    setProperty(IProgressConstants.ICON_PROPERTY, ImageFactory.
                getImg(ImageFactory.IMG_OK));
    Boolean isModal = (Boolean) this.getProperty(
                IProgressConstants.PROPERTY_IN_DIALOG);
    if (isModal != null && isModal.booleanValue()) {
      // The progress dialog is still open so
      // just open the message
      showResults(completedAction);
    } else {
      setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE);
      setProperty(IProgressConstants.ACTION_PROPERTY, completedAction);
    }
  }

  /**
   * Asynchronous execution of an {@link Action}
   * @param action
   */
  protected static void showResults(final Action action) {
    Display.getDefault().asyncExec(new Runnable() {
      public void run() {
        action.run();
      }
    });
  }
}

And since we want to notify the caller about task completion we use this interface:

/**
 * Interface for notifying objects to be refreshed
 * @author robertb
 */
public interface Refreshable {
  public void refresh();
}

And task completion is handled with this Action:

/**
 * The completion task, which either shows a success dialog, or an error dialog,
 * depending on the ok state set and then notifies the {@link Refreshable} to
 * refresh its contents
 * @author robertb
 */
public class CompletionAction extends Action {
  private boolean ok;
  private String okTitle;
  private String okMsg;
  private String failMsg;
  private String failTitle;
  private Throwable throwable;

  private Refreshable refreshable;
  private Shell shell;
  private String pluginId;

  /**
   * @param pluginId
   * @param shell
   * @param refreshable
   */
  public CompletionAction(String pluginId, Shell shell, Refreshable refreshable) {
    this.pluginId = pluginId;
    this.shell = shell;
    this.refreshable = refreshable;
  }

  public void setOk(boolean ok) {
    this.ok = ok;
  }

  public void setOkTitle(String okTitle) {
    this.okTitle = okTitle;
  }

  public void setOkMsg(String okMsg) {
    this.okMsg = okMsg;
  }

  public void setFailMsg(String failMsg) {
    this.failMsg = failMsg;
  }

  public void setFailTitle(String failTitle) {
    this.failTitle = failTitle;
  }

  public void setThrowable(Throwable throwable) {
    this.throwable = throwable;
  }

  public void run() {
    // first refresh
    refreshable.refresh();
    // then show the dialog
    if (ok) {
      MessageDialog.openInformation(shell, okTitle, okMsg);
    } else {
      Status status = new Status(IStatus.ERROR, pluginId,
                throwable.getLocalizedMessage(), throwable);
      ErrorDialog.openError(shell, failTitle, failMsg, status);
    }
  }
}

I put this together with help from the following site:
Job Concurrency

Thanks
eitch

JAVA and JAR’s from the command line

Friday, January 23rd, 2009

This is a small little tutorial which will explain how to create your own little Java application which have dependencies which are in other JAR files

First create the following directory structure:

java_test
    |
    |__myapp
    |     |__src
    |     |   |__ch
    |     |       |__eitchnet
    |     |            |__java
    |     |                 |__Main.java
    |     |__META-INF
    |     |    |__MANIFEST.MF
    |     |__bin
    |
    |__mydep
    |     |__src
    |     |   |__ch
    |     |       |__eitchnet
    |     |            |__helloworld
    |     |                 |__HelloWorld.java
    |     |__bin
    |
    |__deploy
        |__lib

The MANIFEST.MF file has the following content:

	Main-Class: ch.eitchnet.java.Main
	Class-Path: mydep.jar

The Main.java file has the following content:

  package ch.eitchnet.java;

  import ch.eitchnet.helloworld.HelloWorld;

  public class Main {
      public static void main(String[] args) {
      HelloWorld hw = new HelloWorld();
      System.out.println("HelloWorld instances: " + hw.getInstancesCount());
    }
  }

The HelloWorld.java has the following content:

  package ch.eitchnet.helloworld;

  public class HelloWorld {
    private static int instances;

    public HelloWorld() {
      System.out.println("Created HelloWorld object");
      instances++;
    }

    public int getInstancesCount() {
      return instances;
    }

    protected void finalize() {
      instances--;
    }
  }

Change your directory to be in the root of our project

Compile the dependency first:

find mydep/src/ -name "*.java" | xargs javac -d mydep/bin/

Should you be using a windows system, then you have compile file by naming each one. See the java help file for more information

Create the jar:

jar cvf ./deploy/mydep.jar -C ./mydep/bin ./

Compile the app:

find myapp/src/ -name "*.java" | xargs javac -classpath ./deploy/*.jar -d myapp/bin/

Should you be using a windows system, then you have compile file by naming each one. See the java help file for more information

Create the jar:

jar cmvf ./myapp/META-INF/MANIFEST.MF ./deploy/myapp.jar -C ./myapp/bin ./

Run the app by specifying everything explicitly:

java -classpath ./deploy/myapp.jar:./deploy/mydep.jar ch.eitchnet.java.Main

Or by running directly allowing the MANIFEST.MF to do its magic:

java -jar ./deploy/myapp.jar

tutorial files

grretings eitch

JSF and PDF’s

Thursday, January 22nd, 2009

This is a quick snipped on transmitting a PDF in a JSF context:

byte[] bytes = getPDFStreamAsArray();
FacesContext faces = FacesContext.getCurrentInstance();
HttpServletResponse response =
(HttpServletResponse) faces.getExternalContext()
.getResponse();
response.reset();
response.setContentType("application/pdf");
response.setContentLength(bytes.length);
response.setHeader("Content-disposition", "inline;filename="file.pdf""); // inline or attachment
response.setHeader("Cache-Control", "cache, must-revalidate");
ServletOutputStream out = response.getOutputStream();
out.write(bytes);
faces.responseComplete();

JSF and EL (Expression Language) rant !

Tuesday, January 20th, 2009

Beware people… Referring to missing methods in a Bean from a XHTML page using the expression language yields an exception, but referring to a *private* method, doesn’t to nothing. No exception, no message, just plain and simply nothing.

I spent hours trying to understand why my application didn’t work, and now I know it: Be careful that your exposed method is not marked as *private* in your bean!!

eitch

Java RMI quick and dirty

Friday, January 16th, 2009

Your object which will be accessible through RMI must meet the following requirements:

  • have its own interfaces which extends java.rmi.Remote
  • all methods must “throws RemoteException
  • all returned returned objects must implement java.io.Serializable

Starting a RMI server:

  • Set system property: System.setProperty("java.rmi.server.hostname", "hostname");
  • create registry: Registry registry = LocateRegistry.createRegistry(1099);
  • export Object: RemotableObject stub = (RemotableObject) UnicastRemoteObject.exportObject(remoteObject, 0);
  • bind object: registry.rebind("RemoteName", stub);

Remote call:

  • get Registry: Registry registry = LocateRegistry.getRegistry("hostname");
  • get Remote object: RemotableObject remoteObject = (RemotableObject) registry.lookup("RemoteName");
  • call method: remoteObject.remoteMethod();

Apache Tomcat 6.0 configuration for developers

Thursday, May 1st, 2008

Just a quick blog on configuring some specific Tomcat 6.0 settings:

Memory Heap Size on a unix based system

Open the file %tomcat_install_folder%/bin/startup.sh

Add the line:

export CATALINA_OPTS="-Xms256m -Xmx512m"

before the line:

exec "$PRGDIR"/"$EXECUTABLE" start "$@"

to have a memory heap of at least 256mb and max of 512mb.

Memory Heap Size on a Windows based system

On a windows platform you have to set a environment variable called “CATALINA_OPTS”, with the value:

-ms128m -mx256m

You can this by right clicking the icon of your “My Computer” and then choosing properties. Under “System” I think you will then find the environment variable editor. Just add it there.

Activating servlet reloading

Open the file %tomcat_install_folder%/conf/context.xml

Change the element tag “Context” from so:

<Context>

to so:

<Context reloadable="true" privileged="true">

have fun coding webapps
eitch

Simple Configuration for Log4j

Friday, April 18th, 2008

Ever wanted to use Log4j, but didn’t know how to configure it? Or you don’t remember how to configure it in a jiffy?

Just add the following two lines in your application, like say in the main()-method and then your’re done:


BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%d %5p [%t] %C{1} %M - %m%n")));
Logger.getRootLogger().setLevel(Level.INFO);

The first line sets logging to go to the console and it will look something like this:

2008-04-18 11:21:33,395 INFO [main] TestApp main - exists: true

If you want a different logging level, then just take Level.DEBUG, or whatever else suits you.