Posts Tagged Java

Finding Your Center

Way back when I was in high school my typing teacher (yes, on a mechanical typewriter) taught us how to center blocks of text on a page. This has been a useful skill as I got into web development and programming as not everything has a built-in “center” alignment property.

I have never been asked how to do this, so it may be common knowledge, but I thought I would share anyway since I have not been blogging much. Basically, think about your viewing area as a page and what you are centering as a rectangle drawn on that page. Now fold that page in half and you will see that half of your rectangle is contained on half the page… makes sense. You are finding the horizontal position (x coordinate) of the left edge of your rectangle by subtracting half of its width from half the width of the page:

1
x = [page_width]/2 - [item_width]/2

or after a little simplification

1
x = ( [page_width] - [item_width] )/2

This is exactly the same way you would center vertically. The equation from above expressed with more meaningful terms:

1
y = ( [page_height] - [item_height] )/2

Now to bring this into the Java world you can center a JFrame in the center of your monitor screen:

1
2
3
4
5
Dimension frameSize = new Dimension(800,600);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int x = (screenSize.width-frameSize.width)/2;
int y = (screenSize.height-frameSize.height)/2;
frame.setBounds( x, y, frameSize.width, frameSize.height );

Not too bad at all, but it has always surprised me that Swing does not provide helper methods to center components inside of other components.

Popularity: 1% [?]

  • Share/Bookmark

Tags: ,

Java Hosting?

I love Java. I love the language. I love the JVM and I love the ever-increasing list of languages that run on the JVM. One thing that I really don’t like is the high cost of hosting Java web applications. Yes, if you search around you can find some that say they provide Java hosting via Tomcat or Jetty, but unless you get a dedicated server you are not really getting much out of it and there tend to be a lot of limitations involved.

I pay about $72 annually for hosting, and with that I get very limited support for hosting Java web applications. Basically I get a shared Tomcat instance that I cannot configure or restart myself, which is pretty useless beyond very simple applications. I don’t even have java command line access to run my own server from my account. In order to get true, useful, Java hosting you need to bump up your monthly cost quite a bit. Real Java hosting generally starts around $300 per year and goes up from there if you really need to get serious with it (adequate RAM, and JVM configurations). Google App Engine is on the right track but it’s limiting; you are limited to JPA or JDO and not even the full power of either of those along with other limitations. Where is the affordable yet functional Java web hosting for the developer or hobbyist with no real budget?

I then decided to look into some of the other web development languages and found that Ruby (on Rails) has a lot of the same issues with good inexpensive hosting. That struck me as odd since I would think RoR would have lower memory and system requirements. I also looked into Python and found that there seems to be very few options available for it. The big winner in the hosting support I guess should come as no surprise… PHP. PHP has come standard with every hosting package I have ever had or have ever really looked into… at no extra cost. I guess this is why it remains to be so popular.

I think I will have to dig deeper into PHP for some of my personal web projects. If not that, I may have to look at setting up my own server outside my firewall, which just brings up all kinds of other problems.

Popularity: 3% [?]

  • Share/Bookmark

Tags: , ,

My Final Answer

I use the Java ‘final’ keyword quite a bit and I often get asked why. I guess the quick answer would be, “why not”?

I tend to use ‘final’ for instance variables, method parameters and local variables. The keyword can also be used to make classes and methods final but I leave that for the cases when I actually want that specific functionality.

Final instance variables (private fields) are useful for case when you want to specify the value once and then never again. This is helpful when configuring an object through Constructor dependency injection:

1
2
3
4
5
6
7
8
9
10
public class MyController implements Controller {

    private final MyService myService;

    public MyController(final MyService myService){
        this.myService = myService;
    }

    // other methods
}

This allows you to configure the service object in the controller and not have to worry about any of the other methods overwriting it.

Using final for method parameters is quite handy since it keeps you from unexpectedly overwriting one. Consider the following code:

1
2
3
4
5
6
7
8
9
public int count(List<String> list, String name){
    int count = 0;
    Iterator<String> names = list.iterator();
    while(names.hasNext()){
        name = names.next();
        if(name.equals(name)) count++;
    }
    return count;
}

which contains a possibly hard to find variable overwrite error, which becomes quite obvious when you use final

1
2
3
4
5
6
7
8
9
public int count(final List<String> list, final String name){
    int count = 0;
    Iterator<String> names = list.iterator();
    while(names.hasNext()){
        String nme = names.next();
        if(nme.equals(name)) count++;
    }
    return count;
}

Local variables are made final for basically the same reason.

Now, I know that simply because a variable is final does not mean it’s internal data cannot change, such as

