Skip to content
accelerando

Category Archives: Java

Schei� encoding: Java, MySQL and multi-byte UTF-8 support

21-Jan-13

UTF-8 has always been a multi-byte encoding but you probably had to handle only 2 byte (16bit) UTF-8 characters. With the raise of Emojis 4 byte characters rose as well so handling 4 byte UTF-8 characters is not only of interest for handling exotic languages but also for the needs of average users who want to post fancy smilies with their phones.

I won’t go into detail too much but only note some tips and caveats for supporting 4 byte UTF-8 characters in a Java / MySQL ecosystem. You’ll find the basic setup for your MySQL database, considerations about MySQL performance, connecting your Java program to the database and finally a little information about handling 4 byte UTF-8 strings in java:

More…

#WJAX 2012

08-Nov-12

Another year, another W-JAX. It seems to become a jour-fix, being in Munich in November.

As last year i only can recommend staying in the Westin Grand if your company is willing to afford this. You’ll have a much better conference experience than commuting throughout the city for your hotel or hostel. When i started going to conferences i often choose a cheaper hotel, probably outside and most often, i didn’t attend the later session because I was already tired from the conference marathon, just wanting to put my feet a little and wasn’t willing traveling to a city for hours in the night. Also you can take a break much easier.

Enough of that. I only wrote one short post called Old and tired? last year, this year i’m trying to review the talks i visited a little bit, like i did in 2010.

Angry Duke – Physics Games mit JavaFX by Anton Epple @monacotoni

My conference started on wednesday with a great talk by Anton Epple about integrating Box2D respectively JBox2D with JavaFX. My first though was: Ok, time to get those old mathematics back into my brain and try something funny with (J)Box2D. Haven’t done such things in a while.

I was really impressed how easy it seams to recreate something like Angry Birds dubbed Angry Nerds with JavaFX. I was actually fiddling around with JavaFX the last months and i must say this is great stuff. I was always found of Java Swing (I’m project lead of a Desktop GIS project, so no surprises there) and i think JavaFX is the way to go. If Apple eventually allows interpreted stuff on iOS than the possibilities seems endless.

Spring-Data JPA: Datenzugriffsschichten richtig gemacht by Oliver Gierke @olivergierke

So another Spring spin-off, Spring-Data. Spring-Data is an umbrella project that encapsulates data access in general and provides support for relational as well as non-relational databases.

Olivers talk was especially about using Spring-Data JPA to reduce the cruft work of building repositories.

I did like the extensive live coding and saw already many things i could improve in my own projects, not especially related to Spring-Data.

It’s impressive what Spring-Data JPA can do but i’m not convinced of another layer of data access if not needed. I tend to get along with JPA very well. Complex SQL queries are defined as named native queries and apart from that i like the Criteria Query in combination with the metamodel not as bad as Oliver ;)

Natural User Interface Design by Prof. Wolfgang Henseler @prof_henseler

Command line evolved to Graphical User Interface (GUI) evolves to Natural User Interface (NUI) or in short: Times are a-changin. Questions raised in the keynote: What is the definition of intuitive and stuff like that. What’s intuitive to me must not be intuitive to someone else… The quintessence for me: Don’t try to force my model the world on other people. The less one needs to switch the mental model, the more intuitive stuff gets. But in the end: This should be common sense.

I would expect the raise of natural user interfaces together with all the new powerful technologies. New tools change our view of the tools, new views change the tools. And so on.

Cool Java by Arno Haase

Arno stood in for Roman Roelofsen. The talk was nice but mostly about libraries. The one thing new for me: There is not only a “magic” readObject that can manipulate an object while deserializing but also a readResolve that can and should be used to enforce singletons. See some more info here.

In 60 Minuten von der Excel- zu JEE-Anwendung by Konstantin Diener

This talk had potential as it was labeled “with code”. I would have loved to see more actual coding but was disappointed. All i got was an (impressive) enumeration what has been done. A pity, as we have some similar requirements.

