Tuesday, February 19, 2008

Eclipse: Sysdeo Tomcat Launcher

I have found myself in the position to work on a lot of J2EE based web solutions as of late. While not necessarily the area that I like to work in, it is paying the bills. So to continue with my Eclipse focused articles leading up to EclipseCon, I wanted to look at the Sysdeo Apache Tomcat launcher.

I like the Eclipse J2EE tools a lot. In fact, outside of BIRT, WTP is probably one of my more used toolsets in the Eclipse environment. There are just times where it is “overkill”. Also, every now and again I run into library loading issues when launching an app in Eclipse for a web environment where Sysdeo works around that. Sometimes you don’t want a huge Eclipse environment, so a small, 3rd part plug-in fits the bill nicely, and this is where Sysdeo comes into play..

http://www.eclipsetotale.com/tomcatPlugin.html

Installation:

Extract to Eclipse Plugins folder

That’s it, your installed and ready to rock and roll. There are additional steps involved with getting the DevLoader classes installed, but I never use those.

When done, you will see a set of icons for starting, stopping, and restarting Tomcat from within Eclipse.

Now, I need to set up my Tomcat location. I go to Window/Preferences

In the dialog, I go to the Tomcat section, and choose the options to locate Tomcat and the version I am using.

Next, I go to the JVM settings option and set up the Java Virtual Machine.

Now, it is ready for use.

Usage:

In the following example, I am going to import a web project I use as a baseline. The app consists of several JSP pages, and some core libraries. I will skip the steps of importing the actual application since they don’t apply, I will just jump into the configuration of the project for Tomcat.

The first thing I want to do is right-mouse click on my project, and go to properties. Under the property dialog, I want to go to the Tomcat section, and check the option that this is a Tomcat project. I also want to set up the context I will use.

When I hit OK, a new menu will appear for my project when I right-mouse click on it in the Project Explorer. From this menu, I want to choose to add the Tomcat Libraries to my project.

I also will choose the Update context definition to add this project to Tomcat. I do hit one other snag at this point before I can actually run my project. I need to manually copy my Java libraries and compiled class files to the Tomcat folder physically. I copy all the class structures under my BIN folder to /Shared/classes and all the JAR files to /Shared/lib. That takes care of it, now I can start Tomcat and work with my app.

I typically use Sysdeo for simple web apps, JSP based solutions, or solutions with simple classes. Anything more and I will fall back to using WTP.

Tuesday, February 12, 2008

Eclipse: Instantiations SWT Designer, GWT Designer, and RCP Developer

I'm speaking at EclipseCon 2008

Continuing on with my Eclipse centered articles, I am moving on to yet another set of tools I use quite often with Eclipse. Now, while I prefer not to do “product” endorsements, I do have to say I like using the Instantiations Window Builder series of products. In particular, I have been using the RCP Developer (well, more of the SWT Developer) and the GWT Designer products as of late. To put them into perspective, Instanatiations has a series of products that provide a simple, RAD type interface designers for a series of platforms, such as Swing, SWT, RCP and GWT. At last years EclipseCon, I won both a copy of GWT Designer and RCP Developer, which I mainly wanted to evaluate. RCP Developer, at the time, was my primary focus since I was tasked with building an RCP based application (I wrote on this previously 1, 2). However, I have since just been using the SWT Designer that came with it.

Figure 1. Designer Window

Figure 1 shows a screenshow of the Designer Window. This is where SWT Designer really gains its utility from. Having to hand code interfaces is a pain, so being able to quickly whip up an interface visually leads to cleaner visual designs and allows for rapid prototyping of visual interfaces. Here, you see the WYSIWYG designer that you would expect from most visual development environments nowadays, with a component palette next to a designer. You have components at your disposal, such as standard buttons, layout managers, text boxes, list and combo boxes, groupings, and menus. Here I have used a free form layout and built a simple interface, with buttons to connect to servers and edit server info, a code snippet insert below that, a large textbox in on the right, and the option to send a command to the a server. The designer also has the option to quickly test the interface without needing to compile or run (no functionality is provided), to quickly align components, and a quick little tool to externalize strings used in components. There is also a outline view to accurately select a correct component to work with and change properties. This is useful if you have many nested components.

Figure 2. Property Editor

Figure 2 shows the property editor. Here I have selected the Execute button. In the property editor, I can change things like the size, text displayed on the button, name of the button object, if it displays an image, and any other visual elements of the button.

Figure 3. Event handlers