1
2
3
final Map<String,Date> dates = new HashMap<String,Date>();
dates.get("Anniversary"); // will work fine
dates.put("Birthday");    // will work fine

The final keyword does not make them immutable, you just cannot overwrite them. Final makes you think a bit before overwriting a variable with a new object and it can sometimes point out, and save you from, potential bugs.

Eclipse Save Actions

Making your IDE do the work for you. If you use Eclipse (or one of its derivatives) you can have it automatically add ‘final’ to your code. Go into the Preferences and search for “Save Actions” and you should get something like what is show here. I generally auto-final method parameters and local variables since I have found that making private fields final can cause issues with some reflection and/or byte-code manipulation techniques.

Once you have the save actions setup, you will automatically have final added every time you save a file. I would imagine IntelliJ and NetBeans both have some similar functionality available.

Ultimately, the use of final comes down to personal preference. I find it useful and helpful to use the final keyword throughout my code. If you don’t then you really don’t have to use it unless you find a case where it’s absolutely necessary. To me, though, I figure why not use it?

And that’s my final answer.

Popularity: 4% [?]

  • Share/Bookmark

Tags: , , ,

Groovy Unit Testing: Tools

The Java Metroplex User Group meeting last night was a presentation on unit testing and mocking with Groovy, presented by Venkat Subramaniam, a well-known author and consultant… and a great presenter to watch, by the way. In his presentation he showed various techniques for using Groovy to write unit testing for both Java classes and other Groovy classes.

Count me among the converted, but I was not sure just how easy it would be to bring Groovy into a Java project while still maintaining good Eclipse and Maven support. So, I did a quick little experiment and found out that the integration is trivial.

Say you have a maven project, we’ll call it “groover”, already hapily running maven under Java 6 and Maven 2. Add the following dependencies (assuming you dont already have JUnit 4):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.6</version>
    <type>jar</type>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy</artifactId>
    <version>1.7.0</version>
    <type>jar</type>
    <scope>test</scope>
</dependency>

You now have maven setup to run unit tests written in Groovy (assuming you have Groovy 1.7 installed locally as well).

To get everything working in Eclipse, import your project (if it’s not already in Eclipse) and be sure you have the Groovy Eclipse plug-in installed. You may also want/need the Maven Eclipse plug-in, but that is not a requirement. Once the project is imported, right click on the project name and convert it to a Groovy project. Now Eclipse is ready to go too.

Let’s proove that it works by writing a simple little class and a Groovy test for it:

1
2
3
4
5
6
7
package foo;

public class Something {
    public String doIt(String in){
        return in.concat(" gabadata!");
    }
}

and then the test is:

1
2
3
4
5
6
7
8
9
10
11
12
package foo

import org.junit.Test
import static org.junit.Assert.*

class SomethingTest {
    @Test
    void doIt(){
        def result = new Something().doIt('foo')
        assertEquals "foo gabadata!", result
    }
}

Run the test using Ctrl+Alt+X T (normal JUnit run command in Eclipse) and it works just like any other JUnit test. Run the test in a console with maven with “mvn test” and it still works just like normal.

My next thought was that surely it would not work with my coverage tools! I was wrong, coverage worked fine in both the IDE and in maven.

So, by writing unit tests in Groovy I get to write less code, have built in powerful mocking support, and no tool integration issues? Sign me up!

Popularity: 47% [?]

  • Share/Bookmark

Tags: , , ,

Shortcutting Search Loops

A simple mistake I have seen a lot is not breaking out of a search loop once you have found what you are searching for. Take the code below, for example:

1
2
3
4
5
6
7
8
9
10
11
public User findUser(String name){
    User foundUser = null;
   
    for( User user : product.getUsers() ){
        if( name.equals(user.getName()) ){
            foundUser = user;
        }
    }
   
    return foundUser;
}

This code will loop through every user even after you have found the user you are looking for, which for large sets of data can get very inefficient. You can shortcut the loop with a break statement:

1
2
3
4
5
6
7
8
9
10
11
12
public User findUser(String name){
    User foundUser = null;
   
    for( User user : product.getUsers() ){
        if( name.equals(user.getName()) ){
            foundUser = user;
            break;
        }
    }
   
    return foundUser;
}

which will drop the control out of the loop once your user has been found. You could also simply return the user when found, such as

1
2
3
4
5
6
7
8
public User findUser(String name){
    for( User user : product.getUsers() ){
        if( name.equals(user.getName()) ){
            return user;
        }
    }
    return null;
}

This version causes there to be two exit points in the method, which is often frowned upon. Personally, I don’t see a problem with this in short simple methods.