Gute Zeilen, schlechte Zeilen. Regeln für wartbare Programme by Dirk Weil

Nice title, but i guess it could be too less to apologize to RTL if Dirk publishes the logo of this talk ;) Anyway, first halve of the talk was pretty much about codestyle and tools to check it, the second about coding itself. I’m so glad i’m not the only one who is personally embarrassed when i see someone using something like “if(something) return true” or not using De Morgan and stuff like that.

But in the end, many things Dirk mentioned boil down to common sense as well and this is something i’m missing pretty much often in junior programmers.

Hochverfügbare JEE-Architekturen für Online-Portale am Beispiel von ElsterOnline by Johannes Rödel

Johannes’ talk didn’t have much code in it but was pretty interesting nevertheless. Johannes talked about the setup of Germany tax offices for the online tax “Elster Online” and about the metrics they use to evaluate if the portal is highly available or not.

He gave the following anecdote and tip: They wanted to change their setup to use a hardware load balancer between 2 releases but the business didn’t approve the same hardware for integration tests at first. Going production it all went messy. Something was wrong with the internet provider and the balancer and in the end nobody really knew what was going on as it couldn’t have been tested. Lesson learned: Use the same setup in integration test as in production. If this is not possible, don’t use the latest and greatest stuff in production.

Security Patterns – Mehr als nur Authentifzierung und Autorisierung by Mike Wiesner @mikewiesner

I’m always interested in talks about security and also trying to improve stuff so Mikes talk was very welcome.

Mike told us who to prevent common flaws in authentication and authorization through using and correctly configuring frameworks, pretty much – you guess it – also common sense. But its worth mentioning that he also emphasized that the application should not bow to the security (you know the phrase “this cannot be done because of security concerns”).

Most interesting to me where injections (again) but not SQL-Injections this time but injections into queues, for example those of Spring-Integration. You guess it: Everything that comes from “out there” should not be regarded as too friendly ;)

Git Culture by Matthew McCullough @matthewmccull

A keynote about culture and happiness. In english. What could go wrong? Nothing. Matthew had a fantastic talk about how bringing a culture of direct responsibility can help grow a business, in this case Github. He had some great examples that this not only works for a (not so small anymore) startup, but also for companies like Gore. I can proudly say that although I course some times about processes in my company, i’m glad to work at Enerko Informatik because the company cares for its employees as well and holds our ideas high.

Essence (also again, see webcon some weeks ago): Changing ones behavior will change facts in the long run.

I really like talks that bring the technical side and the more humanistic or philosophical side of our profession together. Well done Matthew.

Import continuous delivery by Jevgeni Kabanov @ekabanov

A very ambitious talk about how to use Jenkins, Sonatype Nexus and LiveRebel to automatically build your stuff, test the build, have it reviewed by QA and finally live deployed to production. Although i did not understand everything and we have no need for such a setup at the moment, that was all i needed to finally occupy myself with Jenkins for my team.

Practical Git by Matthew McCullough @matthewmccull

I’m using git for my own projects for about 2 and a half year now and i never regretted the switch from SVN. At work the situation is quite different (somewhere there is still a CVS repository that hounds me (also, the code inside) what i’m not prepared). We still at SVN but after Matthews talk i have some more arguments at hand.

That is to say my own experience with git already changed my way i use branches and i can fully confirm Matthews views about branches. Explaining this to people who are used to SVN can be quite hard. As is branching and merging in SVN.

Good show with a lot of live hacking and talking afterwards.

W-JAX 2012 was quite good, met a lot of kind people and heard interesting stuff. Now i’m looking forward to the Spring workshop tomorrow.

JPA Criteria Query or plain SQL

25-Sep-12

Note: The following stuff is not Hibernate specific but is true for every JPA2 provider and falls into the category of JPA criteria query.

Some days ago i just saw this video Christin Gorman about Hibernate. Although i don’t agree with her and i actually do like hibernate as a great tool, there are certainly some flaws and pitfalls in some of the designs, especially if the stuff you want to select isn’t totally easy to get.

