Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

2017-07-20

Reference to a static method + instrumentation = fail!

In a Java project I am using ActiveJDBC ORM. Part of the ORM is an instrumentation process that adds new methods into compiled classes. In my case the instrumentation adds a few static factory methods into my Record class. For example Record.findAll() to get all records from the database.

I have an execute method that accepts a single parameter of type Callable. The method opens a connection, executes what's in the parameter and then closes it.

I implemented this a simple way. In a repository class, I just passed a reference to a static method of instrumented class into the execute method. After building the application in IntelliJ I got well known failed to determine Model class name, are you sure models have been instrumented? exception.

Even though, the model class was instrumented it didn't work. Then I made few simple changes in a repository class, not related to the execute method itself, and it started working. I was confused.

After a disassembly of repository class I noticed that there is a reference to Record's parent class instead of Record itself. Making small changes in repository and recompilation, fixed the reference.

Reason

  • First compilation went this way:

    1. Java compiled clean project (all classes were compiled).

      First, it compiled model class. The class was not instrumented so there were no static methods at this time.

      Then, it compiled repository class. Because model did not have any static methods at that time, a reference to a static method in the model class was "pointed" to a parent class method.

    2. ActiveJDBC plugin instrumented the model class but reference from repository to model's parent was already set, so it didn't make any change.

    At this moment, the bytecode of static method call looked like this:

    Method arguments:
      #33 ()Ljava/lang/Object;
      #34 invokestatic org/javalite/activejdbc/Model.findAll:()Lorg/javalite/activejdbc/LazyList;
      #35 ()Ljava/util/List;
    
  • Second compilation, after small changes in repository:

    1. Java compiled only the changed repository class. That means at this moment model class had static methods so the reference was set correctly.

    2. ActiveJDBC plugin instrumented the model class but that was not important at the moment.

    Now, the bytecode is correct:

    Method arguments:
      #33 ()Ljava/lang/Object;
      #34 invokestatic demo/Record.findAll:()Lorg/javalite/activejdbc/LazyList;
      #35 ()Ljava/util/List;
    

How to avoid this

Instead of reference to a static method use lambda method call.

So instead of this:

public List<Record> findAll() throws Exception {
    return execute(Record::findAll);
}

write this:

public List<Record> findAll() throws Exception {
    return execute(() -> Record.findAll());
}

In this case Java will not create a reference to parent class Model.findAll() but will point correctly to Record.findAll().

2016-06-05

Shared test sources in Gradle multi-module project

Basic assumptions

Let's suppose following project structure.

:root-module
|    +--- main source set
|    \--- test source set
\--- :module1
     |    +--- main source set
     |    \--- test source set
     \--- :core-module
              +--- main source set
              \--- test source set
Shared test-utility classes shouldn't be placed in test source set

In some legacy projects I've seen utility classes to be located in test source set. This is problematic in multi-project applications because Gradle does not pull test sources to a dependent module. So module1 won't "see" classes from core-module's test source set. This makes sense because you don't want to have module1's test-classpath flooded with core-modules's test classes.

Note: IDEA 14 does not respect this rule and it pull test sources to a dependent module. This behaviour has been fixed lately.

Test-utility classes shouldn't be placed in main source set

For obvious reasons you don't want to pollute main source set with test classes. In main source set there should be production code only. Tests are usually executed on application's build phase so there is no need to put them into final build.

In Spring application test classes shouldn't be located in component-scanned package

This is mandatory for Spring developers who uses component scan. In some cases you may want to create annotated class used exclusively by tests.

IDEA places all source sets marked as sources to classpath. So if you place your test-only annotated class to a package scanned by Spring your application context will ends up polluted.

Shared test classes should be kept in module where it belongs

Because of previous point some people have tendency to put shared test classes to a stand-alone module. Although core-module-test (main) -> core-module (main), core-module (test) -> core-module-test (main) is legal construct in Gradle you don't want to complicate your project's dependency structure by creating "unnecessary" modules.

Module dependency resolution basics in Gradle and IDEA 14 and 16

Gradle

Gradle allows you to define dependency between two module configurations.

// Declared in root-module
dependencies {
    // Current module's testCompile configuration depends on another module's default configuration.
    testCompile project(':module1')
    // Current module's configuration depends on another module's test configuration.
    testCompile project(path: ':core-module', configuration: 'test')
}

Dependency to a default configuration of another module pulls module's dependencies and sources to a dependent module. Dependency to a test configuration pulls only dependencies without sources. So in our case root-module won't see any core-module's test classes.

IDEA 14

In contrast to Gradle the IDEA 14 pulls all sources to a dependent module. Even test sources.

If you open Gradle project IDEA will behave oddly. It will let you run tests that Gradle won't even compile. Unfortunately IDEA 14 doesn't have any feature that can be used to fix this so you have to think about it when you will write your test.

