Programming

Eclipse C/C++ and Linux Libraries

Posted in C/C++, Linux, Programming on February 4th, 2009 by Nick – 20 Comments

This is a really quick tutorial on configuring Eclipse CDT (C/C++ Development Tools) so you can work with shared libraries.  A lot of this may be basic for some readers, but for a programmer that’s used to Visual Studio and a Windows dll environment it may not.  read more »

Inserting javascript into GWT using JSNI

Posted in GWT, Java, Programming on January 27th, 2009 by Nick – 3 Comments

Sure the whole point of using GWT is so you don’t have to mess with that abortion known as javascript, but sometimes you may need (or actually want) to use javascript for something in your GWT application.  For this we use JavaScript Native Interface (JSNI).  JSNI uses the native keyword, so if you’ve used JNI (Java Native Interface) in the past you’ll have little to get used to.

I needed to use JSNI recently.  Since GWT doesn’t provide a way to bring the browser to the front or top like javascript does with it’s self.focus(); I was able to use JSNI to call that line of javascript.  Here’s a quick example:

public static native void bringToFront() /*-{
  self.focus();
}-*/;

Then all you need to do is call the bringToFront() method like you normally would.  Along with noticing in the native keyword, you’ll immediate see that the block looks commented out.  JSNI has two tokens to mark the beginning and end of your javascript the /*-{ marks the begin and }-*/ marks the end.  Everything in between those tokens are assumed to be javascript.

There are more examples on GWT JSNI site.

Simple Charts in GWT with gchart

Posted in GWT, Java, Programming on January 26th, 2009 by Nick – 9 Comments

I’ve been tasked with adding some simple charts to a GWT project and after looking at several APIs I’ve settled with trying out gchart.  A couple of reasons for this choice is:

  • gchart is 100% GWT (meaning it’s not a javascript wrapper)
  • It runs on the client-side. Some other charting APIs actually build the chart on the server-side as an image and return the link for the image.  This can be an advantage for some situations, so you may need to think about if you want a client-side or server-side render.
  • Open source under Apache License, Version 2.0
  • Very simple to use.

I put together a very simple example, and it shows how quickly you can build a chart.  The example is a compound interest financial calculator shown below (go ahead and try it out).  It has a few fields to enter your initial amount, annual contributions, interest rate, number of compounds per year and the number of years.  After clicking on the calculate button it will show your future amount and chart it.


In case the iframe doesn’t show up in your browser you can see and try the charting example here.

The simplicity of this charting API is the fact that the charts are GWT widgets.  Here’s the code for my compounding interest chart:

public class AmountChart extends GChart {
	public AmountChart() {
		setChartSize(240, 200);
		setPadding("4px");
		getXAxis().setAxisLabel("Years");
		getYAxis().setAxisLabel("$");
	}
 
	public void addPoint(double x, double y) {
		GWT.log("point added ("+x+", "+y+")", null );
		getCurve().addPoint(x, y);
	}
}

Then all I did was add it to the DecoratedTabPanel, put in the event listeners, the formula (which I got from wiki) and done.
You can download the full source here, and the entire application is client side.

Updated 2008-01-28: I updated the iframe that the form is in to be more friendly with IE. Also made a change recommended by John Gunther to remedy a problem with IE. Compiled using gchart 2.4 and I updated the downloadable source.

GWT Hosted Mode and Log4j

Posted in GWT, Java, Programming on January 19th, 2009 by Nick – 3 Comments

This is a short tutorial on getting log4j to run in the embedded Tomcat included with GWT.  Before I go on I need to say that log4j will only work on the server-side. GWT doesn’t support logging with log4j on the client side (yet…maybe). To log on the client side you’ll still have to use GWT.log()

There are four things we’ll need to accomplish:
1. Place the log4j.properties file
2. Write a servlet that will initialize the logger.
3. Modify the web.xml file.
4. Modify the GWT -shell and -compile scripts.

1. Place the log4j.properties file

Under <gwt-project>/tomcat/webapps/ROOT/WEB-INF/ create a “classes” dir.  The “classes” dir is where you put the log4j.properties file.  Here’s the log4j.properties file I’m using:
log4j.rootCategory=DEBUG, dest1, dest3

! Log to the console
log4j.appender.dest1=org.apache.log4j.ConsoleAppender
log4j.appender.dest1.layout=org.apache.log4j.PatternLayout
log4j.appender.dest1.layout.ConversionPattern=%-5p %d{HH:mm:ss.SSS} [%-15.15t] [%-25.25c{1}] %m%n

! LOG TO A FILE
log4j.appender.dest3=org.apache.log4j.RollingFileAppender
log4j.appender.dest3.layout=org.apache.log4j.PatternLayout
log4j.appender.dest3.layout.ConversionPattern=%-5p %d{EEE MMM dd HH:mm:ss.SSS zzz yyyy} [%-15.15t] [%-25.25c{1}] %m%n

