Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Wednesday, April 28, 2010

PowerMock - Mocking Statics - Supplemental Documentation

I have recently suffered through a bit of pain working with PowerMock.  It seemed extremely promising, as it sits on top of EasyMock, which we use for mock objects in our unit tests (it also works with Mockito, apparently), and promises to give you the tools to mock those pesky static calls that kill testability.  I had a few issues getting started, and they centered around jUnit 3.

PowerMock with jUnit 3

All the examples and documentation seem to be based on jUnit 4. This page has great examples on how to run your static mocking tests when running on jUnit 4, but how to do it on jUnit 3??  An extremely simple example of how to do this in jUnit 4 is here:


@RunWith(PowerMockRunner.class)
public class AwesomeTest {

  @PrepareForTest(StaticClass.class)
  public void testDoExecute() throws Exception {
    ...
    PowerMock.mockStatic(StaticClass.class);

    expect( StaticClass.doStuff( param ) ).andReturn( "yo!" );
    replay( StaticClass.class );

    //test some stuff!
  }
}


To accomplish the same thing in jUnit 3, without the annotation support, you can do this:



public class MyPowerMockSuite extends PowerMockSuite {

  public static TestSuite suite() throws Exception {
  
    return new PowerMockSuite(AwesomeTest.class);
  }
 
  public static void main(String[] args) throws Exception {
  
    junit.textui.TestRunner.run( suite() );
  }  
}

public class AwesomeTest {

  @PrepareForTest(StaticClass.class)
  public void testDoExecute() throws Exception {
    ...
    PowerMock.mockStatic(StaticClass.class);

    expect( StaticClass.doStuff( param ) ).andReturn( "yo!" );
    replay( StaticClass.class );

    //test some stuff!
  }
}



PowerMock and Multiple Classes

To mock methods from multiple classes, you will need to amend the '@PrepareForTest' annotation, just passing a string array like so:



public class MyPowerMockSuite extends PowerMockSuite {

  public static TestSuite suite() throws Exception {
  
    return new PowerMockSuite(AwesomeTest.class);
  }
 
  public static void main(String[] args) throws Exception {
  
    junit.textui.TestRunner.run( suite() );
  }  
}

public class AwesomeTest {

  @PrepareForTest({StaticClass.class,StaticClassier.class})
  public void testDoExecute() throws Exception {
    ...
    PowerMock.mockStatic(StaticClass.class);

    expect( StaticClass.doStuff( param ) ).andReturn( "yo!" );
    replay( StaticClass.class );

    PowerMock.mockStatic(StaticClassier.class);

    expect( StaticClassier.doStuff( param ) ).andReturn( "yo!" );
    replay( StaticClassier.class );

    //test some stuff!
  }
}


Gotchas

PowerMock 1.3.7 only works with EasyMock 2.5.2, which we have had some issues with.  I had to move back to PowerMock 1.2.5 to use EasyMock 2.4.  I didn't find a lot of issues with using this version, though we had some odd calls that were required where it told me not to stub a return when the method returned something, or where I had to stub out calls that didn't seem like they should be required.  With a simple static method that didn't really call many other static methods, it seems to work like a charm.

Sunday, April 19, 2009

Like OMG! Google App Engine Supports Java! SHUT UP!!

Ever since last week's announcement that Google App Engine would officially support Java, there have been no less than 2,002,555,1111 blog posts and articles written on the subject. Let this one be the one that says

WHO CARES

Seriously. Who cares? Has ever an announcement caused so much excitement? This is hardly the most exciting thing to happen in the world of software. It's someone announcing that their platform that isn't THAT exciting to begin with supports a hacked version of your language...color me less than exciting. It's neat. It's neat like the Macbook Air is neat. Nobody needs it, and certainly I'd think that nobody needs to drop everything to create a tutorial for how every single framework in the whole world interacts with Google App Engine.

It just seems like there are way better things to talk about. I guess it's shiny thing syndrome, but I just don't see the big deal. Google would probably counter by saying 'hey look at all the people excited about it - there must be something there!'. I say, once the shine comes off of it, a new toy will likely replace the excitement around this.

Tuesday, March 31, 2009

Romans, Calendars, Java, and Bad Bugs