If you double click on any component, or right-mouse click and choose add event handler, it will create a new event handler. Double-clicking adds a default handler (in the case of Buttons, widgetSelected). If you use the context menu, you have more control. In Figure 3, I have a widgetSelected event handler already, and am creating a mouseHover event handler. This will automatically import the correct class to use, and create a new instance of it in the addListener method, as seen in Figure 4.

Figure 4. Inserted Event Handler

Unlike with GWT Designer or RCP Developer, SWT Designer does not add a new launch command to Eclipses launch window, which is fine since SWT applications are Java applications anyway. It does, however, create a new Project type, and a number of new project file types, such as an Application Window, Dialog, and Shell.

Figure 5. New Types

RCP Developer provides similar mechanisms for RCP based applications, as does GWT Designer. The biggest differences are the inclusion of different launch mechanisms. With the GWT Designer, the launch mechanism not only launches, but will give you the ability to launch from within Eclipse and debug in Eclipse. With the new project wizard and this launch mechanism, it replaces the manual launch creator that I had previously illustrated.

Figure 6. GWT launch Mechanism

Figure 8. GWT Run Dialog

Figure 9 shows the designer for GWT Designer. As you can see, it is almost identical to the SWT Designer, except that it contains a GWT project, and uses the GWT Design components.

Figure 9. GWT Designer

In addition. GWT requires a little further configuration than either RCP Developer or SWT Designer in that you need to configure the location of the GWT libraries. This is available under the Window/Preferences dialog, under Designer/GWT.

Figure 10. Configure GWT Location

I will avoid my gripes about the license fees since they are more of personal gripes because I am cheap and have more or less spoiled myself with OSS offerings, and in no way reflect on the quality of the products themselves. Some programmers have to eat and pay the bills too, and these products have enabled me to build some cool little apps quickly, so I feel the price is worth it. If you’re at EclipseCon 2008, check out the Instantiations booth to see what else they have to offer. Maybe they will run the games they did last year to win a copy of the above mentioned products.

Sunday, February 03, 2008

Eclipse UML

I'm speaking at EclipseCon 2008

Since we are ramping up for EclipseCON 2008 at the end of March, I’ve been working a little more in Eclipse and getting a feel for the different Eclipse projects so I can attend some other presentations while I am there. I figured, since I am presenting again this year, I might as well take advantage of my presence there and learn a little more about the various Eclipse projects. Last Year I wrote about EasyEclipse and the PHP editor, which was a life saver for a PHP based project I worked on last year. This year, I want to focus on the Performance and Logging tools, and the UML tools.

I have made it well known in the past that I have been incredibly disappointed with the UML tools that are part of Eclipse. Previously they had no graphical interface, which was crap, and one would have to rely on third party plug-ins and projects. Of which many decent ones have surfaced, such as ArgoUML. But again, if something is to be part of the Eclipse Foundation, it should have a certain standard it should have to meet. I suppose I have been spoiled in the past by tools such as Rational Rose.

However, it seems that Eclipse UML has undergone some renovations in later versions. Finally, a graphical interface it present, and it is approaching a usable point for everyday projects. In the following example, I will walk through building some example diagrams.

Figure 1. UML Diagrams

Figure 2. Class Diagram

In Figure 2, I have put together a Class Diagram. This is a standard UML diagram showing the relationships between multiple classes, the properties and the methods of the classes. In this class diagram, I only showed associations and attributes. In Class Diagrams you have associations (linked to relationships), aggregations (whole/part relationships), and generalization/specialization (superclass/subclass relationships) associations.

Figure 3. Activity Diagram

I wont go into too much detail about the remaining diagrams, such as the Deployment Diagram. I had noticed the Activity Diagram has more activity types than in the last version of Rational Rose I had used (which was Rose 2000). I did notice several other diagram types that were absent, such as the Use Case Diagram, Swimline diagrams, and such. And while reverse engineering and code generation are noticeably absent, I feel that Eclipse UML is definitely heading in the right direction.

Wednesday, January 16, 2008

Java: Using JRat under Eclipse

I'm speaking at EclipseCon 2008

Recently I was working on a Java based program that hooked into an indexing process to make modifications to the data it was indexing. In this case, it was stripping out HTML formatting and removing unnecessary whitespace. Because this was a Java app, performance was dismal. Under normal circumstances I would have gone with a platform that would provide better native support for my platform, such as C, C++, or even a scripting language like Perl would have sufficed. However that was outside of the requirements for this project.