IDEA 16

Latest version of IDEA does not pull test sources to a dependent module which is consistent behaviour to Gradle. It also allows you to define dependency to a specific source set. You just have to choose create separate module per source set option when importing Gradle project. It has been added lately to harmonize IDEA's dependency resolution with Gradle.

Using shared test sources by dependent module

Declaring dependency to a module's output directory

In projects having utility test-classes in test source set there is usual hot-fix to add testCompile dependency to other module's output directory. So in our example the module1's tests will depend on core-module's compiled test classes.

// Declared in module1
dependencies {
  testCompile project(':core-module').sourceSets.test.output
}

This is quick solution but it has some cons:

  • In your IDE you have to rebuild shared classes on every change to refresh dependencies. Remember IDEA 16 does not pull test sources.
  • It's against the requirements in first chapter of this article.
Placing utility classes to a custom source set

The good solution is to create custom source set for shared test-classes and declare dependencies to this source set from dependent modules. This approach allows you to keep classes in modules where it belongs still separated from main and test sources. This approach is used by Gradle project itself.

Implementation is quite straightforward. First create script plugin that will add new testFixtures source set and appropriate configurations to a module.

Then apply script plugin on a module and declare necessary dependencies.

// Declared in core-module
apply from: 'testFixtures.gradle'

dependencies {
  testFixturesCompile('junit:junit:4.12')
}

Finally add dependency to the newly created source set.

// Declared in module1
dependencies {
    testCompile project(path: ':core-module', configuration: 'testFixturesUsageCompile')
}

Note for IDEA users: There is a small drawback. If you open the project without create separate module per source set option your custom-source set will be available in main source set. If you use a shared test-class in main source set IDEA won't complain about it but Gradle won't be able to compile. So you have to be careful about what you are using.

2016-05-15

Spring Boot internationalisation with database stored messages and IBM ICU

Motivation

In Java world there is a common approach to store localisation messages in property files. I want to have messages stored in database so users can manage them on runtime. I also want better plural forms handling provided by project ICU.

Introduction to Spring's localisation process

Following figure shows localisation processing in a Spring application.

  1. Requested locale (language and country codes) is passed to the Spring application as part of ServletRequest object. In ServletRequest there are several properties that can hold locale value. For example HTTP header Accept-Language, a cookie or query string parameter. Locale is resolved from the request object in DispatcherServlet.render method by instance of LocaleResolver class. There are several resolvers available in the Spring. You can check out org.springframework.web.servlet.i18n package for more details.
  2. Locale value is send by user's browser by default (as a Accept-Language header). To allow your application to change locale you have to configure LocaleChangeInterceptor. The interceptor reads locale value from query string and sets it to the request. Please read my older article Request mapping on demand in Spring MVC if you want to know more about request processing.
  3. Message code and resolved locale are passed to MessageSource via a view. Message source is responsible for loading message from storage, processing it and returning localised message back to the view. The view incorporates processed message into template.
  4. A message can be simple text or a pattern consisted of placeholders that will be replaced while pattern is processed. Placeholders are used to render text in a locale sensitive way. Patterns are processed by java.text.MessageFormat by default. In this article I will also describe enhanced version of message format (com.ibm.icu.text.MessageFormat) provided by ICU.

LocaleChangeInterceptor and LocaleResolver configuration

AcceptHeaderLocaleResolver is Spring Boot's default locale resolver. The resolver reads locale from Accept-Language header. Unfortunately it does not support locale change on runtime because it's setLocale method is not implemented.

No locale change interceptor is configured by default.

Locale resolver can be changed by creating LocaleResolver bean. I've decided to use CookieLocaleResolver which resolves locale stored in a cookie.

Locale change interceptor can be added by extending WebMvcConfigurerAdapter. Following code snippet shows configuration of locale change interceptor that reads new language code from query string. By adding lang parameter to a query string user can change requested locale.

Database aware MessageSource

To create message source you just need to implement MessageSource interface.

And then configure template engine so it will load messages from newly created message source. Thymeleaf template engine is used in this article.

Message patterns and plural forms handling

Plural forms handling is very common case in multilingual applications. Plural forms handling has to be robust because some languages have pretty complicated plural rules. Here is a example of three sentences that should be generated from a single message pattern:

  • There is 1 apple in 1 basket.
  • There are 2 apples in 2 baskets.
  • There are 0 apples in 2 baskets.
Standard MessageFormat

To deal with plurals Java offers MessageFormat formatter. This formatter can evaluate conditions in message pattern which can be used for plural forms handling. Let's revisit DatabaseMessageSource.resolveMessage method to incorporate the formatter into the application.