Lastly, if you are a couple levels deep in a loop and cannot simply use a “return” for some reason, you can use a label to break out of the loop. Consider this example of a Map of Lists (something that you generally should not do):

1
2
3
4
5
6
7
8
9
10
User foundUser = null;
Iterator<List<User>> lists = users.values();
finder: for( List<User> list : users.values() ){
    for( User user : list){
        if( name.equals(user.getName()){
            foundUser = user;
            break finder;
        }
    }
}

which will break out of the loop labeled “finder” (the outer loop).

There are, of course, other ways of breaking out of loops, but these are the most general and cleanest, in my opinion.

Popularity: 2% [?]

  • Share/Bookmark

Tags: , ,

…Try Try Again

After yesterday’s post, If At First You Don’t Succeed…, I thought of a slightly different approach to the retry execution method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public <T> T execute( final Retriable<T> op ) throws Exception {
    for(int r=0; r<maxRetries; r++){
        try {
            return op.execute();

        } catch(final Exception e) {
            if( ArrayUtils.contains(catchAndThrow, e.getClass()) ) throw e;

            if(log.isWarnEnabled()){
                log.warn("RetryCaughtException[" + r + "]: " + e.getMessage());
            }
        }  
    }

    if(log.isWarnEnabled()) {
        log.warn("RetriesFailed: " + op.getClass().getName());
    }    

    throw new MaxRetriesExceededException(maxRetries,op.getClass().getName());
}

This approach does not rely on the boolean to end the loop. If an exception is thrown it will try again until a return value is returned or the retry count has been exceeded. With this approach you only fall out of the loop on a retry exceeded condition, hence the logging and the thrown exception. This feels a little cleaner than the other approach.

I have not run it through the unit testing so, you might do that first if you intend to use this code.

Popularity: 2% [?]

  • Share/Bookmark

Tags: , , ,

If At First You Don’t Succeed…

Sometimes you run into an operation that is a little on the flaky side and might sometimes fail on one execution but then work fine on the next; apart from fixing the underlying issue which may not be within your control, you can implement an operation retry strategy. With an operation retry strategy you attempt to execute an operation and then retry it if it fails. After a specified number of attempts (or under certain exceptions) you can allow the operation to fail gracefully. This gives you greater isolation of the questionable service while also allowing you more control what happens on a failure.

I have run into this issue a few years back with a twitchy SMTP server, and now again with a slightly-flaky database connection pool. Last time I wrote a very code-specific retry strategy (and like a doof, never blogged about it), but this time something more reusable is in order since this component would be used extensively throughout the code.

Basically the requirement is the ability to run a repeatable operation some number of times until it either succeeds or exceeds a specified number of attempts, at which point it will stop trying and fail. Since there are no closures in Java yet, I came up with a Retriable interface with a single method which will execute the operation and return it’s return value if there is one.

1
2
3
public interface Retriable<T> {
    public T execute() throws Exception;
}

I had originally considered using java.lang.Runnable; however, a return value simplifies cases where you are trying to extract some value from the operation. Similarly I considered the org.apache.commons.lang.Closure class and discarded if for the same reason.

The retry logic itself is pretty straight-forward. The failure condition is based on exceptions thrown by the operation execution. If an execption is thrown that is not contained in the “catchAndThrow” list, the counter will be incremented and the operation will be tried again if the max number of tries has not been exceeded. The “catchAndThrow” list is an array of Exception classes which if caught are to be thrown out of the handler rather than initiating a retry. This allows some desired exceptions to be handled by the calling method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public <T> T execute( final Retriable<T> op ) throws Exception {
    boolean retry = true;
    int count = 0;
    do {
        try {
            return op.execute();

        } catch(final Exception e) {
            if( ArrayUtils.contains(catchAndThrow, e.getClass()) ) throw e;

            retry = ++count < maxRetries;
            if(log.isWarnEnabled() && !retry) {
                log.warn("RetriesFailed[" + op.getClass().getName() + "]: " + e.getMessage(), e);
            }
        }
    } while( retry );

    throw new MaxRetriesExceededException(maxRetries,op.getClass().getName());
}

You will notice that if all the retries fail, a MaxRetriesExceededException is thrown. This allows calling methods to catch and handle the case when total failure occurs in a method-specific manner.

A more advanced retry strategy could also be derived from this where the failure condition is based on an injected object (ala strategy pattern) so that other criteria could be used to determine success and failure. The exception catch and throw filter could also be enhanced in this manner.

The retry object itself, which I have called the Retrier is a reusable thread-safe POJO so it can be configured via dependency injection (Spring) and used for any number of Retriable operations.

1
2
3
4
5
6
7
8
<bean id="retrier" class="retry.Retrier">
    <property name="maxRetries" value="3" />
    <property name="catchAndThrow">
        <list>
            <value>java.lang.NullPointerException</value>
        </list>
    </property>
</bean>

What you end up with is a very clean way to perform retiable logic:

1
2
3
4
5
6
7
8
final long id = someBeanId;
final String criteria = searchCriteria;

SomeBean resultBean = retrier.execute( new Retriable<SomeBean>(){
    public SomeBean execute() throws Exception {
        return searchDao.findBean(id,criteria);
    }
} );

In this sample code a searchDao is being called in a retriable manner using parameters from the calling method. As long as parameters are final they can be passed into the anonymous inner class craeted by the inline creation of the Retriable. You will also see that with the use of generics you get a seamless integration of the retiable operation into your code.

Currently, I do not have this code in any of my projects, though it would be a good addition to my CodePerks-Lang project (which is as of now, still unreleased). I have included a downloadable zip file containing the source code (including unit test) for this example.

Popularity: 3% [?]

  • Share/Bookmark

Tags: , , ,

Abominable Nested Collections

The dreaded nested collection, one of the most vile creatures in the lazy-development arsenal. What’s wrong with nested collections? Nothing, if they are required to solve a problem… everything if they are used as the lazy-man’s domain object or data transfer object. Consider this case where you have AddressBeans being mapped to their zip code and then again to their state:

1
Map<String,Map<String,AddressBean>> map = getAddresses();

or worse yet, back in the pre-Java 5 days:

1
Map map = getAddresses();

How meaningless is that? In the second case you will probably stumble over that Map a few times before you even figure out what’s in it, or you will have to trace down into the code and see what’s being put into it.

Code should be straight-forward and expressive. When you find yourself writing a Collection of Collections (or arrays or maps), step back and look at the larger picture. Do you really need such a complex construct? If so, does it really need to be so general that the caller must figure out it’s meaning?

Generally the answer is no. This example could easily be replaced with a wrapper object, say AddressGroup that may internally still use the nested collection, or some other storage mechanism that the caller really does not care about as long as the data is accessible. This wrapper object would also provided a richer less error-prone means of accessing the data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class AddressGroup {

    private Map<String,Map<String,AddressBean>> addresses;
   
    public AddressBean[] getAddressesForState(String state){
        // return the addresses for the selected state
    }
   
    public AddressBean[] getAddressesForZip(String zip){
        // return the addresses for the selected zip
    }
   
    Iterator<AddressBean> addresses(){
        // return an iterator over all addresses
    }
   
    // other accessors as needed
}

With this wrapper object, we now have a much more meaningful statement:

1
AddressGroup addressGroup = getAddresses();

The point here is that there is nothing stopping you from writing your own “collection objects” that can be used to abstract away some of the nastiness of complex raw data structures. Doing this reduces the complexity of your code while at the same time making it easier to read and understand.

Popularity: 1% [?]

  • Share/Bookmark

Tags: , , ,

XML Serialization

Another pair of those seemingly forgotten classes in the core Java API are the java.beans.XMLEncoder and java.beans.XMLDecoder. Added in 1.4, they don’t really seem to be used all that much, that I have come across anyway. It seems that whenever someone needs to convert objects into xml, they instantly reach for 3rd-party libraries rather than looking in the core API. Not to downplay other APIs, but I do think XMLEncoder and XMLDecoder deserve consideration, especially when you simply need to export data objects in a simple and repeatable manner.

First off, we need something to work with, how about a nice Person class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Person {
    private String firstName, lastName;
    private short age;

    public Person(){ super(); }

    public Person(final String firstName, final String lastName, final short age){
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String getFirstName() { return firstName; }

    public void setFirstName(final String firstName) { this.firstName = firstName; }

    public String getLastName() { return lastName; }

    public void setLastName(final String lastName) { this.lastName = lastName; }

    public short getAge() { return age; }

    public void setAge(final short age) { this.age = age; }

    @Override
    public String toString() { return firstName+" "+lastName+" ("+age+")"; }
}

It’s nothing special, just first name, last name and age with getters and setters. I also overrode the toString() method so we can get something useful from it.

Now say you are in a situation where you need to quickly convert objects of the Person class to a format usable by another client (maybe another programming language); as much trouble as XML can be a times, it is still a good interoperability choice. Converting a collection of Person objects to XML is trivial:

1
2
3
4
5
6
7
8
final Collection<Person> people = new LinkedList<Person>();
people.add( new Person("Joe","Smith",(short) 32) );
people.add( new Person("Abe","Ableman",(short) 54) );
people.add( new Person("Cindy","Lindy",(short) 42) );

final XMLEncoder encoder = new XMLEncoder( outputStream );
encoder.writeObject(people);
encoder.close();

Which will generate the following XML in the given output stream:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.6.0_13" class="java.beans.XMLDecoder">
 <object class="java.util.LinkedList">
  <void method="add">
   <object class="foo.Person">
    <void property="age">
     <short>32</short>
    </void>
    <void property="firstName">
     <string>Joe</string>
    </void>
    <void property="lastName">
     <string>Smith</string>
    </void>
   </object>
  </void>
  <void method="add">
   <object class="foo.Person">
    <void property="age">
     <short>54</short>
    </void>
    <void property="firstName">
     <string>Abe</string>
    </void>
    <void property="lastName">
     <string>Ableman</string>
    </void>
   </object>
  </void>
  <void method="add">
   <object class="foo.Person">
    <void property="age">
     <short>42</short>
    </void>
    <void property="firstName">
     <string>Cindy</string>
    </void>
    <void property="lastName">
     <string>Lindy</string>
    </void>
   </object>
  </void>
 </object>
</java>

Yeah, it’s not pretty and it’s a bit on the verbose side, but it was easy to produce and easy to read. Now, if you want to read that back into Java objects, it it equally as simple:

1
2
3
final XMLDecoder decoder = new XMLDecoder( inputStream );
final Collection<Person> persons = (Collection<Person>)decoder.readObject();
decoder.close();

which will give you back copies of your original objects. If you were to call toString() on the resulting collection you would get:

[Joe Smith (32), Abe Ableman (54), Cindy Lindy (42)]

Exactly what you put in.

Obviously, this is not the best approach for serializing and deserializing data, but it’s another tool in the tool box and I am always surprised by how few developers actually know that they are avaialable.

Popularity: 1% [?]

  • Share/Bookmark

Tags: , ,

MessageFormat Goodies

The java.text.MessageFormat class is, in my opinion, underutilized. It is what org.springframework.context.MessageSource implementations use under the covers to provide message formatting, so they are probably used quite a bit, but do you really let them do what they are made to do… formatting? I am guilty of it to; you convert a Date object to a formatted string before handing it off to a MessageSource or MessageFormat instance… but no more.

I wrote a quick little format dumper to show what each type of formatting prints out:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Object[] params = new Object[]{ new Date() };
out.println("Dates:");
out.println("  default:\t" + format("{0}",                 params) );
out.println("  short:\t"   + format("{0,date,short}",      params) );
out.println("  medium:\t"  + format("{0,date,medium}",     params) );
out.println("  long:\t\t"  + format("{0,date,long}",       params) );
out.println("  custom:\t"  + format("{0,date,d MMMM yyyy}",params) );

out.println("\nTime:");
out.println("  default:\t" + format("{0,time}",         params) );
out.println("  short:\t"   + format("{0,time,short}",   params) );
out.println("  medium:\t"  + format("{0,time,medium}",  params) );
out.println("  long:\t\t"  + format("{0,time,long}",    params) );
out.println("  full:\t\t"  + format("{0,time,full}",    params) );
out.println("  custom:\t"  + format("{0,time,HH:mm:ss}",params) );

params = new Object[]{ new Float(31415.967F) };
out.println("\nNumbers:");
out.println("  default:\t"  + format("{0}",                  params) );
out.println("  integer:\t"  + format("{0,number,integer}",   params) );
out.println("  currency:\t" + format("{0,number,currency}",  params) );
out.println("  percent:\t"  + format("{0,number,percent}",   params) );
out.println("  custom:\t"   + format("{0,number,#,###.0000}",params) );

Note: I used static imports for System.out and MessageFormat.format so that I could minimize the code noise. For the same reason, I pulled the format label text outside of the formatting call; they could have easily been done as:

1
out.println( format("  short:\t{0,time,short}",   params) );

It just seemed easier to see the formatting the other way.

When I ran my format dumper I ended up with:

Dates:
  default:	11/23/09 7:59 PM
  short:	11/23/09
  medium:	Nov 23, 2009
  long:		November 23, 2009
  custom:	23 November 2009

Time:
  default:	7:59:37 PM
  short:	7:59 PM
  medium:	7:59:37 PM
  long:		7:59:37 PM CST
  full:		7:59:37 PM CST
  custom:	19:59:37

Numbers:
  default:	31,415.967
  integer:	31,416
  currency:	$31,415.97
  percent:	3,141,597%
  custom:	31,415.9668

I am going to make a point to use these from now on, rather than converting manually beforehand.

Popularity: 6% [?]

  • Share/Bookmark

Tags: , ,

Switch to our mobile site