2012-01-01

Java + Java EE

This page is a mix of czech and english, sorry for non-separated and loosely organized content, but hopefully you will find your subject by using Ctrl+F :-)


My usual MySQL JDBC params:

jdbc:mysql://localhost/test?characterEncoding=UTF-8&characterSetResults=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull

Maven Tips

To start maven goals in debug mode:

mvnDebug test ...

This does not work for me:

mvn test -DargLine="-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=4000"

Java alternative of PHP's preg_replace_callback

XSLT transformation in Java

My XSLT + Java notes show:

  • How to call Xalan from a command line
  • A simple class for XSLT conversion using JDK's XSLT
  • Template which does some change and copies all other data

What I would change about Java

Enum with a lookup map

JAXB – a List with inherited classes

Groovy bootloader bug with DOMBuilder

JBoss

How to transform web.xml with XSTL and XPath

In short, the trick is that XPath doesn't work well with element names containing a minus. So you have to match e.g web-xml like this:

*[name()='web-xml']

How to incrementally update a JAXB-mapped object

Using a factory delegating the setters to the original object. To be eventually written later.

JSON with JAXB – Jackson

JBoss AOP in a standalone application – example / howto

Few articles about JBoss AOP:

JBoss Microcontainer in a standalone application

Java Concurency, Threads and Synchronization

Maven: Order of execution of plugins in profiles

I was curious in which order Maven executes the plugins:
Whether it uses POM profile appearance order, or uses the ordering from the command line's -P param value.

Here is the result of my try-out.

Spring AOP common mistake: CGLIB2 is not available

You've added a new bean to Spring. And want to do some AOP over its methods.
But you run into this:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'udalostiQueueController' defined in class path resource [properties/Actions.xml]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.

Caused by: org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.
        at org.springframework.aop.framework.DefaultAopProxyFactory.createAopProxy(DefaultAopProxyFactory.java:67)
        at org.springframework.aop.framework.ProxyCreatorSupport.createAopProxy(ProxyCreatorSupport.java:106)
        at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:110)
        etc.

The reason is simple: To do AOP, Spring needs either CGLIB to do class instrumentation (bytecode magic) at runtime, or you have to use your bean through an interface.

So, put all your public methods into an interface and put all it's methods into an implementation. Use the implementation in Spring as the bean class, and when obtaining the bean in the code, store it into interface-typed reference.

public interface MyBean {
  public void doSomethingInAOP();
}

public class MyBeanImpl implements MyBean {
  public void doSomethingInAOP(){ ... }
}
<bean id="myBean" class="info.insolvencnirejstrik.controllers.MyBeanImpl" />

<aop:config>

  <aop:pointcut id="controllerMethods" expression="execution(* info.insolvencnirejstrik.controllers.*.*(..))"/>

  <aop:advisor advice-ref="txAdvice" pointcut-ref="controllerMethods"/>

</aop:config>
MyBean bean = appContext.getBean("myBean");

Ibatis instantiation error

Ibatis instantiation exception can arise from the lack of default constructor.

StackOverflowError with Xerces 2.0.2

Beware of DBCP in combination with Spring and iBatis using Maven. DBCP uses Xerces 2.0.2, which is old buggy version and causes stack overflow exception when parsing Spring's applicationContext.xml, which uses namespaces (e.g. for AOP).

Caused by: java.lang.StackOverflowError at org.apache.xerces.util.URI.isConformantSchemeName

Because Maven uses the „nearest node in dependency graph“ rule for resolving version conflicts, it choses DBCP's Xerces 2.0.2, because other dependencies have Xerces deeper.

Maven Unzip Plugin

I'm going to write unzip plugin for Maven2. Stay tuned.

//Update:// So here it is: Maven Unzip Plugin

Enjoy :-)

Jabber (XMPP) Maven plugin

I've created a simple plugin for Maven2, which can send a message from the Maven build process.

See Jabber (XMPP) Maven plugin

Used in the Insolvenční rejstřík project.

JPA and Hibernate mapping with MySQL – common errors and exceptions

Some tips for those tampering with Java Persistence API and Hibernate – how to tame the exceptions comming from Hibernate EntityManager, Hibernate Annotations and JDBC.