private String resolveMessage(String code, Object[] args, Locale locale) {
    String message = ""; // TODO Load message from database...
    MessageFormat messageFormat = new MessageFormat(message, locale)
    return messageFormat.format(args);
}

Then you need to create a message pattern with choice conditions. Curly braces are used as a placeholders for message parameters and can contain message formatting syntax.

There {0,choice,0#are|1#is|2#are} {0} {0,choice,0#apples|1#apple|2#apples} in {1} {1,choice,0#baskets|1#basket|2#baskets}.

To pass values into message you just need to add braces with values at the end of message code.

<p th:text="#{apple.message(1,1)}"></p>
<p th:text="#{apple.message(2,2)}"></p>
<p th:text="#{apple.message(0,2)}"></p>

Shown example is official Java recommended approach for plural forms handling. Unfortunately it's choice conditions are quite complicated even for English language which has only two plural forms. For languages like Polish it's almost unreadable.

IBM ICU MessageFormat

Project ICU focus on dealing with internationalisation. It offers its own implementation of MessageFormat that is more robust and easier to use. To incorporate this formatter to the application you need to slightly change DatabaseMessageSource.resolveMessage method.

private String resolveMessage(String code, Object[] args, Locale locale) {
    String message = ""; // TODO Load message from database...
    MessageFormat messageFormat = new MessageFormat(message, locale);
    StringBuffer formattedMessage = new StringBuffer();
    messageFormat.format(args, formattedMessage, null);
    return formattedMessage.toString();
}

For plural forms handling ICU formatter offers purpose built plural pattern argument.

There {0,plural,one{is # apple}other{are # apples}} in {1,plural,one{# basket}other{# baskets}}.

Localised URLs

In the Request Mapping on Demand article I've described possibilities of URL localisation on the fly.

Conclusion

There are several more internationalisation approaches available in Java world. For example there is possibility to use GNU gettext in Java. But it's not that easy to implement it in Spring. I've done some research and found out that combination of ICU and message codes seems to be the best choice.

2007-10-28

Instalace jdk6 na debian etch

Protože oficiální linuxový instalátor javy nefunguje na debianu (hází hlášku error: Failed dependencies), je potřeba zvolit jiný postup.

Nejdříve si otestuju aktuální verzi javy nainstalovanou na mém systému, pomocí příkazu:

java -version

Mělo by se vypsat něco jako:

java version "1.4.2"
gij (GNU libgjc)...

Teď si stáhnu poslední verzi javy z http://java.sun.com, stáhnu soubor s koncovkou .bin. Teď tento soubor rozbalím do nějakého temp adresáře, pomocí příkazu:

./jdk-6u2-linux-i586-rpm.bin -x

Měl by se mi rozbalit jeden nebo více .rpm souborů.

Teď nainstaluji alien, pomocí:

apt-get install alien

a pustím ho na .rpm soubory:

alien --scripts --keep-version -d *.rpm

Chvilku to bude trvat, záleží na výkonnosti pc. Na mém celeronu 1400Mhz to trvalo asi 5 minut. V tmp adresáři by se měl/měly objevit instalační soubory debianu s koncovkou .deb. Ty nainstaluji pomocí příkazu:

dpkg -i *.deb

A voila, java byla nainstalována někam do /usr/java/. Nyní ještě vytvořím softlink na javu pomocí

ln -s /usr/java/latest /usr/lib/java

a do souboru /etc/profile přidám mezi původní řádky export systémové proměnné

PATH
umask 022

cestu k javě, tzn., soubor bude vypadat asi takhle:

export PATH
JAVA_HOME="/usr/lib/java"
export JAVA_HOME
umask 022

Namapuju binárky pro cestu k javě, aby se po zadání příkazu java do konzole volala správná verze:

update-alternatives --install /usr/bin/java java $JAVA_HOME/bin/java 200
update-alternatives --install /usr/bin/javac javac $JAVA_HOME/bin/javac 200
update-alternatives --install /usr/bin/jar jar $JAVA_HOME/bin/jar 200
update-alternatives --install /usr/bin/keytool keytool $JAVA_HOME/bin/keytool 200

Teď už jenom stačí restartovat PC. A znovu otestovat příkazem

java -version

Můžu si i přidat javu do firefoxu a to tak, že vytvořím symbolický link do složky plugins firefoxu na plugin v adresáři, kde mám nainstalovanou javu. Pod debianem se firefox jmenuje iceweasel, proto ta složka.

ln -s /usr/java/jdk1.6.0/jre/plugin/i386/ns7/libjavaplugin_oji.so /usr/lib/iceweasel/plugins/libjavaplugin_oji.so

Restartuju firefox a otestuju zadáním

about:plugins

a podívám se, jestli je java nainstalovaná.