Archive

Posts Tagged ‘java’

Run JUnit test from the command line

December 23rd, 2012 No comments

JUnit tests can be run easily from within your IDE. Every remotely up to date IDE has some built-in view that gives nice visual feedback, usually red or green indicators.

But of course it is also possible to invoke your tests from the command line. A simple example:

import org.junit.runner.JUnitCore;

public class MyClass {
    public static void main(String[] args) {
        JUnitCore.main(MyJUnitTest.class.getName());
    }
}

A very nice article on JUnit testing by Lars Vogel can be found at http://www.vogella.com/articles/JUnit/article.html. He suggests iterating through the failures of a Result class to run the tests via code, which works fine, too:

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class MyClass {
    public static void main(String[] args) {
        Result result = JUnitCore.runClasses(MyJUnitTest.class);
        for (Failure failure : result.getFailures()) {
            System.out.println(failure.toString());
        }
    }
}
Categories: Uncategorized Tags: ,

Specifying file encoding when writing dom Documents

August 10th, 2011 2 comments

Assumed, we got a fully parsed org.w3c.dom.Document:

Document doc;
//parse doc etc...

Just using LSSerializer‘s writeToString method without specifying any encoding will result in (rather impractical) UTF-16 encoded xml file per default

DOMImplementation impl = doc.getImplementation();
DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
LSSerializer lsSerializer = implLS.createLSSerializer();
lsSerializer.getDomConfig().setParameter("format-pretty-print", true);
String result = ser.writeToString(doc);

will output

<?xml version="1.0" encoding="UTF-16"?>
...

Unfortunately, specifying an encoding isn’t trivial. Here are two solutions that don’t require any third party libraries:

1. Using org.w3c.dom.ls.LSOutput

DOMImplementation impl = doc.getImplementation();
DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
LSSerializer lsSerializer = implLS.createLSSerializer();
lsSerializer.getDomConfig().setParameter("format-pretty-print", true);

LSOutput lsOutput = implLS.createLSOutput();
lsOutput.setEncoding("UTF-8");
Writer stringWriter = new StringWriter();
lsOutput.setCharacterStream(stringWriter);
lsSerializer.write(doc, lsOutput);

String result = stringWriter.toString();

2. Using javax.xml.transform.Transformer

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(doc);
Writer stringWriter = new StringWriter();
StreamResult streamResult = new StreamResult(stringWriter);
transformer.transform(source, streamResult);        
String result = stringWriter.toString();
Categories: Uncategorized Tags: , ,

Multiple main methods in a single jar archive

May 13th, 2011 No comments

A Java archive file usually holds a manifest file that specifies the main class to start when you invoke java -jar jarfile. It’s something similar to this:

Main-Class: com.yourcom.package.MyClass

When you distribute your jar file, a user can simply execute it (possibly even with a double click) without knowing anything about your package structure or location of the main class.

But what if you want to execute a different main method in another class inside your jar file, maybe for testing purposes? Well, you don’t have to hack the manifest and re-package. Simply do

java -cp jarfile com.yourcom.package.MyClass

and the main method inside MyClass will be executed.

Categories: Uncategorized Tags:

Duplicate log4j output lines

June 28th, 2010 No comments

Ever seen duplicate lines in your log4j output? Maybe something like this:

2010-06-28 21:56:11,743 [main] INFO  org.quartz.impl.StdSchedulerFactory - Quartz scheduler version: 1.8.1
2010-06-28 21:56:11,743 [main] INFO  org.quartz.impl.StdSchedulerFactory - Quartz scheduler version: 1.8.1
2010-06-28 21:56:11,750 [main] INFO  org.quartz.core.QuartzScheduler - Scheduler MyScheduler_$_1 started.
2010-06-28 21:56:11,750 [main] INFO  org.quartz.core.QuartzScheduler - Scheduler MyScheduler_$_1 started.

Well, the obvious cause is probably duplicate loggers your log4j configuration:

log4j.rootLogger=INFO, DefaultConsoleAppender
log4j.logger.org.quartz=DEBUG, DefaultConsoleAppender

As the properties are inherited from the root logger, this is telling log4j that all quartz-classes should send their log to the DefaultConsoleAppender (which the root logger is doing anyway). So we simply have to remove the appender from the second logger definition:

log4j.rootLogger=INFO, DefaultConsoleAppender
log4j.logger.org.quartz=DEBUG

So watch your inherited log levels and appenders in your log4j configuration!

If anyone knows, why these duplicate lines appear from time to time in heavily multi-threaded environments (although log4j claims to be thread-safe) despite correct property files, please drop me a mail or leave a comment.

Categories: Uncategorized Tags: ,

Efficiently searching the Java API

June 17th, 2010 No comments

Since Sun’s API search is a real pain in the arse and even DocWeb doesn’t allow you to quickly search the Java API, this firefox plugin is a substantial improvement: https://addons.mozilla.org/en-US/firefox/addon/60675/

It basically redirects the search query to Google’s “I’m Feeling Lucky” feature to search Java’s API for the class information.

Together with Second Search querying the Java API is now lightning fast: https://addons.mozilla.org/en-US/firefox/addon/4096/

Categories: Uncategorized Tags: ,

Implementing equals() the right way

June 15th, 2010 No comments

At first sight, implementing equals() doesn’t seem fairly hard. Unfortunately, it turns out that writing a correct equality method is surprisingly difficult:

http://java.sun.com/javase/6/docs/api/java/lang/Object.html

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

In fact, after studying a large body of Java code, the authors of a 2007 paper concluded that almost all implementations of equals methods are faulty.1

