Categories
Maven

Maven: “Error installing metadata”

Today I had a problem compiling and installing a simple maven project.
Every time I ran “mvn install” I received the following error:

Error installing artifact's metadata: Error installing metadata:
Error updating group repository metadata
input contained no data

The problem here was an empty maven-metadata-local.xml in my local repository of the artifact I wanted to install. After completely removing this artifact from my repository an install was possible.

Categories
Java

Using reflection with arrays and primitive types

Sometimes it is necessary to handle a parameter of type object different for the real type. So you have to use instanceof to determine the type of an object. If you are need to check if it is an array, you can use the Reflection-API provided by the JRE. The Reflection API is a comfortable and rich functional API to inspect and manipulate Objects at runtime. One example could be to access private fields at runtime.

I had the problem to serialize some variables to JavaScript, so I wrote me a simple function:

1
public void objectToJavaScript(Object object, StringBuffer buf);

If the given object is primitive I would simple add it to the provided StringBuffer, but if it is an array I need to output ‘[‘ and ‘]’ with the given parameters. So I have to check if the object is an array:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void objectToJavaScript(Object object, StringBuffer buf) {
    if (object == null) {
        buf.append("null");
        return;
    }
    ... //other types
    if (object.getClass().isArray()) {
        buf.append('[');
        //TODO output array content
        buf.append(']');
        return;
    }
    ...
}

But how to access each entry of the array? One way could be to cast the object to Object[]. Unfortunately if the array is an array of primtive types this would throw a ClassCastException. So we have to use the functions, provided by java.lang.reflect.Array. The full code looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public void objectToJavaScript(Object object, StringBuffer buf) {
    if (object == null) {
        buf.append("null");
        return;
    }
    ... //other types
    if (object.getClass().isArray()) {
        buf.append('[');
        int len = java.lang.reflect.Array.getLength(object);
        for(int i = 0; i < len; i++) {
            if (i > 0) buf.append(',');
            objectToJavaScript(java.lang.reflect.Array.get(object, i), buf);
        }
        buf.append(']');
        return;
    }
    ...
}
Categories
Java

comfortable thread pools using java.util.concurrent

Today I had another time the problem to execute many short tasks in a thread pooled environment. One way could be to write the pooling itselfs (like the other times in history ;)). But I thought: Why to reinvent the wheel every time and not using standardized libraries like the java.util.concurrent.*?

What I want:

  • A self enlarging and shrinking ThreadPool depending on the queued tasks. (Because sometimes it is nothing to do and sometimes it could be to get many hundreds of tasks in a short time)
  • A definable Limit of maximum running Threads (Because we cannot create hundreds of threads just for this task. Keep in mind: the tasks have a short run time)
  • Queuing the Tasks to run later, if the ThreadPool has reached the given limits

So I looked at the given Examples and the Executors-Class, which provides fast and simple methods:

  1. newCachedThreadPool : This looks good, but unfortunately you can’t define a maximum limit of threads.
  2. newFixedThreadPool : This handles the wanted limitation, but not the automatic enlarging and shrinking.

So we cannot use the predefined methods and need to instantiate ThreadPoolExecutor directly.

Categories
Javascript JQuery

Preloading Images with JavaScript

Sometimes in a complex javascript-application you want to display an image when it is fully loaded. Until then you want to show for example a common loading-imageAjax Loading Image. In this case the best solution is to load the image in background, and then show it to the use. For that you can use the Image-Class provided by the browsers.

This class is the used Class at img-Tags. So you have all known properties, like “src”. With the onload-Event you can then check, if the image was fully loaded or not. An example would be:

?View Code JAVASCRIPT
1
2
3
var image = new Image();
$(image).load(function () { alert("picture is fully loaded."); });
image.src="http://www.javahelp.info/wp-content/uploads/2009/11/Bild-80-300x64.png";

In the example I use JQuery for event-handling, because this is more comfortable as the normal event-method of JavaScript.

Categories
Java

Java 5 – End of Service Life (EOSL)

The Standard Service Life of Java 5 expired on Friday, October 30th. This is not really tradic, because Sun provides a Java SE 6 since December 2006. But on the other side on Mac OS X (up to 10.5. Leopoard) the default JRE is Version 5.0. Standard Java Version on Mac OS X 10.5
Apple only published a Version 6 for 64 bit Intel processors. So many desktop applications still uses Java 5 as basis. It would be interessting, what Apple will do, if critical bugs in Java 5 would be found.

An overview of the whole EOL-Policy for Java can be seen at http://java.sun.com/products/archive/eol.policy.html

Categories
Java JBoss

Using TransactionAttribute in submethods on same EJB3-Beans

The EJB3 Standard provides some annotations to handle general approaches, like transactions (@TransactionAttribute) and security (@RolesAllowed, etc.). To use these methods, you only have to add them to the concerning method.

1
2
3
4
5
6
7
8
@Stateless
@Local(SampleStateless.class)
public class SampleStatelessBean implements SampleStateless {
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void sampleMethod() {
        // do some stuff
    }
}

Sometimes you have to call methods of other business objects to handle the business logic. For example you have a batch update separated into many small update steps. Here you want to split the main transaction into several small transactions and the main part should have no transaction, because it only handles the reading of external data (The example code is not complete and should only demonstrate the usage of the annotations.).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Stateless
@Local(SampleStateless.class)
public class SampleStatelessBean implements SampleStateless {
    @TransactionAttribute(TransactionAttributeType.NEVER)
    public void import() {
       //read some data
       while (haveData) {
           importData(subData);
       }
    }
 
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    private void importData(List data) {
        // do some stuff
    }
}