! Specify the file name
log4j.appender.dest3.File=./logs/hosted-log4j.log

! Control the maximum log file size
log4j.appender.dest3.MaxFileSize=3000KB
log4j.appender.dest3.MaxBackupIndex=3

2. Write a servlet that will initialize the logger.

Next you’ll want to have a servlet that will load the properties file and init the logger. This file (Log4JInitServlet.java) will go in the <gwt-project>/src/ dir.

package com.nick.example.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
/**
* Log4JInitServlet
*
* This class should get loaded first (based on the web.xml),
* so it can init the logger.
*
* @author Nick
*/
public class Log4JInitServlet extends HttpServlet {
  static final Logger logger = Logger.getLogger(Log4JInitServlet.class);
 
  public void init() throws ServletException {
    System.out.println("Log4JInitServlet init() starting.");
    String log4jfile = getInitParameter("log4j-properties");
    System.out.println("log4jfile: "+log4jfile);
    if (log4jfile != null) {
      String propertiesFilename = getServletContext().getRealPath(log4jfile);
      PropertyConfigurator.configure(propertiesFilename);
      logger.info("logger configured.");
    }else{
      System.out.println("Error setting up logger.");
    }
      System.out.println("Log4JInitServlet init() done.");
  }
}

This servlet should be loaded first, which can be accomplished by modifying the web.xml file.

3. Modify the web.xml file.

This file is located in <gwt-project>/tomcat/webapps/ROOT/WEB-INF/
My web.xml file looks like:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <servlet>
    <servlet-name>Log4JInitServlet</servlet-name>
    <servlet-class>com.nick.example.server.Log4JInitServlet</servlet-class>
    <init-param>
      <param-name>log4j-properties</param-name>
      <param-value>/WEB-INF/classes/log4j.properties</param-value>
     </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet>
    <servlet-name>shell</servlet-name>
    <servlet-class>com.google.gwt.dev.shell.GWTShellServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>shell</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>

Notice the line <load-on-startup>1</load-on-startup>, which tells tomcat to load the Log4JInitServlet first.

4. Modify the GWT -shell and -compile scripts.

Modify your gwt –shell and –compile files to add the log4j jar into the class path. Here’s my <project>-shell.cmd file. Take note of the log4j jar that I added.

[Windows]
@java -Xmx256M -cp “%~dp0\src;%~dp0\bin;C:/lib/gwt-windows-1.5.3/gwt-user.jar;C:/lib/gwt-windows-1.5.3/gwt-dev-windows.jar;C:/lib/gwt-windows-1.5.3/log4j-1.2.12.jar” com.google.gwt.dev.GWTShell -out “%~dp0\www” %* com.nick.example.HostedLog4j/HostedLog4j.html

[linux]
#!/bin/sh
APPDIR=`dirname $0`;
java -Xmx256M -cp “$APPDIR/src:$APPDIR/bin:$HOME/projects/gwt-linux-1.5.3/gwt-user.jar:$HOME/projects/gwt-linux-1.5.3/gwt-dev-linux.jar:$HOME/projects/lib/log4j-1.2.15.jar” com.google.gwt.dev.GWTShell -out “$APPDIR/www” “$@” com.nick.example.HostedLog4j/HostedLog4j.html;

Make sure to change the <project>-compile.cmd in the same way.
You can then run your <gwt-project>-shell.cmd and the logger should work. It will create a log directory in under <gwt-project> and place your log file inside there.

Java EchoServer Example

Posted in Java, Programming on January 11th, 2009 by Nick – Be the first to comment

I’m using this post to experiment with syntax highlighting in my blog.  Recently a friend needed a program to echo data on a socket while he was testing an internet appliance and some other network enabled hardware so I figured I’d just use that code as my example.

The EchoServer will open a listen socket on port 4444.  Compile it, run it and then to test it you can open a command prompt and type telnet localhost 4444

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
 
/**
 * @author NickC
 */
public class EchoServer {
   private static final int BUFFER_SIZE = 256; 
   private static int listenPort = 4444;
 
   public static void main(String[] args) throws Exception{
      ServerSocket serverSock = new ServerSocket(listenPort);
      System.out.println("listening on port "+listenPort);
      Socket sock = serverSock.accept();
      System.out.println("new connection " + sock);
 
      InputStream sockIn = sock.getInputStream();
      OutputStream sockOut = sock.getOutputStream();
      byte[] buffer = new byte[BUFFER_SIZE];
      while(true) {
         Thread.sleep(50);
         int count = 0;
         if ((count = sockIn.available()) > 0) {
            if (count >= buffer.length) {
               count = buffer.length;
            }
            count =  sockIn.read(buffer, 0, count);
            System.out.println("echoing "+count+" bytes");
            sockOut.write(buffer, 0, count);
            sockOut.flush();
         }
      }
   }
}

Source in a file: EchoServer.java