ImmutableProperties class

I've created an immutable adapter of the java.util.Pro­perties class. Not that there aren't bunches of similar over the net…

How to read properties file in Spring Framework

A new short tutorial on how to provide properties read from a file to a bean.

Parametrized Spring Configuration

Here's a short sketch of my idea about parametrizing Spring configuration, using placeholders (PropertyPlaceholderConfigurer) and overrides (PropertyOverrideConfigurer).

Web service client from WSDL using Axis2

Here's how to create web service client from WSDL using Axis2.

Logování v Javě ? log4j a java.util.logging

Sepsal jsem si stručný úvod do logování v Javě
s ukázkaou konfigurace.

JPA with Hibernate common mistakes

ERROR [org.hibernate.LazyInitializationException] (main:) could not initialize proxy - no Session
Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - no Session
        at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:57)
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
        at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:111)
        at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:57)
        at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:111)
        at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.invoke(CGLIBLazyInitializer.java:150)
        at cz.dynawest.isir.entities.User$$EnhancerByCGLIB$$f6910a6b.setMail(<generated>)
        at cz.dynawest.isir.test.Manipulace.main(Manipulace.java:49)
        at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.invoke(CGLIBLazyInitializer.java:150)
        at cz.dynawest.isir.entities.User$$EnhancerByCGLIB$$f6910a6b.setMail(<generated>)
        at cz.dynawest.isir.test.Manipulace.main(Manipulace.java:49)\--

**Two common reasons:**

1) You have loaded an entity containing a collection (List, Set, ...), but by default,
Hibernate does not load their members; instead, it puts a proxy, which waits for the case
you access the collection and then loads it.


2) You've loaded the entity using JPA's `getReference()` or Hibernate's `load()`.
That creates a proxy object, which holds only an ID.
Try calling JPA's `find()`, resp. Hibernate's `get()` //(sure, JPA quite messed the nomenclature...)//


So you're trying to manipulate the entity without having any open transaction (session).
Hibernate generally needs every database operation to happen in a transaction,
opened either explicitly (using e.g. `EntityManager.getTransaction()`)
or implicitly (using e.g. Spring AOP).



------------------------------------------------
org.hibernate.PersistentObjectException: detached entity passed to persist

You load or create an entity in one transaction, which then ends, and then you try to call persist(). Instead, you must call merge(), because that's the method which is meant to re-attach detached entities. Use persist() to store the entity when you change it inside the same transaction as it was loaded in.


Generally speaking:

If you load an entity using a DAO, usualy you have a transaction in that DAO's methods. Thus when changing the entity inside DAO, use persist(); When you change it outside DAO and then call some DAO method to save it, call merge().

Začátky se Spring AOP (Aspect Oriented Programming)

Rozchodil jsem Spring AOP a zde dávám stručný návod, jak si Spring AOP rozchodíte taky.

FreeMarker templates via Spring in non-web application

Note on how to use FreeMarker configured by Spring Dependency Injection in a standalone (non-web) application.

iBatis inline map format: empty String in nullValue

If i want to set a nullValue replacement for an empty String I use this in an explicit parameterMap:

<parameter property="street" jdbcType="VARCHAR" nullValue=""/>

I want to do the same thing using inline parameters. I've tried the following:

#street:VARCHAR:""#
#street:VARCHAR:#
#street,jdbcType=VARCHAR,nullValue=""#
#street,jdbcType=VARCHAR,nullValue=#

but none works.

How should i write the statement?

Thanks, Ondra

I recommend not using nullValue replacement. It's confusing and doesn't work the way most people would expect it to, quite the opposite actually. It's used to map nullable columns to non-nullable class members, like int, long, double, boolean etc…

It will not be available in iBATIS 3.

Clinton Begin

