Java, J2EE, 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:-)
JPA 2.0 / Hibernate 3.6: Cannot create TypedQuery for query with more than onereturn
Trying Jira on JBoss? Specification
violation [EJB3 JPA 6.2.1.2]
- You have not defined a jta-data-source for a JTA enabled persistence context
named: propertyset
Trying to get CDI/Weld working in embedded Jetty for a Wicket application
JNDI: sample jndi.properties file
HTTP PUT and POST requests with Jersey
RHQ: How to set transaction timeout
Mobicents and FreeTTS what do they have together?
How to get curent class'es
.jar location (directory,path)
Web Services over SSL with JBoss WS
Package javax.crypto.spec does not exist compilationerror
NoClassDefFoundError: PropertyResolver in Wicket Exception invoking periodic operation on shutdown
JUnitDiff JUnit test results reports comparison
CsvCruncher CSV manipulation through SQL (HSQLDB)
Hibernate and JPA 2.0 Maven dependencies
JBoss startup failure Error installing to Create: name=ProfileKey@[domain=default, server=default, name=farm]
Null-safe bean comparator for Apache commons-beans
Quartz intro and how to use Quartz in Wicket
SVNbot an IRC bot announcing SVN commits, written inJava
My usual MySQL JDBC params:
jdbc:mysql://localhost/test?characterEncoding=UTF-8&characterSetResults=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull
MySQL JDBC driver for Maven mavenized Connector/J
- PircBot IRC Bot framework library in a provisory Maven repository.
JAXB example keywords: JAXB howto example tutorialintro.
Sardine WebDAV client library for Java
JBoss AS
Java system variables (-D for bin/run.sh)
JBoss Operation Network and Tomcat on Windows 2003:No-go
JBoss WebServices (JBossWS) notes
Simple JBoss AS clustering example (2nodes, JSP session replication).
Maven Tips
Standard maven pom.xml for standalone application
Maven 3: How to force artifact resolution update
Mavenhoe fake Maven repository from .jar'sin local directorytree
Maven'spom.xml XSLT transformation how to handle namespaces.
Maven and Log4j: Missing JMX dependencies mavenized jmxri and jmxtools.
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"
Profile activation and properties
How
to add existing Java project's .jarsto Maven repository
How to create an application distribution package withMaven
How to create a JNPL file (for Java WebStart) withMaven
Quick and dirty mavenization How to install an existing library with dependencies to Maven repository.
I've presented Maven 2for the company Iwork for. Download here: Maven presentation for Red Hat / JBoss.
Ashort polemic against Ivy / Maven2 Comparison: Read my own opinion about How Maven 2compares to Ivy.
Short code for Antrun Maven plugin
Java alternative of PHP's preg_replace_callback
Here.
XSLT transformation in Java
My XSLT + Java notes show:
- How to call Xalan from a command line
- Asimple class for XSLT conversion using JDK'sXSLT
- Template which does some change and copies all otherdata
What Iwould change about Java
Enum with a lookup map
JAXB a List with inherited classes
JAXB a List with inherited classes
Groovy bootloader bug with DOMBuilder
Is this a bug?
JBoss
Unsign JBoss AS distribution: find . -type f -iname '*.jar' -exec zip
-d '{}' META-INF/JBOSSCOD.{SF,RSA} \;
Bootstrapping JBoss Embedded server Avery brief how-to just a maven deps and the bootstrapingcode.
Common JBoss AS mistakes and exceptions
JBoss vs. Spring An attempt to answer what to use as a base for an enterprise web application.
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
likethis:
*[name()='web-xml']
How to incrementally update a JAXB-mapped object
Using a factory delegating the setters to the original object. To be eventually writtenlater.
JSON with JAXB Jackson
How to create JSON output from POJOs using JAXB annotations.
JBoss AOP in a standalone application example / howto
Few articles about JBoss AOP:
- Abrief introduction to usage of JBoss MC with JBossAOP
- JBoss
AOP:
java.lang.IllegalArgumentException: Unknown AOP tag: bean - JBoss AOP: Could not find class
JBoss Microcontainer in a standalone application
Abrief introduction to usage of JBoss MC in a standalone app.
Java Concurency, Threads and Synchronization
Attempt for one modifier and many concurent readers a variant of producers and consumers problem.
Maven: Order of execution of plugins in profiles
Iwas 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 paramvalue.
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 intothis:
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'smethods 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. forAOP).
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'sXerces 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říkproject.
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 andJDBC.
ImmutableProperties class
I've created an immutable adapter of the java.util.Properties class. Not that there aren't bunches of similar over thenet
How to read properties file in Spring Framework
Anew short tutorial on how to provide properties read from a file to a bean.
Parametrized Spring Configuration
Here'sa short sketch of my idea about parametrizing
Spring configuration, using placeholders
(PropertyPlaceholderConfigurer) and overrides
(PropertyOverrideConfigurer).
Web service client from WSDL using Axis2
Here'show to create web service client from WSDL using Axis2.
Logov�n� vJav�, log4j a
java.util.logging
Sepsal jsem si stru�n� �vod do
logov�n� vJav�
suk�zkou 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'sthe 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 loadedin.
Generally speaking:
If you load an entity using a DAO, usualy you have a transaction in that
DAO'smethods. 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?tetaky.
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 iwant to set a nullValue replacement for an empty String Iuse this in an explicit parameterMap:
<parameter property="street" jdbcType="VARCHAR" nullValue=""/>Iwant 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 iwrite the statement?
Thanks, Ondra
Irecommend not using
nullValuereplacement. It'sconfusing and doesn't work the way most people would expect it to, quite the opposite actually. It'sused to map nullable columns to non-nullable class members, like int, long, double, booleanetcIt will not be available in iBATIS 3.
Clinton Begin
Quite bad news for me :(
Iuse
nullValueas a convenient brief instrument to unify both null values OR empty String toNULLin the database (e.g. when importing from Excel and some cells are empty (that yieldsnull) and some have empty strings). Handling it in Java or SQL code would clutter it quitemuch.Can we expect some substitute for this in iBatis 3?
Ondra
While waiting for response, Irealized 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 resultclass.
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 sayit
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.4or 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? UsezeroDateTimeBehavior
When working with MySQL over JDBC and the driver encounters a zero
DATE, TIME, or DATETIME value (that is,
e.g, 00000000 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 itreads:
jdbc:mysql://localhost/test?zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=UTF-8&characterSetResults=UTF-8
java and javaw difference
What'sthe difference between
java and javaw?
N?vod: Import projektu ze SVN do NetBeans projektu
Cht?l jsem se trochu povrtat vprojektu Apache POI, ale jak pr?vodci vNetBeans, tak instrukce na str?nce projektu p?edpokl?daj?, ?e se SVN um?te, jak kdy? bi?em mrsk?, co? vm?m p??pad? bylo dote? 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?szaujme 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'sletter name like 1 to A, 2
to B, 43 to AQ, etc. It'snot as trivial
as converting a number between two radixes. Here is my solution.
Uzávěry vjazyce Java přes místní vnitiní třídu
Přitvorbě GUI kjednomu systému se mi zastesklo po snadnosti uzávěrů vJavaScriptu. Prozkoumal jsem možnosti uzávěrů vJavě.
Spring Framework úvod
P?ipravil jsem velmi stručný tutoriál na rozběhnutí jedné části Spring Frameworku, a sice Beans Factory. Včeštině.
Hibernate super-quick start in NetBeans
Here'smy 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.2GA 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 Iknew it:)
java.lang.NoSuchMethodError: org.hibernate.cfg.AnnotationConfiguration.addProperties(Ljava/util/Properties;)Lorg/hibernate/cfg/AnnotationConfiguration;
Simplest One-line Formatter for java.util.logging
Ididn'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 vangli?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-bitsystem
Ihave 64-bit version of Windows XP and 64-bit version of JDK and JRE.
During instalation of jEdit, Igot 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.4to continuesetup.
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.
Java implementace p�eklada�e Texy!
Zdrav�m,necht�l by n�kdo �irou n�hodou implementovat p�eklada� Texy vJav�?
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. Kdispozici nahttp://download.texy.info/refs.zip
Algou a omegou p�vodn� PHP implementace jsou PCRE. Knihovna pro Javu, kter� zvl�d� PCRE podle Perl 5, je na http://jakarta.apache.org/oro/.
Ondra �i�ka
�pln� za��tky vJav�
Java �asto za��te�n�ka odrad� relativn� slo�itost p��pravy k�du a jeho p�ekladu do �ehokoliv spustiteln�ho (vroce 1998to byl im�j p��pad a Javou jsem se prokousal a� odal�� dva roky pozd�ji :-).
Pro ten p��pad jsem p�ipravil velmi polopatick� n�vod, jak vytvo�it zdroj�k
vJav�, jak ho p�elo�it do souboru .class a jak jej
spustit.
J2EE Java pro web
Vposledn� dob� se prokous�v�m sv�tem J2EE. Je to sv�t rozs�hl� a nep�ehledn�. Vt�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 vz�plav� t�� a� p�tip�smenn�ch zkratek.