This above code is unfortunately NOT CORRECT. The reason is that the @TransactionAttribute-annotations will only be honored, if you call the method via a business interface. So the first solutions is to inject the bean itself and call the submethod via the injected bean.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Stateless
@Local(SampleStateless.class)
public class SampleStatelessBean implements SampleStateless {
    @EJB
    private SampleStateless bp;
 
    @TransactionAttribute(TransactionAttributeType.NEVER)
    public void import() {
       //read some data
       while (haveData) {
           bp.importData(subData);
       }
    }
 
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void importData(List data) {
        // do some stuff
    }
}

Another solution, which is quite faster on JBoss in my tests, is to use the SessionContext to get a reference to the current business object.

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
@Stateless
@Local(SampleStateless.class)
public class SampleStatelessBean implements SampleStateless {
    private SampleStateless bp;
 
    @Resource
    private SessionContext ctx;
 
    @PostConstruct
    public void init() {
        bp = ctx.getBusinessObject(SampleStateless.class);
    }
 
    @TransactionAttribute(TransactionAttributeType.NEVER)
    public void import() {
       //read some data
       while (haveData) {
           bp.importData(subData);
       }
    }
 
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void importData(List data) {
        // do some stuff
    }
}
Categories
Java

Reading JPEGs with CMYK profile

Today I tried to read a JPEG with the ImageIO-Library, provided by the JRE. But instead of a wonderful image I only received the following exception:

1
2
3
4
5
6
7
8
java.lang.IllegalArgumentException: bandOffsets.length is wrong!
	at javax.imageio.ImageTypeSpecifier$Interleaved.< init >(ImageTypeSpecifier.java:382)
	at javax.imageio.ImageTypeSpecifier.createInterleaved(ImageTypeSpecifier.java:495)
	at com.sun.imageio.plugins.jpeg.JPEGImageReader.getImageTypes(JPEGImageReader.java:743)
	at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:935)
	at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:912)
	at javax.imageio.ImageIO.read(ImageIO.java:1400)
	at javax.imageio.ImageIO.read(ImageIO.java:1322)

With an EXIF-Reader (by the way a nice website) I tried to analyze the picture and saw the picture includes an embedded color profile “(unrecognized embedded color profile ‘SWOP (Coated), 20%’)”. A little bit more research showed the currently unresolved bugs in the JRE (especially ImageIO-Library; #4799903 and #5100094). So I’m not the only person, who had the problem. There are some code snippets and bug workarounds on the net trying to convert CMYK or YCCK to RGB. For my picture the CMYK-Solution doesn’t work, because the JRE means the embedded ICC profile doesn’t match the given raster (raster contains 3 bytes per pixel, but CMYK 4 bytes). But Werner Randelshofer wrote that it is important to use the given ICC, because of unexpectable color problems. So just to use a fix conversion method is not the wanted solution.

Then I tried first not to use the ImageIO library, but to give AWT-Toolkit a try. I was very surprised, that this function can correctly read the given image. So I didn’t need to handle the embedded ICC profiles directly. I modified my code to use this method, if ImageIO fails. The resulting code looks like:

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
    private BufferedImage readImage(InputStream picture) throws IOException {
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        byte[] b = new byte[10240];
        int l = 0;
        while ((l = picture.read(b)) >= 0) {
            buf.write(b, 0, l);
        }
        buf.close();
        byte[] picturedata = buf.toByteArray();
        buf = null;
        try {
            return ImageIO.read(new ByteArrayInputStream(picturedata));
        } catch (IllegalArgumentException e) {
                ImageInputStream input = ImageIO
                        .createImageInputStream(new ByteArrayInputStream(
                                picturedata));
                Iterator< ImageReader > readers = ImageIO.getImageReaders(input);
                ImageReader reader = null;
                while (readers.hasNext()) {
                    reader = (ImageReader) readers.next();
                    if (reader.canReadRaster())
                        break;
                }
 
                if (reader == null)
                    throw new IOException("no reader found");
                // Set the input.
                reader.setInput(input);
                int w = reader.getWidth(0);
                int h = reader.getHeight(0);
                BufferedImage image;
                image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
                Image intImage = Toolkit.getDefaultToolkit().createImage(
                        picturedata);
                new ImageIcon(intImage);
                Graphics2D g = image.createGraphics();
                g.drawImage(intImage, 0, 0, null);
                g.dispose();
                return image;
        }
    }

The Toolkit-Method also has no problems on servers without an X11 server.

Categories
Eclipse

Eclipse 3.4 (Gallileo) – NoClassDefFoundError

I recently updated my Eclipse from a beta of 3.4 to the latest Gallileo version using Yoxos OnDemand service.

After that I received always the following error, if I started a application or unit test case from eclipse:

1
Exception in thread "main" java.lang.NoClassDefFoundError: info/javahelp/TestClass

The solution for me was to reset the used JRE in the Build Path (Project Properties -> Java Build Path).

Project properties

Here I changed from a System JRE from the underlying operation system Mac OS X to the used JRE Eclipse in running in.

Edit Library

After that a normal start of the application or test case was possible.

Categories
Maven

Running classes via maven from console

If you use maven to compile and handle your applications, you may want to directly call it from console. Here you can use the Maven-Exec-Plugin. This plugin provides an easy method to execute Java-Classes. Of course you can configure the plugin as usual in you pom.xml, but you also can directly use it from the console.

To run a simple class you can use:

1
mvn exec:java -Dexec.mainClass=info.javahelp.examples.Example

The advantage is that java is correctly called with all used jar-dependencies and the resulting classpath.

To affect the used dependencies you can also define the used scope (default: compile). For example your application is in testing scope you can run it with:

1
mvn exec:java -Dexec.mainClass=info.javahelp.examples.tests.Example -Dexec.classpathScope=test