Posts Tagged ‘java’

Handling Session Timeouts (and other errors) using Ajax

Released January 11th, 2008

Ajax can bring a much more responsive and intuitive feel to web applications. However, many times developers overlook error cases when using Ajax. What if the request fails? In one particular case a user’s session may have timed out before they made an Ajax call. This post describes one such way of handling this in a somewhat friendly way.
(more…)

Tomcat + UTF8 + HTTP Get

Released March 19th, 2007

By default tomcat doesn’t UTF-8 encode get parameters like it does post parameters. This doesn’t seem to be the case with other application servers. So before you get yourself into trouble with your internationalized web application, make sure you make this change.

Hibernate and your Getters and Setters

Released March 11th, 2007

When you’re using Hibernate and are mapping to properties, keep your getters and setters as simple and self-contained as possible. The receiver being initialized may not have any other properties set, and the value being passed may not be fully initialized yet, either.

If you don’t respect these two possibilities, then you will get bit in the butt alot, when you least expect it. To be fair, these situations can happen whether you’re using Hibernate or not, but when we first started using the framework we made lots of assumptions.

Here is a completely ridiculous example that violates the above restrictions:
(more…)

Using the Hibernate API to Inspect Mapped Classes

Released August 2nd, 2006

For my current project we needed to audit the property setters Hibernate was using on our objects to make sure that any logic in them was not overly state dependent. More about this issue in Hibernate is available here. We have fairly rich object models, and a lot of methods, including setters, are never used by Hibernate. We wanted a report of the setters actually used by Hibernate to limit the amount of code we had to examine.

The Hibernate API allows you a lot of access to its configuration object model, and this is ideal for finding out how Hibernate is interacting with your code. I wrote a small class to do this inspection. The method below is run after a Hibernate Configuration object named creatively as “configuration” has been built with mapping files:

public Map findSetters() throws MappingException
{
  Map classToSetters = new HashMap();
  Iterator classMappingIterator =   configuration.getClassMappings();

  while(classMappingIterator.hasNext())
  {
    PersistentClass persistentClass = (PersistentClass)classMappingIterator.next();
    Class mappedClass = persistentClass.getMappedClass();
    Iterator propertyIt = persistentClass.getPropertyIterator();
    List classSetters = new LinkedList();

    classToSetters.put(mappedClass, classSetters);

    while(propertyIt.hasNext())
    {
      Property property = (Property)propertyIt.next();
      Setter setter = property.getSetter(mappedClass);

      classSetters.add(setter.getMethodName());
    }
  }
  return classToSetters;
}

I have uploaded a Java project that contains the full HibernateInspector class, as well as some sample classes and mappings. Un-tar it, and run

ant -Dhibernate.home="path to hibernate 3" 

to build and run the example.

accessing as400 databases with Ruby, Java, and the RubyJavaBridge

Released April 24th, 2006

iSeries systems and Ruby are separate universes right now; I know of no native Ruby way to connect to an AS400 system. However, with the help of Java we can bridge the gap.

Probably the simplest example is connecting to an iSeries system using JDBC to select from some tables, and with the right libraries it is straightforward. It’s also fun to be doing some nifty quick Ruby but with some preexisting and proven Java libraries.

Also, if you use Java and Ruby, definitely put arton’s RubyJavaBridge in your pocket; you’ll end up using it more than once.

What you’ll need:

  • Ruby (well yea)
  • Java (ok)
  • access to an AS400 system (that’s the whole point here…)
    For testing, I’ve been using a free account available from Holger Scherer Software und Beratung.
  • jt400.jar jdbc drivers from JTOpen, a great open-source Java library for AS400 access.
  • RubyJavaBridge is the keystone for this.

Installing the software is the hardest part of this exercise, but it’s more tedium than anything. Once you’ve got it all downloaded and running the fun can begin.

(more…)

Thread pooling with Java concurrency utilities new (java 1.5) and old (util.concurrent)

Released April 24th, 2006

Threading in java is fairly easy and now with java 1.5 some of the stuff that was harder has become even easier. A few years ago someone pointed me to a site that had some concurrency utils that where the precursor to what are now the concurrent utils in java 1.5. They are very close in functionality and if you can’t use java 1.5 the older version of the utils will work with older versions of java and give you a lot of the same functionality.