I’m writing on a little scheduler whose data model looks like so:

Scheduler

There are tasks that have an one-to-many relation to parameters which are their default parameters. Jobs consists of a task (a many-to-one relation) and optional a list of concrete parameters (an one-to-many relation from jobs to job_parameters).

There is a foreign key that ensures that concrete parameters can only be from the jobs task.

Nothing fancy so far on the database site. The JPA mapping already get’s kinda complicated as i want to reproduce the constraint on job_parameters (on columns parameter_id and task_id) that references a unique constraint on tasks so i must use an @EmbeddedId on the task parameter entity.

That’s not the hard part.

I want a query that returns the names of all default parameter for a given job and have not been used on that job. In SQL i would write it down like so:

SELECT defaultParameter.name FROM sch_jobs jobs 
  JOIN sch_tasks tasks ON tasks.id = jobs.task_id
  JOIN sch_task_parameters defaultParameter ON defaultParameter.task_id = tasks.id
 WHERE jobs.id = :job_id
   AND defaultParameter.name LIKE '%' || '%'
   AND NOT EXISTS (
	   SELECT '' FROM sch_job_parameters concreteParameters
	    WHERE concreteParameters.job_id = jobs.id
	      AND concreteParameters.task_parameter_id = defaultParameter.id
   );

and be done with it.

If i would for whatever reason use a JPA Query along with the typesafe JPA Metamodel the method that gets me the list of unused parameters looks like this:

final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
final CriteriaQuery<SchedulerDefaultParameter> criteriaQuery = cb.createQuery(SchedulerDefaultParameter.class);
 
// The "root" of the query... See how it differs from the result type?
final Root<SchedulerJob> jobs = criteriaQuery.from(SchedulerJob.class);
// Joining to other entities
final Join<SchedulerTask, SchedulerDefaultParameter> defaultParameter = jobs.join(SchedulerJob_.task).join(SchedulerTask_.parameters);
 
// Preparing the subquery for the not exists clause		
final Subquery<SchedulerConcreteParameter> subQuery = criteriaQuery.subquery(SchedulerConcreteParameter.class);
final Root<SchedulerConcreteParameter> concreteParameter = subQuery.from(subQuery.getResultType());
 
return entityManager.createQuery(
		criteriaQuery.select(defaultParameter).where(
				cb.and(
						cb.equal(jobs.get(SchedulerJob_.id), jobId),
						cb.like(cb.function("lower", String.class, defaultParameter.get(SchedulerDefaultParameter_.name)), name.toLowerCase() + "%"),
						cb.not(cb.exists(
								subQuery.select(concreteParameter).where(
										cb.and(
												cb.equal(concreteParameter.get(SchedulerConcreteParameter_.job), jobs),
												cb.equal(concreteParameter.get(SchedulerConcreteParameter_.defaultParameter), defaultParameter)														
										)
								)
							)
						)
				)
		)
).getResultList();

What do i have now? A complete typesafe query that gives me a compilation error as soon as i change the mapping in an incompatible way.

And the price? As soon as i have written this post i forget how this stuff actually works.

As much as i like the automatic generation of standard joins and lookups and stuff that JPA respectively Hibernate in my case does, i’d never advocate to enforce some rules “only use JPA criteria” just for sake of compile time query checking.

I think that many people forget about the one true advantage of using sql: Telling the database what you want to have and not how you want to have it selected…

Java 7, JAAS and Kerberos Single Sign-on vs. newer Windows Systems

23-Jul-12

Java Authentication and Authorization Service aka JAAS is a pretty neat way to build a pluggable authentication mechanism for a Java application.

My goal was to build a Single Sign-on (SSO) mechanism targeted on Windows machines (Windows XP SP3, Windows 7) that uses the cached kerberos ticket.

The jaas configuration should be pretty simple:

name_of_the_login_context {
    com.sun.security.auth.module.Krb5LoginModule required
    	debug=true
    	doNotPrompt=true    
    	useTicketCache=true        
    	renewTGT=true
    ;    
};

