toString Velocity Template

1 min read

[@586]
toString Velocity Template

I'm using the excellent GenereateToString plugin to automatically create toString() methods in IDEA.

I've modified the default Velocity template as follows:

/**
* Returns a string representation of the object.
*
* @return A string representation of the object.
*/
public final String toString() {
final StringBuffer sb = new StringBuffer(super.toString());
#set ($i = 0)
#foreach ($member in $members)
#if (!$member.modifierStatic)
#if ($i == 0)
sb.append("[ ##
#else
sb.append(", ##
#end
#if ($member.string)
$member.name.replaceFirst("_", "") -> '")##
#else
$member.name.replaceFirst("_", "") -> ")##
#end
#if ($member.primitiveArray)
.append($member.name == null ? "null" : "");
sb.append('{');
for (int i = 0; $member.name != null && i < $member.name .length; ++i)
sb.append(i == 0 ? "" : ", ").append($member.name[i]);
sb.append('}');
#elseif ($member.objectArray)
.append($member.name == null ? "null" : Arrays.asList($member.name).toString());
#elseif ($member.string)
.append($member.accessor).append('\'');
#else
.append($member.accessor);
#end
#set ($i = $i + 1)
#end
#end
#if ($members.size() == 0)
sb.append("{}");
#else
sb.append(" ]");
#end
return sb.toString();
}

Here's an example of the code it automatically generates:

public class Test
{
  private String _name;
  private int _port;
  private String _url;
  private String[] _validIPs;
  // …
  /**   * Returms a string representation of the object.   *   * @return A string representation of the object.   */   public final String toString()   {     final StringBuffer sb = new StringBuffer(super.toString());     sb.append("[ name -> '").append(_name).append('\'');     sb.append(", url -> '").append(_url).append('\'');     sb.append(", port -> ").append(_port);     sb.append(", validIPs -> ").append((_validIPs == null) ? "null" : Arrays.asList(_validIPs).toString());     sb.append(" ]");
    return sb.toString();   } }

Here's a sample of what it returns:

Test@126b249[ name -> 'Test', url -> 'http://www.test.com', port -> 80, validIPs -> [127.0.0.1, localhost] ]

Overall not that many modifications from the default template:

  • The default template uses name=value, I use name -> value which I find more legible.
  • The default template prepends the class name, I prepend the super's toString() representation.
  • I also remove the underscore in front of field names, once again for legibility.
  • Finally, I added some javadoc comments.

Array Initialization

<1 min read

[@687]
Array Initialization

public class Example {
  public Boolean flags[] = new Boolean[4];
  public static void main(String[] args) {
    Example ex = new Example();
    System.out.println( "Flag 1 is " + ex.flags[1] );
  }
}

Yes, Flag 1 is null. I can't believe I forgot that.

Logging Packages with Log4J

1 min read
[@021]

The Pulse

Erik's Pulse has been published.

[@570]

Logging Packages with Log4J

I was looking for a way to log a specific package to its own file using Log4J. Took me a while to figure it out, but here's what I came up with in my log4j.xml file:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<!-- Main Rolling Log (by Size) --> <appender name="R" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="main.log"/> <param name="Append" value="true"/> <param name="MaxFileSize" value="10MB"/> <param name="maxBackupIndex" value="10"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss}] [%p] %m%n"/> </layout> </appender>
<!-- MyPackage Rolling Log --> <appender name="P" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="mypackage.log"/> <param name="Append" value="true"/> <param name="MaxFileSize" value="10MB"/> <param name="maxBackupIndex" value="10"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm:ss}] [%p] %m%n"/> </layout> </appender>
<!-- MyPackage Logger --> <logger name="net.thauvin.erik.mypackage" additivity="false"> <appender-ref ref="P"/> </logger>
<!-- Print only messages of priority INFO or above in the com.example package --> <category name="com.example"> <priority value="info"/> </category>
<!-- Root (Default) Logging --> <root> <priority value="fatal"/> <appender-ref ref="R"/> </root>
</log4j:configuration>

Incidentally, Log4j 1.2.13 was just released.

War of the Worlds

<1 min read
[@556]
War of the Worlds We finally watched War of the Worlds last night, thanks to Netflix. I can't believe that the same people who brought us Minority Report have produced such a yawner. This movie was all about special effects, and frankly, they weren't all that good. Especially the eye thing, which as been used and re-used in countless sci-fi movies. I was reading some of the reviews afterwards. Most movie critics are really clueless when it comes to the sci-fi genre. But since Spielberg directed it, they all pretty much liked it. The man can do no wrong. Some even had the audacity to compare it to Close Encounters. Please. Spielberg has made his share of crap, and you can add this one to the list.

iFit & iWorkout

2 min read

[@581]
Violation Notice Email

Hello Erik

We are sorry. The following question has been removed by our administrator due to violation of the rules.

Question: - Who's your daddy?

Details of Violation:

Reason of Violation: The act of guessing at a riddle and other exchanges unrelated to Knowledge Service : Please post a legitimate question.

Point Deduction: -0

If you feel you were not in violation, please contact our Customer Care and tell us why.

Yahoo! Answers Team

The correct answer was Angelina Jolie. Yahoo! Answers has no sense of humor.

[@461]
iFit & i2Workout

On Monday we received our new NordicTrack C2300 treadmill. I had to enlist a neighbour's help to take it up to be bedroom. I'm still pissed at Motor Cargo for only providing curb-side delivery. — Thanks Bill.

It took Vicki and I (yes, it is a two men's job) around 45 minutes to put it together. It came mostly assembled, except for the wheels, the console and the hydraulics.

I did my first workout on Tuesday morning. It's very silent and quite comfy, but I hate the presets (walk, jog, run). The custom options are a pain to setup too.

I decided to look into the iFit.com support. They do offer a few workout samples, but I'd have to hookup my laptop's audio to the treadmill to use them. CDs and MP3s are available at a cost. They also have premium services, which sound like a big joke to me.

Enters i2Workout, a nifty little shareware application that lets you create your own iFit-compatible workouts. It can export to MP3s (or CDs) with or without soundtracks.

I gave it a try last night with my Carbon, worked like a charm.