I’m going to give a quick thread pooling example using both the new and old concurrency utils. I picked the thread pooling out of both since that seems to be what I end up using the most out of all the new utilities. I may revisit this again at some point to go over the periodic executors or some of the other things I have used but just not as much.

(more…)

Using axis with https and a self signed certificate

Released April 8th, 2006

While developing a webservice based application we ran across some issues using a self signed certificate. After running our wsdl2java ant task we got the following error using Java 1.4:

sun.security.validator.ValidatorException: No trusted certificate found

Using Java 1.5 the error looks like this:

sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested targ

Fair enough. Java is telling us we need to import our self signed certificate into java:

/usr/local/java5/bin/keytool -import -alias mycert \\
  -file server.crt -keystore /usr/local/java5/jre/lib/security/cacerts
Enter keystore password:  changeit
... CERTIFICATE DUMP ...
Trust this certificate? [no]:  yes
Certificate was added to keystore

Running our ant task again:

java.io.IOException: HTTPS hostname wrong:  should be <localhost>
  at sun.net.www.protocol.https.HttpsClient.checkURLSpoofing(HttpsClient.java:490)
  at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:415)
...LONG STACK TRACE TRUNCATED....
</localhost>

(more…)

AJAX file upload progress for Java using commons fileupload and prototype

Released April 2nd, 2006

This has been done before with PHP (AJAX upload progress meter for PHP) etc but I needed something a little different because I wanted to upload a file and then have it loaded into a database. I looked around and found that someone had already made something that used the commons file upload package to do the upload part (AJAX Upload progress monitor for Commons-FileUpload Example). It wasn’t exactly what I was looking for but it a good start.

To understand the way this works I think it is easiest to break it down into parts:

  1. A file upload extention that counts bytes as they are uploaded
  2. An interface that monitors the progress of something running on the server
  3. AJAX to pull the monitoring into the current screen

(more…)

JDBC + Batch updates + Non-Standard == Oracle

Released February 11th, 2006

I recently ran into an issue where doing a large number of inserts and updates in an Oracle 8i database was taking forever. I was already using a prepared statement and commiting only after a certain number of rows. After some digging I found out that there is a special Oracle way of doing batch updates that made things a good bit faster. They do support the normal addBatch batch updates but it isn’t as fast as using their special way.

Here is an example of how to do things their way:

public static void doBatchInsert(List aLargeList, Connection connection) throws SQLException
{
  // You have to turn auto commit off, if you are doing a large set of inserts and updates you are probably doing this already.
  connection.setAutoCommit(false);

  PreparedStatement preparedStatement = connection.prepareStatement("insert into a_table(a_col) values (?)");
  // This is the magic. Set the number of statements to allow in one batch
  ((OraclePreparedStatement)ps).setExecuteBatch (10);

  int count = 0;
  for(Iterator i=aLargeList.iterator(); i.hasNext(); count++)
  {
    YourData yourData = (YourData)i.next();

    preparedStatement.setInt(1, yourData.getAnInt());
    preparedStatement.executeUpdate();

    if(count % 10 == 0)
    {
      // Send all currently queued statements
      ((OraclePreparedStatement)preparedStatement).sendBatch();
      connection.commit();
    }
  }

  ((OraclePreparedStatement)preparedStatement).sendBatch();
  connection.commit();
  preapredStatement.close();
}

For more information see the following link:
http://www.oracle.com/technology/products/oracle9i/daily/jun07.html

Commons Collections By Example: Maps

Released February 9th, 2006

I realized today just how much I used the Commons Collections library. Sure, there’s alot of anonymous inner classes, but after years of writing Swing I’ve gotten used to sort of crossing my eyes and looking past the syntactic cruft.

Here’s a silly example. Let’s map the names in the Greek alphabet to actual letters. Here’s our data

    Map nameToLetter = new HashMap();
    nameToLetter.put("ALPHA","a");
    nameToLetter.put("BETA","b");
    nameToLetter.put("GAMMA","g");
    nameToLetter.put("DELTA","d");

    String[] values = {"ALPHA","BETA","GAMMA","GAMMA","DELTA","EPSILON"};
    List valueList = Arrays.asList(values);

Let’s convert that valueList to the letters:

    Collection resultCollection = CollectionUtils.collect
    (
      valueList,
      TransformerUtils.mapTransformer(nameToLetter)
    );

    System.out.println(resultCollection);

>[a, b, g, g, d, null]

Hmm…how do we go back the other way….
(more…)