Categories
Java

days between two dates with Java 8

A common task in programming is to calculate a difference between two dates / timestamps. Java 8 introduced a new Date/Time API for solving such problems in an easy way.

To use this API you have to use LocalDate or LocalTime. So if you have an “old school” java.util.Date instance, you must convert it..

LocalDate localDate = new Date().toInstant().atZone(ZoneId.systemDefault());

Now you can calculate the difference between two values:

//now
LocalDate localDate1 = LocalDate.now();
//a converted future date 
LocalDate localDate2 = dateInFuture.toInstant().atZone(ZoneId.systemDefault());
int differenceInDays = localDate1.until(localDate2, ChronoUnit.DAYS)

A second variant is to use ChronoUnit method between:

//now
LocalDate localDate1 = LocalDate.now();
//a converted future date 
LocalDate localDate2 = dateInFuture.toInstant().atZone(ZoneId.systemDefault());
int differenceInDays = ChronoUnit.DAYS.between(localDate1, localDate2)

Categories
GWT Java Maven

HTMLUnit and GWT

After developing on an other aspect of a project, I realized later that all my GWT testcases didn’t work anymore. I got the following strange Exception:

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
java.lang.NoSuchFieldError: FIREFOX_17
	at com.google.gwt.junit.RunStyleHtmlUnit.<clinit>(RunStyleHtmlUnit.java:200)
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Class.java:264)
	at com.google.gwt.junit.JUnitShell.createRunStyle(JUnitShell.java:1181)
	at com.google.gwt.junit.JUnitShell.doStartup(JUnitShell.java:942)
	at com.google.gwt.dev.DevModeBase.startUp(DevModeBase.java:982)
	at com.google.gwt.junit.JUnitShell.getUnitTestShell(JUnitShell.java:698)
	at com.google.gwt.junit.JUnitShell.runTest(JUnitShell.java:672)
	at com.google.gwt.junit.client.GWTTestCase.runTest(GWTTestCase.java:421)
	at junit.framework.TestCase.runBare(TestCase.java:141)
	at junit.framework.TestResult$1.protect(TestResult.java:122)
	at junit.framework.TestResult.runProtected(TestResult.java:142)
	at junit.framework.TestResult.run(TestResult.java:125)
	at junit.framework.TestCase.run(TestCase.java:129)
	at com.google.gwt.junit.client.GWTTestCase.run(GWTTestCase.java:247)
	at junit.framework.TestSuite.runTest(TestSuite.java:255)
	at junit.framework.TestSuite.run(TestSuite.java:250)
	at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
</clinit>

The exception also occurred via Maven and not only in IntelliJ, so I knew it has something to do with my Maven-Project.

After checking the dependencies of my project with mvn dependency:tree, I found a new transitive dependency of a new added dependency. Because I didn’t need the htmlunit-part of this component I excluded the htmlunit-dependency with the following directive in my pom.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<dependencies>
....
    <dependency>
        <groupdid>my.dependency
        <artifactid>mydependency
        <exclusions>
            <exclusion>
                <groupid>net.sourceforge.htmlunit</groupid>
                <artifactid>htmlunit</artifactid>
            </exclusion>
        </exclusions>
    </artifactid></groupdid></dependency>
....
</dependencies>

A deeper analysis of the problem shows, that the transitive dependency was too new, because the field FIREFOX_17 is not available any more, but the newer one like FIREFOX_38.

Categories
GWT Java Javascript Maven

GWT-Hidden-Feature: code coverage

In July 2012 a until now rarely documented feature was added to GWT (related Git-Commit). It’s code coverage on the client side.

How it works

You can activate it via the System-Property “gwt.coverage”. The property-value must contain either all named Java source files separated by comma, or it must point to a text file containing all Java source files; one per line. Now the GWT compiler will instrument the corresponding JavaScript which is based on the named Java source files. Additionally the compiler registers an onUnLoad-Event, which stores the code coverage into LocalStorage of the browser.

Maven-Example

I have a simple GWT-Project which is build via Maven. In the main source (src/main/java/org/jajax/gwt/test/client/MyEntryPoint.java) I have the following file:

1
2
3
4
5
6
7
8
9
10
11
12
package org.jajax.gwt.test.client;
 
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.Window;
 
public class MyEntryPoint implements EntryPoint {
 
   @Override
   public void onModuleLoad() {
       Window.alert("Hello world");
   }
}

Additionally I created a Textfile (target/gwt-coverage-sources.txt) with the following content:

1
org/jajax/gwt/test/client/MyEntryPoint.java