Well, I learned today that Java is not smart enough to figure out that if there aren't 31 days in a month, just to go to the last day. Now I may be the last self-respecting Java developer on the planet to figure this out, but if not, here's a tip:

1) use the roll() method to push an element of the date forward, without affecting the other days.
2) Don't instantiate your GregorianCalendar and then just add a month, because if you move to April 31, it automatically becomes May 1. Instead, you can also just create a new Calendar with the day set to 1, and then new month set correctly.

Java, you vex me so. What a terrible bug by me. And without the benefits of unit tests, not something I ever would have found out until we hit a 31st day of a month, or until we reached January and went into February with it's 28 days. Sigh.

Friday, March 20, 2009

Struts 2 Error Reporting Tips

As I wrote before, Struts 2 isn't the best framework for error handling or notification. I think for the most part the entire framework is an incredible improvement over Struts 1, which had so many silly moving parts that just made it a genuine pain in the ass to work with. Struts 2 is simple, and I take well to the Action-As-Bean pattern used here. Moreover, it's what we use, so I had to learn to deal with the oddness of it. Since I wrote that post, I have come up with/implemented a couple handy tricks:

1) Display the Error Details on the Error Page

Obviously I didn't invent this, but we weren't doing it yet, so here's what I did:

You will likely create a global error mapping. In the action that you map to, add this code that will trap the error details:

Throwable error = (Throwable) request.getAttribute("javax.servlet.error.exception");

request.setAttribute( "errorCause", error.getCause().toString() );
request.setAttribute( "errorMessage", error.getMessage() );
request.setAttribute( "errorStackTrace", error.getStackTrace() );
Now you can insert a little line into your error page that shows the error, instead of having struts swallow it up forever.

<%= if ( request.getAttribute( "errorMessage" ) != null { %>

-- print out the data --

<% } %>

2) Debug Better

If you get the source code for Struts 2, you can add it to your Eclipse project, and insert a breakpoint in the following piece of code in com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept():

public String intercept(ActionInvocation invocation) throws Exception {
String result;

try {
result = invocation.invoke();
} catch (Exception e) {

/* BREAKPOINT HERE */

if (logEnabled) {
handleLogging(e);
}
List exceptionMappings = invocation.getProxy().getConfig().getExceptionMappings();
String mappedResult = this.findResultFromExceptions(exceptionMappings, e);
if (mappedResult != null) {
result = mappedResult;
publishException(invocation, new ExceptionHolder(e));
} else {
throw e;
}
}

return result;
}
This way you can see if something weird happened inside struts that didn't get reported in the logs. Boom, you can see if there is some mysterious internal error getting thrown, rather than trying to divine it using rain dances and crossed fingers. These two things have really improved my experience with Struts. If I were a better person, I would upgrade to see if it's fixed, and if not, I'd probably add some decent logging.

Bonus Tip

If your application starts up, but you are getting invalid results from your struts action, like the "no result defined for action" message, make sure your source control tool didn't merge incorrectly and add a double mapping for the action. We ran across this recently, where an old mapping was included, and was picked up first. Perhaps there should be a way to tell Struts2 to error out and fail if it finds the same mapping twice in a file? Just something to watch for.

Happy Strutting!

Saturday, March 7, 2009

Garbage Collection, Tomcat, Hibernate, and You

java.lang.OutOfMemoryError: PermGen space

If you are using Sun's Hotspot JVM, maybe you've seen this in your log file, and you don't know what to do. Maybe this will help.

Ever since we upgraded at work from Hibernate 2.1 to 3.2, we have been fighting memory management issues. Some of those can probably be traced back to increased traffic, some probably to odd legacy code that can be refactored pretty easily, and much of it relates to Hibernate and cgLib. There are endless blog posts about this, so if you want to read about the way cgLib, Hibernate, and the Perm region of the JVM heap interact, google away.

To break it down, here's how to know you may run across a problem:
/bin/jps
This will give you a listing of running JVM instances on your machine. Tomcat presents as:
xxxx Bootstrap
this is the JVM pid that you can use to check out memory utilization. Now run the garbage collection util to see what's going on in your heap:
jstat -gcutil
You will be presented with the following:












S0S1EOPYGCYGCTFGCFGCT GCT
0.0031.5860.1357.7699.6626475.19262.1147.306

The measures above give you space utilization in percentage of the regions of the JVM memory space. For a detailed explanation of this, check out the official Sun paper on the topic. For our purposes, we will do a quick overview:

S0 and S1 are both survivor spaces.
E is Eden space.
O is Old space.
P is Perm space.

When an object is created, it lives in Eden space. If it makes it past a garbage collection while still containing an active reference to it, it will move on to Survivor space. From there, if it's still actively referenced, it moves on to Old space. Garbage Collections of Eden and Survivor spaces are not the big garbage collections - the are the Young Garbage Collections (YGC). Once something gets into the Old space, it can only be removed by a Full Garbage Collection (FGC). You can see from the above table that a YGC is not expensive - 2647 of them were performed in a total of 5.192 seconds, while just six full collections take 2.114 seconds. Finally, there is the Perm space. This is where the JVM structures and class objects are put. The classloader sticks stuff here to help you so it doesn't have to constantly load and reload these structures. The problem is that if you have a lot of these things, it's going to just keep sticking things in there until it's full.

There are a couple of ways to combat this issue:
  1. Maybe you haven't increased the default size of the Perm space. You can do that by adding this JVM flag to your startup script: -XX:MaxPermSize=m. To give some perspective, the default is 32m.
  2. Look at your classpath. Are you loading a LOT of libraries in? Do you need them all? Perhaps you can remove some of those libraries.
If you still have problems with Perm space after making the above changes, try these JVM arguments and see if you have any more issues.

-XX:+UseConcMarkSweepGC -XX:+CMSPermGenSweepingEnabled -XX:+CMSClassUnloadingEnabled
Whereas we were constantly hovering around 99.88% perm space utilization prior to these changes, now we are usually back down around 60%, so an extraordinary event in the system won't trigger an outofmemory situation. Hope this helps.

Thursday, February 19, 2009

Reading Feeds using the ROME API

A recent task had me doing something pretty simple - reading some RSS feeds for display on pages inside our application.  I know that it's easy enough to just write some custom code that parses an RSS feed - after all it's just XML, right?  I didn't want to do that, so I did some digging, and found two real options - ROME, and Commons FeedParser.

It quickly became obvious that ROME was the correct choice, and that's when the fun started. ROME is a Sun project that seemed to provide the most flexibility as far as reading different syndication formats, and clarity of API docs.  Using this tutorial from the site, getting the feed and parsing it was really really easy.  Just pass a feed url to the feed reader, and get some content items back.  

Loop through them and display the correct content.  


URL feedUrl = new URL( feed );

SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build( new XmlReader( feedUrl ) ;

List feedEntries = feed.getEntries();

There are some subtleties, however, that seemed to merit a post, as I didn't really find any clear explanations for these things in one place.

Issue 1:  Content Encoding

We are parsing a feed from a wordpress blog, and it seems that some posters always post content that has the weird characters that signify a content encoding issue.  The weird diamonds with question marks in them (or just empty boxes in Opera) that are inserted where there is a sort of 'half-space' on the actual blog.  I determined that the blog was using UTF-8 (this seems to be the default encoding for a WordPress instance.  After much searching, I came across this post, which seemed to contain about a million suggestions for how to handle the error.  What worked for some didn't seem to work for others, and certainly didn't work for me! I tried to read the url as a stream, and to no avail.  

Instead, I settled on setting the character encoding type on the HttpServletResponse object, which seems to take care of things.  Seems a little weird to me, but that's okay as long as it works and I don't have to write custom parsers.  After updating things, here's how my code looked:


URL feedUrl = new URL( feed );
String respEncoding = "";
if ( encoding == null )
{
encoding = "UTF-8";
respEncoding = "UTF8";
}
else
{
respEncoding = encoding.replaceAll( "-", "" );
}

XmlReader.setDefaultEncoding( "UTF-8" );

SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build( new XmlReader( feedUrl.openStream(), true ) ) ;

List feedEntries = feed.getEntries();

response.setCharacterEncoding( respEncoding );

Issue 2: Where's My Content?

The first blog I tested was easy to parse, once I got that list of feeds.  I just needed to to display the description field on the SyndFeedEntry object, and it gave me a nicely formatted (accounting for html inside the post) abridged posting.  Then I tried to display a blog that was hosted by the blogger platform (the very blog you are reading now).  Would you believe that the description property was unset.  No content. Now I am left having to get the raw content  straight out of the raw content feed.  I didn't really want an if-else for this in the display, and the way the SyndEntry was made, it wasn't really super simple to subclass it, so I went ahead and created my own class that took that SyndEntryImpl object and decorated with a few simple convenience methods:



/**
* Helper method to return the contents whether they come from the description field (ie wordpress is kind and does this) or raw content
* @return
*/
public String getAbridgedContents() {
//first try the description
if ( myEntry.getDescription() != null && myEntry.getDescription().getValue() != null )
{
return myEntry.getDescription().getValue();
}

//if that's not working, use the raw contents
StringBuilder sb = new StringBuilder();
SyndContent sc = null;

for ( int i = 0; i < myEntry.getContents().size(); i++ )
{
sc = (SyndContent) myEntry.getContents().get( i );
sb.append( sc.getValue() );
}

String ret = sb.substring( 0, 255 ) + " [...]";

return ret;
}

public String getDateString()
{
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, MMM d" );

return dateFormat.format( myEntry.getPublishedDate() );
}

public String getCatName()
{
if ( myEntry.getCategories() != null && myEntry.getCategories().size() > 0 )
{
SyndCategory sc = (SyndCategory) myEntry.getCategories().get( 0 );

return sc.getName();
}
else
{
return null;
}
}

public String getCatUri()
{
if ( myEntry.getCategories() != null && myEntry.getCategories().size() > 0 )
{
SyndCategory sc = (SyndCategory) myEntry.getCategories().get( 0 );

return sc.getTaxonomyUri();
}
else
{
return null;
}
}



Hopefully this will help people get their feedreader working quickly.

Wednesday, February 11, 2009

Fun and Games with Struts

I had a requirement for a project at work to insert some preprocessing into our Struts actions that will check to see if something fancy has to happen to decorate the page differently based on a branded association. I thought to myself, "hmm, that will be easy".  I was mostly right.  I have been working mostly with Struts 2 lately, which provides us with a handy dandy prepare() method to override, that is always called before the execute() method in a Struts 2 class that extends ActionSupport.  This is simple:

public class AwesomeActionSupport implements Preparable
{
private Integer integerToSet;
private Boolean someBool;

public void prepare() throws Exception
{
if( someBool )
{
integerToSet = new Integer( 1 );
}
else
{
integerToSet = 1;
}
}

public String execute()
{
System.out.println( integerToSet );

return SUCCESS;
}

//GETTERS/SETTERS FOR PRIVATE VARS ABOVE

}

As you can see it's quite simple when using Struts 2.  Sadly, most of the functionality in our application is still running Struts 1 for now.  This makes something easy much less simple.  There isn't really a built-in mechanism to make a pre-execution call.  Here's what I came up with:

public abstract class AwesomeAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
//do prep work
request.setAttribute( "whatever the action needs", theValue );
return perform( mapping, form, request, response );
}

/**
* A stub for performing the execute method, to be implemented by each
* individual struts action, after the execute pre-processing is performed
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public abstract ActionForward perform( ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception;
}
So now when you write your actual action class, instead of extending the Action class, you extend this action class that does the preprocessing, then delegates the real work to the perform method that you have to define.  Seems to work great, with the only caveat being you can't use a Dispatch action with multiple methods.  If you really want to do that, then upgrade your action/application to Struts 2!

Monday, May 12, 2008

Struts 2 Error Handling...How do I put it?

You could start with...

NOT THAT AWESOME.

There have been two things I have found now that are bizarre. Allow me to describe:

1) Let's say that you have a jsp mapped in your struts.xml, and it has an incorrect path somehow. Sure this is your fault, but what would you expect to happen:

A) An error on startup saying that the jsp can't be found?
B) An error when the action tries to forward to the nonexistent jsp?
C) A blank screen (even if the bad jsp call is inside a functioning jsp call by way of s:action?

Now, one would think that A or B would be good, normal ways for an error of this kind to be handled. You web application won't start if you have an invalid action class mapping, so why should it be different for a bad jsp mapping? But, even if we allow startup, (hey, maybe you will put the jsp in there later), shouldn't we throw some sort of error if we forward to a page that doesn't exist?

No, the answer is, C. A blank screen. No messages in the error logs. Awesome.

2) When you have properties on your form that don't map correctly to the variables or setters on your action class, should the framework:

A) Tell you that the action class call failed because the properties couldn't be mapped to an instance variable?
B) Be even more specific and catalog the properties that failed?
C) Tell you:

No result defined for action com.awesometown.SweetAction and result input - action - file: xxx
And fail without giving you any clue about what happened!

If you answered C, you'd be correct! Odd, but true, you should get an error message that tells you that your property can't map to the action class. What makes this particular situation even stranger is that when you have s:checkbox params that don't map to variables on the action, it warns you. So odd. Ah well. Other than that, Struts 2 is great and I think it's still a big improvement over Struts 1, even if you spend a bit of time banging your head on the wall. At least when you are done, you don't have to code an ActionForm.

Tuesday, May 6, 2008

"We're sorry. The lines are full."

So I tried to get Java hosting for my little startup that I am working on. I found out that they didn't support JDK5. Wow. That was only released like 4 years ago. Anyway, they didn't remedy the problem in a timely fashion (I can install Java 5 on a server in about 10 min), so I canceled. I want to get business DSL and a static IP address at home. It's about the same price as my current account, and I can write most of it off. So, I have to call Verizon right? Except 5 times now (3 last night and 2 this morning), I have gotten this message that says they are too busy to help me. And not just to let me know that I should wait on the line. No - their automated person hangs up on me! WHAT THE HELL IS THAT? I am willing to wait! I would like to wait patiently on speakerphone until someone has the time to help me. But NO. I have to keep on calling. Kudos Verizon. I am going to try RCN now to see if they have human beings who won't hang up on me. I hate the internets sometimes. Scratch that, just Verizon's control of the internets' wires near my house.

Thursday, April 17, 2008

Quartz - Job Processing Done Right

On our site, we have some background jobs that run periodically - we used JBoss to manage them, and it usually works. Sometimes they don't. The problem there is that once the job scheduler stops doing its thing, you can't really do anything but rerun the jobs periodically until you have a chance to bounce the server, which you can't do until night time (and obviously that isn't even particularly desirable). Well, today was one of those days. JBoss stopped running its scheduler, with nary a log message or stack trace. Just stopped. Yesterday it worked. Today, not so much. That sucks. We decided that it was a good time to untether ourself from JBoss and move to Quartz. In about a half of an afternoon, I had downloaded the code, perused the documentation, rewritten our scheduled processes to use Quartz, and tested and committed it. You can't often say that when you undertake something like this (believe me - we are currently in the testing stage of a long-overdue Hibernate 2-3 upgrade that hasn't been fun or easy), so I thought in honor of Quartz's simplicity and ease of use, I'd write a post, including how we got it working.

What is Quartz?

From their site:

"Quartz is a full-featured, open source job scheduling system that can be integrated with, or used along side virtually any J2EE or J2SE application"
How Do I Use Quartz?

Quartz is simple to use. To get started, download the distribution from their site, stick it in your classpath, and you are ready to go. First things first - you need to get your properties file set up. A simple configuration need only include this (or less if you want to fall back to defaults):

#===============================================================
# Configure Main Scheduler Properties
#===============================================================

org.quartz.scheduler.instanceName = QuartzScheduler
org.quartz.scheduler.instanceId = AUTO

#===============================================================
# Configure ThreadPool
#===============================================================

org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 5
org.quartz.threadPool.threadPriority = 5

#===============================================================
# Configure JobStore
#===============================================================

org.quartz.jobStore.misfireThreshold = 60000
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore


Once you have this going, you need to setup your jobs file. Most of the examples that came with Quartz show how to declare jobs in Java code. This is fine and all, but what if you don't want to have to recompile to change a quick setting? No good. I want to use XML. If you don't agree, feel free to follow one of the many examples they provide. To use XML, there are a couple things to keep in mind. First off - Quartz doesn't want to read these jobs from XML by default - you have to tell it to. In order to do so, you just need to add the following to quartz.properties:

org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.JobInitializationPlugin
org.quartz.plugin.jobInitializer.fileName = my-jobs.xml
org.quartz.plugin.jobInitializer.overWriteExistingJobs = false
org.quartz.plugin.jobInitializer.failOnFileNotFound = true


Then just create a file my-jobs.xml:

<?xml version="1.0" encoding="UTF-8"?>
<quartz xmlns="http://www.opensymphony.com/quartz/JobSchedulingData"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
overwrite-existing-jobs="true">

<job>
<job-detail>
<name>AwesomeProcessor</name>
<group>awesome-group</group>
<description>Run the awesome job</description>
<job-class>
com.sportsvite.AwesomeProcessor
</job-class>
<job-data-map allows-transient-data="false">
<entry>
<key>superbad</key>
<value>true</value>
</entry>
</job-data-map>
</job-detail>

<trigger>
<cron>
<name>awesomeTrigger</name>
<group>awesome-trigger-group</group>
<job-name>awesomeProcessor</job-name>
<job-group>awesome-group</job-group>
<!-- trigger every 30 min -->
<cron-expression>0 0/30 * * * ?</cron-expression>
</cron>
</trigger>
</job>
</quartz>

Pretty simple, right? That's all you have to do on the configuration side.

NOTE: When you deploy the code, make sure that these two files end up in WEB-INF/classes so they are picked up in the classpath.

Now you need to kick off the Scheduler somehow. Most of the exercises show you how to do it in the code, but we don't want to rely on that, right? If you are running in a servlet container, they give you a simple servlet, the QuartzInitializerServlet. It is included in the jar file, and all you have to do is add it to the web.xml:


<servlet>
<servlet-name>QuartzInitializer</servlet-name>
<display-name>Quartz Initializer Servlet</display-name>
<servlet-class>org.quartz.ee.servlet.QuartzInitializerServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

So we have told the Quartz scheduler to kick off a job called AwesomeProcessor, so we need to code the class. This is simple - you just need a class that implements the Quartz interface Job, and has the following method:

public void execute( JobExecutionContext ctxt )
{
String s = (String) ctxt.getString( "superbad" );
doFoo( s );
}

Note the use of the JobExecutionContext - you can use that to pass a bunch of arguments in a Map-like structure. It corresponds to the job-data element in the my-job.xml file.

Now when you fire up your server, the Quartz scheduler will activate and you'll see a message like this in standard out:

18:27:45,722 INFO [JobSchedulingDataProcessor] Scheduling 1 parsed job.
18:27:45,723 INFO [JobSchedulingDataProcessor] Adding job: awesome-group.AwesomeProcessor
18:27:45,735 INFO [JobSchedulingDataProcessor] 1 scheduled job.
18:27:45,735 INFO [QuartzScheduler] Scheduler QuartzScheduler_$_NON_CLUSTERED started.
18:27:45,736 INFO [Engine] StandardContext[]QuartzInitializer: Scheduler has been started...
18:27:45,736 INFO [Engine] StandardContext[]QuartzInitializer: Storing the Quartz Scheduler Factory in the servlet context at key: org.quartz.impl.StdSchedulerFactory.KEY

That's it! It's going to work now. The best thing about Quartz is that if you have bad XML or some other issue, it gives you a meaningful error message that you can easily remedy. Not all open source products can say the same.

Kudos to Quartz. It made my programming day pretty pleasant. Hope this helps others get up to speed. For a bunch of examples and other helpful information, check out the Quartz Wiki.

Wednesday, April 2, 2008

MacBookPro.Sweetsauce.Awesome.Computer.com

So. It happened. I got a MacBook Pro. Here at Sportsvite, the entire engineering team (yes all three of us) has Macbook Pros. Out of sheer computer envy, I kept watching my compadres on their fancy computers and thinking to myself "Man, I sure would be more productive if I had one of those." I think that in the back of my mind I knew that was BS, and I just wanted to have the same computer as them. I am here to say that I was right, and wrong.

What's Awesome

Old Computer (Core 2 Duo 1.66Mhz, Vista Home Premium) JBoss Startup: 90s
New Computer( Core 2 Duo 2.2Mhz, OS X Leopard) JBoss Startup: 16s
Old Computer Screen: 14in, 1200x800
New Computer Screen: 15in, 1440x900
Old Computer Startup: 2-3 min
New Computer Startup: 30-60 sec

The incredibly crisp seamless performance.

This whole .dmg file, where you open it and drop it into the Applications directory and it just works? Not bad!

The giant crisp display.

The smooth, quiet keyboard.

The dock. Nice.

The non-ridiculous power cord, and the magnetic connection to the computer that it uses.

Garageband. I have no clue how it works, but it will be a part of my guitar practice sessions for a while, until I do.

Adium. The little green duck is hilarious, and it seems be a really awesome simple chat tool.

What's Not So Awesome

Well for starters, where the hell is the right mouse button? I don't know, but I wish I could find it. Don't tell me to hit apple either every time I click. That's LAME.COM. But, I can look past this - I am sure all those devoted Mac snobs out there must look at it as a sign of their greater purpose and ability. I think it's kinda lame, but I am okay with it. Fortunately, there are USB ports, into which you can plug nice mice with all the buttons. Problem solved!

Installing Apache http server. This one was a tough one. This really sucked. A lot. Like on the suckiness scale, this one had to be about a 30 out of 10. Fortunately, my friend Bob showed me DarwinPorts, which seems to be awesome. They have all these ready made packages, and you just type things like port install apache2. True to its name, it does just that! Huzzah! By the way, I also hate mod_jk2, but oh well. It all works now.

Sudo. The idea of sudo sucks. I will have to get around to do setting it up so everything is done as root like I do on my linux box at home. Sudo is lame. Sudo just means you have to type a four-letter word before you do something catastrophically stupid. I don't like Sudo.

The apparently lack of the start menu like in Windows. I don't really like that either. I know I can use finder to get to Applications, but it's just not the same as being able to just get there from my screen. Again, likely something I'll figure out.

The fact that JDK6 isn't ready yet. Come on guys! Good thing I am not doing performance engineering anymore, since all those sweet tools like jmap, jhat, jstack, and jconsole were greatly improved in JDK6.

No pgUp or pgDn by themselves. Also no home or end. This is one place where my Toshiba really shines - it's got a great and friendly keyboard.

Replacing 'control' with this 'Apple' key, but not having it in the same place as 'Control' - that sucks. maybe there is some way to reroute the keyboard. I can see this causing so many problems.

More to come later

Friday, March 28, 2008

Java Hosting Solutions

So, I am looking for a place to host a Tomcat-based application for testing. While it's incredibly easy to find about a million solutions for LAMP hosting that all fall under 10/mo, I can't for the life of me find a hosting company that does Java hosting for under 15/mo. Color me cheap, but that seems like a lot! I don't need a dedicated server or anything - just a mysql database and tomcat 5.5+. Does anyone have hosting suggestions? Post any ideas in the comments if you do. Also, if anyone has any experience with Verizon business DSL for your home and static IPs, please feel free to share...

Monday, December 3, 2007

Web Applications and Memory Abuse

As a performance engineer, part of my job is to make our software run really really fast. Another part is to figure out how to make sure that it still runs as fast with 1000 users as it does with 10. That's usually the harder part. You can usually squeeze gains out of each transaction enough to make the single-user cases perform fine. Jeff Atwood describes it very well in this blog post. Says Atwood:
"Everything is fast for small n. Don't fall into this trap. It's an easy enough mistake to make. Modern apps are incredibly complex, with dozens of dependencies...The only way to truly know if you've accidentally slipped an algorithmic big O bottleneck into your app somewhere is to test it with a reasonably large volume of data."
As an example:

A big reason for poor scalability is the abuse of memory. Everything is faster when loaded from memory, right? That's always good, right? Matter of fact, why not put everything the user sees in their session? That way all they have to do is go straight to their own little section of memory so that everything they do is fast fast fast. Hmm. Good when the n is small. Bad when the n is big. Let's say, for kicks that every user session grows to 2MB. That's not unrealistic when considering some of the data-driven applications that you use on a day-to-day basis. Not so bad, right? After all, memory is cheap! Now, let's say your application is running on 32-bit Windows. For reasons explained here, you can only fire up a 1.5 GB JVM. So let's say you have 500 active users on your system. Do the math:

1500MB total heap size - 250MB server bootstrap - ( 500 users * 2MB session ) = 250MB for processing. Now things aren't looking so peachy, eh. However! We can just cluster, right, so we have multiple JVMs running, to take advantage of all that memory! Ha! In the words of Lee Corso, "Not so fast, my friend!". The default method of session propagation is simply to multicast the session changes across cluster nodes. Now you have 1GB of user-specific crap clogging up each of your JVMs. That leaves little heap for actual system processing needs. Now, factoring in the fact that most users don't proactively log out of systems, rather letting their session lapse to timeout, and the fact that many (non-financial) systems have rather long timeout intervals, you could have ALL THAT MEMORY just sitting there for users who may not even be in the same room as the computer that was associated with that session. Bad. Smokey says that "Only you can prevent forest fires". Well I am saying "Only you can prevent OutOfMemoryExceptions!" You could also put it like this: "Friends don't let friends bloat their sessions."

However you say it, you need to understand the trade off between saving processing time on the database and ruining the overall ability of your application server to respond to increasing numbers of sessions and requests.

Wednesday, October 17, 2007

Why Is It That If You Use An IDE You Aren't A 'Real Programmer'?

I was perusing dZone and I ran across an interesting blog post that applies the Pareto Principle to software developers. I agree with most of the sentiments shared by the author, but one thing got me:
"The 80% folks make up the bulk of the software development industry. They’re not stupid; they’re merely vocational. They went to school, learned just enough Java/C#/C++, then got a job writing internal apps for banks, governments, travel firms, law firms, etc. The world usually never sees their software. They use whatever tools Microsoft hands down to them — usally VS.NET if they’re doing C++, or maybe a GUI IDE like Eclipse or IntelliJ for Java development."
You see this opinion again and again in the nerdoblogosphere, and it's one of the silliest things you can say that would distinguish an accomplished programmer from an "80 percenter". I would consider myself part of the 20% that this author is referring to. I make decisions for my team to develop or refactor software that has direct impact to literally millions of students around the world. At my company we have a ton of really smart "Alpha developers" as this post refers to them. Guess what? All of them use Eclipse.

We don't use Eclipse because we are part of some herd that is shepherded through our careers by the big players like Microsoft, Oracle, BEA, IBM, or the Eclipse Foundation. We do it because it's easier. We do it because we could try to remember the exact method calls on String, and which argument does what, but we don't really feel like it. We do it because it allows us to refactor throughout a large codebase without pulling our hair out. We do it because we like the plugins that all those awesome "20 percenters" developed for us. We do it because we can use the debugger to figure out the problems that we would otherwise spend hours fixing by sifting through System.out.println() statements.

I can understand why people would postulate that IDEs make programmers lazy. This can be true in some respects. You should probably learn how to build programs and compile and execute at the command line. You certainly shouldn't be doing builds out of them, or using them as a production deployment tool. Some people can be misled into thinking that an IDE is all they need. That's not true at all, but writing good software is not just a matter of what tool you use (or don't). You can write terrible software in any editor, even vi! It's about understanding the business requirements, understanding how your users use the system, and how to create code that is easily reused and easily maintained. I just think that having a better holistic view of your codebase makes a world of difference. There are too many advantages to using IDEs to NOT use them.

But I could be wrong =)


Terracotta Clustering

A product I have been reading about is Terracotta. Currently at my company we use Tomcat's native clustering, which does session replication across all nodes - this is practical for many of our subsystems, but obviously it has to change your perspective on the way you use (abuse) the session for storage. A solution like Terracotta is great because you aren't replicating session across every JVM, and you don't have to deal with annoying things like making sure any object that is replicated implements java.io.Serializable. I hope to test it as part of some R&D for my company as a potential configuration. The architecture is explained by this diagram:

The architecture diagram would make it appear that in a clustered environment, you have introduced a single point of failure, which would be pretty counterintuitive, but of course, you can cluster the Terracotta servers as well. Effectively, Terracotta with its granular session update writes, configured in a clustered setup, should theoretically scale in a near-linear fashion. I am curious to see if this is the case. Furthermore, I am interested to see if we can integrate it with our application without having to completely hack the installer!

Some interesting links for anyone who is interested:

Interview with Terracotta
Terracotta Confluence Site
Terracotta from theServerSide
Terracotta's Scalability Story


I will post an update with my experiences.

Friday, October 12, 2007

Performance Engineering Reading

While performance engineering isn't necessarily entrenched at many companies (outside of a few people recording and playing back LoadRunner or SilkPerformer scripts), there are some really smart people writing about it in the 'interweboblogosphere'. A couple of things I am reading about today:

Coding Horror on "little n"
jsLex - A JavaScript Profiler - saw Mr. Buffone present at JavaOne - it's a neat tool and a great idea.