There are quite a lot of HowTos available on the web. One of the best might be the article “How to Write an Equality Method in Java” by Martin Odersky, Lex Spoon, and Bill Venners.

So instead of repeating all the pitfalls you have to avoid, I’ll give you a sample implementation2 of the equals()-method that follows the general contract using the example of an imaginary class Point:

public boolean equals (final Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (this.getClass() != obj.getClass()) {
      return false;
    }
    final Point other = (Point) obj;
    if (this.x != other.x) {
      return false;
    }
    if (this.y != other.y) {
      return false;
    }
    return true;
  }

Be careful: Whenever you overwrite equals() it is generally necessary to override the hashCode()-method, too!

If you want to learn more about this topic, I suggest, you have a look at Joshua Bloch’s Effective Java Second Edition. Addison-Wesley, 2008.


[1] Vaziri, Mandana, Frank Tip, Stephen Fink, and Julian Dolby. “Declarative Object Identity Using Relation Types.” In Proc. ECOOP 2007, pages 54–78. 2007.
[2] http://www.artima.com/forums/flat.jsp?forum=226&thread=259279&start=30&msRange=15

Categories: Uncategorized Tags:

Using a HashSet in a thread-safe manner

June 13th, 2010 1 comment

Thread safety is a very hot topic for Java programmers right now. But I’ve seen quite a few folks using the rather complex collections from java.util.concurrent when they actually needed just a thread-safe implementation of a Set.

Of course, the HashSet implementation is non-thread-safe:

http://java.sun.com/javase/6/docs/api/java/util/HashSet.html

Note that this implementation is not synchronized. If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be “wrapped” using the Collections.synchronizedSet method. This is best done at creation time, to prevent accidental unsynchronized access to the set:

So getting a thread-safe representation of the HashSet class is pretty easy:

   Set s = Collections.synchronizedSet(new HashSet(...));

This returns a synchronized set backed by the specified set. But be careful: In order to guarantee serial access, it is critical that all access to the backing set is accomplished through the returned set.

A further pitfall is the use of the class’s iterator

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

So it is imperative that you manually synchronize on the returned set when iterating over it:

  Set s = Collections.synchronizedSet(new HashSet());
      ...
  synchronized(s) {
      Iterator i = s.iterator(); // Must be in the synchronized block
      while (i.hasNext())
          foo(i.next());
  }
 

Failure to follow this advice may result in non-deterministic behavior.

Categories: Uncategorized Tags:

Java plugin for Firefox 3.6

May 26th, 2010 No comments

Since Mozilla dropped support on OJI (Open Java Virtual Machine Integration), the classic java plugin file javaplugin-oji.so doen’t work anymore for Firefox versions >3.6. Starting in Firefox 3.6, Mozilla will only support the standard NPAPI and NPRuntime interfaces.

However, a ‘Next-Generation Java plugin’ (that’s what Sun calls it) is available in Java version 6 update 10 or newer and supports the NPAPI and NPRuntime interfaces.

Installation is quite simple. Remove the symbolic links to libjavaplugin_oji.so from the Firefox plugins directory and replace it with to libnpjp2.so:

cd ~/.mozilla/plugins/
rm -f libjavaplugin_oji.so
ln -s <JRE>/lib/i386/libnpjp2.so . 

where <JRE> is the path to your Java runtime environment.

Resources:
http://java.sun.com/javase/6/webnotes/install/jre/manual-plugin-install-linux.html

Categories: Uncategorized Tags: ,

log4j performance

May 6th, 2010 No comments

Log4J is the current de facto standard not only in open source development. It claims to be fast and flexible: speed first, flexibility second. But there are some pitfalls when it comes to the crunch.

The costs of a log request consists of a method invocation and an integer comparison. This is typically about 1-20ns (depending on your processor) per call. However, this does not include the “hidden” costs of parameter construction.
A simple example:

logger.debug("Value: " + x*y);

Regardless of whether the message will actually be logged or not, the parameter construction will cause additional costs. These costs of parameter construction can be quite high and depend on the size of the parameters involved.

To avoid the parameter construction costs:

      if(logger.isDebugEnabled() {
        logger.debug("Value: " + x*y);
      }
  

This will not incur the cost of parameter construction if debugging is disabled. On the other hand, if the logger is debug-enabled, it will incur twice the cost of evaluating whether the logger is enabled or not: once in debugEnabled and once in debug. This is an insignificant overhead because evaluating a logger takes about 1% of the time it takes to actually log.

So if speed is a real issue, you should double-check your logging statements for “hidden” costs.

Resources:
http://logging.apache.org/log4j/1.2/manual.html

Categories: Uncategorized Tags: ,

FileWriter, XML and UTF-8

November 15th, 2009 1 comment

Deep down in the Java-API:

http://java.sun.com/javase/6/docs/api/java/io/FileWriter.html

Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

So, if you want to write you XML-Document to a file, for the love of god, don’t use the FileWriter like this:

        BufferedWriter bufout = new BufferedWriter(new FileWriter(OUTFILE));
        bufout.write(out);
        bufout.close();

or you might end up with an XML-file that has a UTF-16 header (encoding="UTF-16") but is encoded completely differently (plain ASCII?! Not sure…).

Insted, use

                OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(OUTFILE),"UTF-16");
                out.write(s);
                out.close();

Resources:
http://www.malcolmhardie.com/weblogs/angus/2004/10/23/java-filewriter-xml-and-utf-8/

Categories: Uncategorized Tags: ,