So to improve performance, I needed a profiler to track down my performance bottlenecks. I tried the Eclipse Performance and Logging tools, only to be really disappointed with the results. And by disappointed, I mean that I received errors when running the Eclipse profiler so I couldn’t get any kind of results. So, my search for an alternative lead me to JRat.

JRat is fairly easy to use. To Launch an application for profiling, you simply append an argument to the Java VM. From Eclipse, this can be done from the Run Dialog, under the Arguments tab.

To demonstrate this, I am using the Prime Number example (not sure why I called it Factorize). The code I am using contains both the unoptimized prime number list and the optimized one. The code is below:


package com.digiassn.blogspot;

import java.util.ArrayList;
import java.util.List;

import java.util.Iterator;

public class Factorize {

private static int MAX_NUMBER = 10000;

public boolean isPrime(int number)
{
if (number == 1)
return false;

for (int x = 2; x < number; x++)
{
if ((number % x) == 0)
{
return false;
}
}

return true;
}

public List getFactors()
{
List factors = new ArrayList();

for (int x = 2; x < MAX_NUMBER; x++)
{
if (isPrime(x))
{
factors.add(x);
}
}

return factors;
}

public List getFactors2()
{
boolean [] list = new boolean[MAX_NUMBER];
List l = new ArrayList();

for (int x = 0; x < MAX_NUMBER; x++)
{
list[x] = true;
}

list[0] = false;
list[1] = false;

for (int x = 2; x < MAX_NUMBER; x++)
{
if (list[x])
{
for (int y = (x * 2); y < MAX_NUMBER; y += x)
{
list[y] = false;
}

l.add(x);
}
}

return l;
}

/**
* @param args
*/
public static void main(String[] args) {
Factorize f = new Factorize();

List l = f.getFactors();
List l2 = f.getFactors2();

for (int x = 0; x < l.size(); x++)
{
if (!((Integer)l.get(x)).equals((Integer)l2.get(x)))
{
System.out.println("Something didn't match" + l.get(x) + " " + l2.get(x));
}
}

System.out.println(l.size());
System.out.println(l2.size());
}

}


In the below screenshot, I have jRat installed under C:\Jrat.

Figure 1. Adding JRat to your Eclipse Run

That’s basically it, when you run the program, you will see a whole bunch of output from the console.

Figure 2. Console output

When run with Jrat, it will save its statistics to a file under the project folder that you will need to open in JRat in order to view your statistics. To run JRat to view statistics, you would run the following command:

java -jar shiftone-jrat.jar

Figure 3. The JRat Window.

Above is a screenshot of the file generated by JRat opened and sorted by percentage of time spent in a method. I can see that unoptimized getFactors method is where the program spent a majority of its time, were the optimized getFactors2 barely spent any time at all.

To be fair, this doesn’t offer nearly as much analysis as the Eclipse Profiler. The Eclipse Profiler has the option to test memory allocation sizes as well as execution time, and it provides some very nifty outputs, such as the ability to export class interations into UML diagrams, as shown in the below screenshot.

Figure 4. The Eclipse Profile Perspective.

While I like JRat, I did find a few things I didn’t like. The biggest one is that is isn’t a Eclipse plug-in. While this is actually a pro as well as a con, I have to admit a certain amount of lazyness on my part, and having to jump outside of Eclipse to view my results can be a little annoying. I suppose a plug-in could be built to view these results, however. Next, is the release schedule is a little inconsitent. As of this writing, the last stable release was on 2007-09-11, and before that, it was 2006-07-31. Yikes. I hope the project is still viable.

So if you get into a situation where the Eclipse profiler refuses to work with your application, you might want to give jRat a try.

Wednesday, January 02, 2008

BIRT: Creating Event Handlers in Java

I'm speaking at EclipseCon 2008

Strange, although I wrote about it in this article, I never wrote an article on how to use Java classes as Event Handlers in BIRT. I probably was meaning to, but it was one of those things that slipped my mind. Its taken me a few weeks, but I am slowly coming out of perpetual daze from a series of excessively demanding jobs, the book writing, and the wedding over the past 6 months.

So, in this article we are going to look at how to create an external event handler in Java, and how to get BIRT to call it. I will look at using this in the Eclipse environment only, with a brief explanation on how to get the class to work in a BIRT deployed environment.

1: Start a new Java project called MyEventHandler.


2: In your project, be sure to include the libraries from the BIRT Runtime.