This means: Require and use the Krb5LoginModule module, do not prompt for a user details and use the windows ticket cache. As it turns out, this works out of the box with Java 6 but does not with Java 7.

Java 7 respects a Windows feature that disables the export of Sessions Key for Ticket-Granting Tickets so the native TGT on Windows (XP with SP2, Vista and 7) has an empty session key.

To enable the export of non empty Session keys add the following registry setting on Vista, 7 and Server:

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\Kerberos\Parameters
Value Name: AllowTgtSessionKey
Value Type: REG_DWORD
Value: 0x01  ( default is 0 )

and this on XP SP2

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\Kerberos\
Value Name: AllowTgtSessionKey
Value Type: REG_DWORD
Value: 0x01

I expected the configuration to work… But it didn’t. It seems there are problems with User Account Control (UAC) and domain users that are local admins (so is my account on my machine). I tried to disable UAC (not acceptable for either me or the customer), adding the setting above to the KDC server, creating a krb5.ini file and some other attempts but no success. The jaas configuration started to work as soon as i removed my account from the local admins. Funny thing is: I readded it and it still works.

While doing my research i found several other irritating behaviors:

As SSO wasn’t working, it tried the following JAAS config:

name_of_the_login_context {
    com.sun.security.auth.module.Krb5LoginModule required
    	debug=true
    	useTicketCache=false
    ;    
};

This should force a login prompt with an adequate javax.security.auth.callback.CallbackHandler. On my Windows 7 machine Java 6 *does* need a krb5.ini file under c:\windows, Java 7 does not.

The exception with Java 6 is: “KrbException: Could not load configuration file C:\Windows\krb5.ini”

So i created one… After that, i had a “KrbException: Message stream modified (41)”, great, thanks. The problem here is the case sensitivity of the realm name. If the domain is FOOBAR and the krb5.ini contains

[realms]
    foobar = {
        kdc = dc.foobar
        admin_server = dc.foobar
        default_domain = foobar
    }

the authentication will fail. If the kdc returns the realm as FOOBAR, the krb5.ini must contain the realm FOOBAR like so

[realms]
    FOOBAR = {
        kdc = dc.foobar
        admin_server = dc.foobar
        default_domain = foobar
    }

Seems to be fun for the whole family… Hopefully this will save someone else some hours of frustration.

tl;dr

  • Java 6 on Windows 7 needs a krb5.ini file when useTicketCache == false
  • The realm name in krb5.ini is case sensitive
  • Kerberos SSO under Windows works only with AllowTgtSessionKey set to 1 under HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\Kerberos\Parameters
  • Kerberos SSO doesn’t work reliable with Domain Users that are local machine admins due to UAC

Update on the location of the jaas.conf file

I was asked how and where to specifiy the location of the JAAS configuration file. You basically have 3 options (for Java 7).

  • The JRE looks for a default jaas.conf in
    “file:${user.home}/.java.login.config”
  • You can add configuration files to java.security located in “lib/security” in the JRE base directory like so:
    “login.config.url.1=file:C:/config/.java.login.config”
  • Or you can specify the jaas configuration on the command line with:
    “-Djava.security.auth.login.config=path_to_file”

Take care of net.sf.ehcache.transaction.TransactionTimeoutException

15-Feb-12

The net.sf.ehcache.transaction.TransactionTimeoutException is one of those unchecked RuntimeExceptions you should take care of if you use ehcache. If this exceptions occurs you must explicitly rollback the ongoing transaction, otherwise all further requests to start an ehcache transaction from within the current thread will fail with another net.sf.ehcache.transaction.TransactionException as the cache is in an inconsistent state.

I do it like so:

final TransactionController transactionController = cacheManager.getTransactionController();
try {
	transactionController.begin();
	// Do stuff
	transactionController.commit();
} catch(TransactionTimeoutException e) {
	// Rollback transaction because cache will be invalid from this point
	transactionController.rollback();
	// Rethrow or handle e in some way
}

Close
E-mail It