Quite bad news for me :(

I use nullValue as a convenient brief instrument to unify both null values OR empty String to NULL in the database (e.g. when importing from Excel and some cells are empty (that yields null) and some have empty strings). Handling it in Java or SQL code would clutter it quite much.

Can we expect some substitute for this in iBatis 3?

Ondra

While waiting for response, I realized this:

In case of MySQL, one can use NULLIF(expr1,expr2) function in INSERT, which returns NULL if expr1 = expr2 is true, otherwise returns expr1.

INSERT INTO table SET name = NULLIF(#name#,'');

java.lang.InstantiationException in iBatis when using java.util.Map

Exception:

JavaBeansDataExchange could not instantiate result class.  Cause: java.lang.InstantiationException: java.util.Map

SQL mapping code:

<select id="getMatchingDluzniciForUser" parameterClass="long" resultClass="map">
SELECT * FROM table
</select>

Cause: iBatis is trying to instantiate java.util.Map, which is an interface, thus can't be instantiated.

Fix: Instead, use java.util.HashMap or other Map implementation as the result class.

Compiling Connector/J

If you try to compile MySQL Connector/J from the source, after resolving dependencies, you will probably end up with many compiler errors.

That is because of the special way how Connector/J is compiled. Let Mark Matthews say it

The issue is that you can't compile Connector/J with just JDK6, as the driver supports JDBC4 and pre-JDBC4 APIs from the same codebase, and there are new classes and methods in JDBC4 that aren't available pre-JDK6.Therefore, the way it works is that you have to set JAVA_HOME to point to JDK-1.4 or 1.5, and then set the Ant properties „com.mysql.jdbc­.java6.javac“ with the full path to your JDK6 java compiler, and „com.mysql.jdbc­.java6.rtjar“ with the full path to your JDK6 runtime class libraries, when invoking Ant.

SQLException for zero DATETIME or TIMESTAMP column? Use zeroDateTimeBehavior

When working with MySQL over JDBC and the driver encounters a zero DATE, TIME, or DATETIME value (that is, e.g, ‚0000–00–00‘ for DATE), an exception is thrown:

java.sql.SQLException: Cannot convert value '0000-00-00 00:00:00' from column 4 to TIMESTAMP.

In this case, using SQL commands like

SET GLOBAL sql_mode = 'NO_ZERO_DATE';

does not help much, because that works only in „strict SQL mode“, and needs to be set for every connection, or globally for the whole server.

What helps is setting JDBC driver's zeroDateTimeBehavior property to convertToNull:

What should happen when the driver encounters DATETIME values that are composed entirely of zeroes (used by MySQL to represent invalid dates)? Valid values are "exception", "round" and "convertToNull".

The way to set it depends on the way you configure JDBC driver. The most common case is to use connection URL parameters. In my case it reads:

jdbc:mysql://localhost/test?zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=UTF-8&characterSetResults=UTF-8

java and javaw difference

What's the difference between java and javaw?

Návod: Import projektu ze SVN do NetBeans projektu

Chtěl jsem se trochu povrtat v projektu Apache POI, ale jak prúvodci v NetBeans, tak instrukce na stránce projektu předpokládají, že se SVN umíte, jak když bičem mrská, což v mém případě bylo přesně naopak :-)

Proto jsem sepsal velmi stručný núvod, jak do NetBeans dostat projekt ze Subversion repository.

Levn? Java/JSP/J2EE hosting

Pokud hledáte levný hosting pro svoji J2EE webovou aplikaci, možná vás zaujme tato nabídka.

Converting a number to Excel column character name

When working with Excel sheets, you might need to convert the column number to it's letter name – like 1 to A, 2 to B, 43 to AQ, etc. It's not as trivial as converting a number between two radixes. Here is my solution.

Uzávěry v jazyce Java – přes místní vnitřní třídu

Při tvorbě GUI k jednomu systému se mi zastesklo po snadnosti uzávěry v JavaScriptu. Prozkoumal jsem možnosti uzávěr v Javě.

Spring Framework – úvod

Připravil jsem velmi stručný tutoriál na rozběhání jedné části Spring Frameworku, a sice Beans Factory. V češtině.

Hibernate super-quick start in NetBeans

Here's my how-to for starting a Hibernate project using Java Persistence API (JPA).

Later, I'll write something about object-relational mapping.

Hibernate Compatibility Matrix Error

Beware of the Hibernate Compatibility Matrix at http://www.hibernate.org/6.html.

Hibernate EntityManager 3.3.2 GA is said to be compatible with Hibernate Annotations 3.3.x. But, it is not compatible with Hibernate Annotations 3.3.0 – only with Hibernate Annotations 3.3.1. This information could spare you few minutes, as it would do to me if I knew it :)