3: Create a new class called CountingScriptedEventHandler. Be sure to include a package, otherwise BIRT will not recognize it. I am not sure why that is the case, it just will not. The class must inherit the org.eclipse.birt.report.engine.api.script.eventadapter. ScriptedDataSetEventAdapter class.



4: Using Eclipses built in Override/Implement method utility, available from the Source menu, pick the fetch and open methods to implement.




5: Use the following code for the Event Handler:

package com.digiassn.blogspot.birt.handlers;

import org.eclipse.birt.report.engine.api.script.IUpdatableDataSetRow;
import org.eclipse.birt.report.engine.api.script.ScriptException;
import org.eclipse.birt.report.engine.api.script.eventadapter.ScriptedDataSetEventAdapter;
import org.eclipse.birt.report.engine.api.script.instance.IDataSetInstance;

public class CountingScriptedEventHandler extends ScriptedDataSetEventAdapter {
int count = 0;

@Override
public boolean fetch(IDataSetInstance dataSet, IUpdatableDataSetRow row) {
try {
if (count < 10)
{
row.setColumnValue("count", count);

count++;

return true;
}
} catch (ScriptException e) {
e.printStackTrace();
}

return super.fetch(dataSet, row);
}
}


6: Save your file. Exit Eclipse and reenter (not sure why the event handler won’t show up without this step, but it won’t). Now, create a report project called MyEventHandlerReport.
7: Create a new report called myEventReport.rptDesign.
8: Add in a new Scripted Data Source.


9: Create a new scripted Data Set. Create a single column called count.



10: Select the data set. In the Property Editor, select the Event Handler tab. Click browse and select the event handler from the list.



11: Now, select the data set in the Data Explorer, and drag it over to the Report Designer.



Save and run the report.



Well, that’s cool and all, but how do we get report parameters into this guy. Lets say we wanted the user to able to limit the count themselves instead of using a hardcoded number. Well, we need to get access to the Report Context object, which is not available in the open or fetch method. So instead, we need access to the BeforeOpen method in the parent class. Rewrite the event handler like so:

package com.digiassn.blogspot.birt.handlers;

import org.eclipse.birt.report.engine.api.script.IReportContext;
import org.eclipse.birt.report.engine.api.script.IUpdatableDataSetRow;
import org.eclipse.birt.report.engine.api.script.ScriptException;
import org.eclipse.birt.report.engine.api.script.eventadapter.ScriptedDataSetEventAdapter;
import org.eclipse.birt.report.engine.api.script.instance.IDataSetInstance;

public class CountingScriptedEventHandler extends ScriptedDataSetEventAdapter {
int count = 0;
int MAX_NUM;

@Override
public boolean fetch(IDataSetInstance dataSet, IUpdatableDataSetRow row) {
try {
if (count < MAX_NUM)
{
row.setColumnValue("count", count);

count++;

return true;
}
} catch (ScriptException e) {
e.printStackTrace();
}

return super.fetch(dataSet, row);
}

@Override
public void beforeOpen(IDataSetInstance dataSet,
IReportContext reportContext) {

super.beforeOpen(dataSet, reportContext);

if (reportContext.getParameterValue("MAX_NUMBER") != null)
MAX_NUM = (Integer)reportContext.getParameterValue("MAX_NUMBER");
else
MAX_NUM = 10;
}
}


Next, I create a report parameter of type Integer called MAX_NUMBER.



Now, when I run the report, and put in the parameter, it controls the number of results I see.

Thursday, December 27, 2007

Development: Optimize Prime Number Search Using Sieve of Eratosthenes

For some reason I have been playing one of those online games where you have a series of hacking or programming related challenges to pass. The most recent challenge I did was one involving a series of silly computations on large numbers involving retrieving all of that numbers preceding prime numbers. Not too difficult, however, performance was a key component of the exercise since you had to have your program give an answer in under 3 seconds. And to add to my frustrations, I decided to do the whole thing in Java due to Javas utilities for network communication.

First, I figured I would take the input number, loop through all numbers up to it, and add any prime number to a List. What resulted was something like below:

import java.util.ArrayList;
import java.util.List;