Now only the configuration of GWT is missing. You have to add the Parameter gwt.coverage=target/gwt-coverage-sources.txt.

1
2
3
4
5
6
7
8
<plugin>
    <groupid>org.codehaus.mojo</groupid>
    <artifactid>gwt-maven-plugin</artifactid>
    <version>2.7.0</version>
    <configuration>
        <extrajvmargs>-Dgwt.coverage=target/gwt-coverage-sources.txt</extrajvmargs>
    </configuration>
</plugin>

Now if you run you application, you can access the code coverage via JavaScript

?View Code JAVASCRIPT
1
localStorge.getItem("gwt_coverage");

You will get a JSON with the following content:

1
{"org/jajax/gwt/test/client/MyEntryPoint.java":{"6":1,"10":1}}

The inner object has for every line as key a value of 0 for a missing coverage or 1 for covered code.

Conclusion

This feature is very interesting, because the alternatives are very rare. The old option to use Emma / Jacoco is not functional anymore with the current versions of Java (1.8), GWT (2.7.0 / 2.8.0-SNAPSHOT), etc. So this feature seems to be a good alternative. Unfortunately there is no tool to extract the code coverage of Unit-Tests or Integration-Tests, but I will release a Tool, which connects the GWT code coverage with Jacoco Reports. So stay tuned!

Categories
GWT Polymer/Webcomponents

Resources for Quickstart with GWT and Polymer

Today I would like to give some resources for a quick start in development with GWT and Polymer components. Polymer components are an implementation of basic components with the Webcomponents technology.

  1. The first point is an overview of the Polymer components in GWT. So you have an overview what is possible. You can click through the show case of the gwt-polymer-elements library.
  2. The second point is the official documentation from the GWT-Project. This is a good start to see how you will consume webcomponents with GWT.
  3. As described there you will use the gwt-polymer-elements library from vaadin. This library provides standard polymer (paper and iron elements and some vaadin elements) ready for use with GWT. Currently the Version 1.2.3.0 is the latest release and you will need to use the 2.8.0-SNAPSHOT version of the GWT project.

With these resources and the provided demos you will be able to start your development and play a little bit with the technologies. In the next days I will write some more Howtos about concerning points. If you have some problems with the setup, feel free to write a comment.

Categories
Java

Client-Certificate Exception “Cannot recover key”

Today I tried to use a SSL with a Client-Certficate. I used the keytool to create a keystore and imported a PKCS12 – Certifcate with:

1
keytool -v -importkeystore -srckeystore client.p12 -srcstoretype PKCS12 -destkeystore mykeystore -deststoretype JKS

After using it with Java I got the following error:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Caused by: java.security.UnrecoverableKeyException: Cannot recover key
at sun.security.provider.KeyProtector.recover(KeyProtector.java:311)
at sun.security.provider.JavaKeyStore.engineGetKey(JavaKeyStore.java:121)
at sun.security.provider.JavaKeyStore$JKS.engineGetKey(JavaKeyStore.java:38)
at java.security.KeyStore.getKey(KeyStore.java:763)
at com.sun.net.ssl.internal.ssl.SunX509KeyManagerImpl.&lt;init&gt;(SunX509KeyManagerImpl.java:113)
at com.sun.net.ssl.internal.ssl.KeyManagerFactoryImpl$SunX509.engineInit(KeyManagerFactoryImpl.java:48)
at javax.net.ssl.KeyManagerFactory.init(KeyManagerFactory.java:239)
at com.sun.net.ssl.internal.ssl.DefaultSSLContextImpl.getDefaultKeyManager(DefaultSSLContextImpl.java:170)
at com.sun.net.ssl.internal.ssl.DefaultSSLContextImpl.&lt;init&gt;(DefaultSSLContextImpl.java:40)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at java.lang.Class.newInstance0(Class.java:357)
at java.lang.Class.newInstance(Class.java:310)
at java.security.Provider$Service.newInstance(Provider.java:1221)
... 21 more

The solution here is to correct the password of the Java-Keystore. The password of the P12-Certifcate and the password of the Keystore has to be the same.

Categories
Java

Loading TTF-Fonts with Java

It is very easy to load some TrueType-Fonts (TTF) with Java.

1
java.awt.Font.createFont(Font.TRUETYPE_FONT, new File("font.ttf"));

But with some files I got the following Exception:

1
java.awt.FontFormatException: Font name not found

You can correct this with a font-editor to add the font names. For Linux I can advise the tool fontforge. It is very powerful also for convertions of fonts. For Debian you can simply install with the following command:

1
apt-get install fontforge
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 &lt; len; i++) {
            if (i &gt; 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
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
    }
}