java.lang.NoSuchMethodError: org.hibernate.cfg.AnnotationConfiguration.addProperties(Ljava/util/Properties;)Lorg/hibernate/cfg/AnnotationConfiguration;

Simplest One-line Formatter for java.util.logging

I didn't like the two-line output of java.util.logging.SimpleFormatter. On current widescreen LCDs, whole log record can fit at a single line. So I've written cz.dynawest.logging.SimplestFormatter. Compare:

13.7.2008 0:47:10 cz.dynawest.isir.Conversion3Controller ZpracujArchiv - INFO:   Test
13.7.2008 0:47:10 cz.dynawest.isir.Conversion3Controller ZpracujArchiv - INFO:   Test2

vs.

13.7.2008 0:47:10 cz.dynawest.isir.Conversion3Controller ZpracujArchiv
INFO:   Test
13.7.2008 0:47:10 cz.dynawest.isir.Conversion3Controller ZpracujArchiv
INFO:   Test2

If you like it, the source code is available for download here.

Java tipy a triky

Patříte mezi programátory, kteří prvně hledají řešení na Google jako slovní úlohu a až pak studují jakékoliv API? Pak vám možná pomůže moje stránka tipů pro Javu. Zatím není nijak moc rozsáhlá, budu postupně doplňovat.
Podobných tipů a triků jsou po webu kvanta, ale ne tolik v češtině.

//Update:// Tak nakonec stejně vše zveřejňuju v angličtině…

Bug in MySQL JDBC implementation – Connector/J

I've found a bug in Connector/J ver. 5.1.6. It appears upon subsequently called Connection.isValid(), which uses unsynchronized threads.

Reported at http://bugs.mysql.com/bug.php?….

Java Runtime Environment or Java Developement Kit not found on 64-bit system

I have 64-bit version of Windows XP and 64-bit version of JDK and JRE.
During instalation of jEdit, I got this message from the installer:

Setup was unable to find an installed Java Runtime Environment or Java Developement Kit of version 1.4, or higher. You must have installed at least JDK or JRE 1.4 to continue setup.

jEdit installer looks for 32-bit version of JRE. Install it alongside the 64-bit version to fix the problem.

The same problem was with NetBeans installer.

Texy! Java Implementation

Anyone knows about any? Please, let me know via e-mail.

Texy! syntax use cases here.

Java implementace překladače Texy!

Zdravím,

nechtěl by někdo čirou náhodou implementovat překladač Texy v Javě?

www.texy.info

Mohlo by to být dobré téma projektu / bakalářky… Formální specifikace není, jen podle popisu syntaxe a ukázek použití…

Java komunita by vás jistě oslavovala :-)

Ondra

Autor Texy David Grudl sestavil sadu testovacích souborů, na kterých lze ověřit implementaci překladače. K dispozici na http://download.texy.info/refs.zip

Algou a omegou původní PHP imiplementace jsou PCRE. Knihovna pro Javu, která zvládá PCRE podle Perl 5, je na http://jakarta.apache.org/oro/ .

Ondra Žižka

My usual MySQL JDBC params

jdbc:mysql://localhost/test?characterEncoding=UTF-8&characterSetResults=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull

Úplné začátky v Javě

Java často začátečníka odradí relativní složitost přípravy kódu a jeho překladu do čehokoliv spustitelného (v roce 1998 to byl i můj případ a Javou jsem se prokousal až o další dva roky později :-) .

Pro ten případ jsem připravil velmi polopatický návod, jak vytvořit zdroják v Javě, jak ho přeložit do souboru .class a jak jej spustit.

J2EE – Java pro web

V poslední dobé se prokousávám světem J2EE. Je to svět rozsáhlý a nepřehledný. V této souvislosti uvedu jeden trefný citát:

Entrance to this world is a cultural conversion, not a choice of one simple programming language over another.

-- GBdirect, „Active Web Sites and Comparison of Scripting Languages“

Pro kamaráda jsem začal psát velmi stručný úvod, aby se hned zkraje neutopil v záplavě tří až pětipísmenných zkratek.


0