public class BadPrimer {

/*
* Generic prime number check
*/
public boolean isPrime(int number)
{
if (number == 1)
return false;

for (int x = 2; x < number; x++)
{
if ((number % x) == 0)
{
return false;
}
}

return true;
}

/**
* Find all prime numbers before number
* @param number
* @return
*/
public List findAllPrimes(int number)
{
List l = new ArrayList();

for (int x = 2; x <= number; x++)
{
if (isPrime(x))
{
l.add(x);
}
}

return l;
}

public static void main(String[] args) {
BadPrimer p = new BadPrimer();

List l = p.findAllPrimes(8000000);
for (java.util.Iterator i = l.iterator(); i.hasNext();)
{
Integer number = (Integer)i.next();
System.out.println(number);
}
}

}


Needless to say, that was not quite up to task. Worked great on small numbers, but for numbers in the area of 8,000,000 or so, it was just horrendously bad. So, back to the drawing board. My next thought was, why not generate the list of primes beforehand. But generating the list took just as long, and wasn’t very efficient. There are things I could have done to speed things up, but the bottom line was this just wasn’t efficient enough.

So I had to hit the books a little and find some of those really old school math algorithms that weird Greeks came up with thousands of years ago to do large calculations without the aid of computers. What I came up with was the Sieve of Eratosthenes, a way of taking a set of numbers in a list, and eliminating numbers that aren’t prime numbers, really quickly. So, with pre-generating a list of Prime numbers using the found algorithm, my next attempt looked like this:

import java.util.Arrays;

public class BadPrimer {
public int [] primeArray;

/**
* using the sieve of Eratosthenes algorithm, quite cool actually
*/
public void buildPrimeSet()
{
int MAX_SIZE = 10000000;

//create a boolean array and set all elements to true
boolean [] numArray = new boolean[MAX_SIZE];
Arrays.fill(numArray, true);

//we already know 0 and 1 are not prime numbers, so ignore them
numArray[0] = false;
numArray[1] = false;

//x will be out driving prime loop, y will be the elimination loop
for (int x = 2; x < MAX_SIZE; x++)
{
//if x is still true, it is a prime, and we need to keep it
if (numArray[x])
{
//advance our inner loop, starting at twice the current position of x, and start dividing
//If you use y++ as the counter advance, the generation takes to long
for (int y = (x * 2); y < MAX_SIZE; y += x)
{
//if y is already false, dont bother setting
if (numArray[y])
{
numArray[y] = false;
}
}
}
}

int totalCount = 0;

//find the total number of primes
//this could be done in the above loop, but for logic
//illistration, I kept it here
for (int x = 2; x < MAX_SIZE; x++)
{
if (numArray[x])
{
totalCount++;
}
}

//create our array based on the number of primes
//and populate the array with the prime numbers
//Note: there are better ways of doing this, such as adding
//the prime numbers in the above loop when they are found, but
//I did it this way for logic reason, not efficiency
primeArray = new int[totalCount];
int pos = 0; //a position counter
for (int x = 2; x < MAX_SIZE; x++)
{
if (numArray[x])
{
primeArray[pos] = x;
pos++;
}
}
}

/**
* Find all prime numbers before number
* @param number
* @return
*/
public int findAllPrimes(int number)
{
//using x as our arary position
//go through the list until the value in our
//array is greater than the number used. We now have the cut off position
//to mark all prime numbers lower than our current number
int x = 0;
while (primeArray[x] <= number)
{
x++;
}

return x;
}

public static void main(String[] args) {
BadPrimer p = new BadPrimer();

p.buildPrimeSet();
int primeCutOff = p.findAllPrimes(31337);

for (int x = 0; x < primeCutOff; x++)
{
System.out.println(p.primeArray[x]);
}
}

}


I saved you a lot of the iterations I went through. The final chunk above was after learning quite a few things. First, working with primitives is much faster than working with objects. I abandoned the idea of using a List of integers and instead went with an Array of integers. This made a large improvement in performance since I didn’t have to do any conversions of object types, and I found out the hard way that Java will take int from a List and convert them to Integer objects. The second biggest thing was eliminating unnecessary iterations in my loops. At first, I was going through the inner loop in buildPrimeSet() using y++ instead of y+=x. This wasted a lot of iterations since the most a number divided by something else will do is halve it (integer wise). So if x was 50, it didn’t make sense to test 51 – 99 since they aren’t valid multiples of X, and that kind of defeats the purpose of the Sieve of Eratosthenes algorithm, which states to eliminate numbers that are multiples of the current prime.

So, the end result, what took hours to run before gets run in a matter of milliseconds now. Valuable lesson... I might need to brush up on some of my algorithm development skills. Regardless, this took care of the first part of the calculation in finding all the prime numbers for the requested number, the remaining parts will remain a mystery so I don’t give away the answer to the challenge.