29 September 2024
Server-side HTML generation
I have been trying out htmx with Kotlin and http4k.
To use htmx, you need some way of generating HTML on the server. In Kotlin, you have plenty of options, both Kotlin specific ones and everything from the broader Java/JVM ecosystem. There are two main categories here, template languages and internal DSLs.
Given Kotlin’s good support for internal DSLs, I decided to explore that route, and try kotlinx.html and HtmlFlow. They both make great promises of encoding the entire HTML standard and enforce valid HTML at compile time.
14 September 2024
No streaming with pgJDBC
I am using PostgreSQL from a Kotlin (JVM) application with the pgJDBC driver.
According to the documentation, you can get results from a query based on a cursor to avoid loading the whole result set into the application’s memory at once by calling the setFetchSize() method with a positive value on the Statement before issuing the query.
I had a non-trivial query which generated a lot of rows (several thousands), and I only needed the first hundred or so.
2 November 2022
How to capture log events in tests with Log4j 2
Sometimes you want to verify that your program actually logs what it is supposed to be logging.
When using Apache Log4j 2 as logging framework, it can be done like this:
Include this dependency (for Maven, adjust appropriately for other build systems): <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <type>test-jar</type> <scope>test</scope> </dependency> Import some stuff: import org.apache.logging.log4j.core.Logger; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.test.appender.ListAppender; Add a ListAppender to the logger you are interested in: var loggerContext = LoggerContext.
30 July 2019
How to run exec-maven-plugin only if a file is not up-to-date
In my Maven build, I use exec-maven-plugin to run an external tool for Java code generation. In this case the flatbuffers compiler (flatc).
By default, flatc always runs, so you always get a new .java file. This will always trigger Java compiler to run, which will in turn always trigger jar packaging to run, etc. I would like flatc to only run if it’s source file is updated, so I can get a properly incremental build and avoid needlessly recompiling.
8 February 2016
Objects vs. data structures
Several popular statically typed programming languages, including C++, Java and C#, have a serious design flaw. They make no useful distinction between objects in the OOP sense and plain data structures.
A plain data structure should only be a dumb container for data. It should not have any behaviour, only simple accessors for data items in it. It should not be possible to override data accessors. It should be clear and transparent what it does.
3 August 2015
Typesafe’s Reactive Straw man
In their quest to promote Reactive, Typesafe is beating up a straw man by portraying blocking I/O in a particularly stupid way which is rarely (if ever) done in practice.
In a recent webinar, I found this slide which suggests that a blocking I/O operation will waste CPU time while waiting for the I/O to complete.
If I understand it correctly, it does not actually work like this in any reasonable runtime environment / operating system.
26 October 2014
Create a self-contained .jar file with Maven
If you want to create a self-contained .jar file, with all library dependencies included, you can do it with Maven. Include this in your pom.xml:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>2.4</version> <configuration> <archive> <manifest> <mainClass>com.yourcompany.youapp.Main</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> <executions> <execution> <id>make-jar-with-dependencies</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> </build> Then when you run mvn package, you will get a target/*-jar-with-dependencies.jar file which you can run with java -jar.
2 October 2014
Running Jetty as a service in Ubuntu Linux
Jetty is a popular open source Java application server. In order to run it as a service on a Linux server, they recommend using a horribly overcomplicated and quite fragile script.
In Ubuntu server, there is a better way. Leverage Upstart and its declarative job definitions.
First install Jetty into /opt/jetty and create a jetty user:
useradd --user-group --shell /bin/false --home-dir /opt/jetty/temp jetty Then create a file /etc/init/jetty.conf with content like this:
5 June 2014
Don’t use large BLOBs in MySQL from Java
The MySQL database can store large chunks of binary data (up to 1 GB) using the BLOB data types.
However, this does not work well if you access the MySQL database from Java (or any other JVM based language) using the MySQL JDBC driver.
The JDBC API supports an efficient stream based way to handle BLOBs, but the MySQL JDBC driver does not implement this properly. It works, but it will buffer all data in memory in a way which is very inefficient and can make your JVM run out of memory if the BLOBs are large.
4 March 2014
Don’t use PipedOutputStream on Android
I was using java.io.PipedOutputStream in an Android app. The app performed horribly bad. After doing some profiling, it turned out that the call to PipedOutputStream.write(byte[]) that was really slow. After digging into the Android source code, I discovered that PipedOutputStream.write(byte[]) was not implemented, it just delegated to the default implementation in OutputStream which iterate through the array and call PipedOutputStream.write(byte) for each byte.
Since PipedOutputStream.write(byte) does some synchronization and Object.notifyAll() each time, it is really slow to do this 1000 times when you write a block of 1 KB data.
13 October 2013
Using an embedded SQL database in Java web application
You have a Java web application needing a relational SQL database. According to JavaEE conventions, you declare the DataSource in web.xml:
<resource-ref> <res-ref-name>jdbc/DS</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> and then fetch it in code with (DataSource)new InitialContext().lookup("java:comp/env/jdbc/DS").
Using Maven, Jetty and HSQLDB, you can very easily run the web application for local testing without having to setup neither a web container, nor a database. Add this to pom.xml:
<build> <plugins> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.
25 November 2010
Web application frameworks in Java
When you know which type of web application you are to develop, it’s time to have a look at some possible choices.
I have tried to categorize some modern and popular web application frameworks in Java.
Simple server driven MVC page based This category contains the traditional frameworks used for developing web applications with purely server driven application logic. They are based on complete HTML pages and uses the Model-View-Controller design pattern.
9 June 2010
Using Vaadin with Maven
Vaadin is a comprehensive framework for developing web applications in Java. The Vaadin web site presents a number of ways to use Vaadin with Maven, but I am not completely satisfied with any of those. Here is how I do it.
Use a pom.xml like this:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.thecompany</groupId> <artifactId>theapp</artifactId> <version>1.0</version> <packaging>war</packaging> <name>The App</name> <dependencies> <dependency> <groupId>com.vaadin</groupId> <artifactId>vaadin</artifactId> <version>6.3.3</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.
29 April 2010
Implementing POX Web Services with Spring WS and JAXB
Spring Web Services together with JAXB 2.0 provides a convenient way to implement POX Web Services in Java.
POX means Plain Old XML, and a POX Web Service is a protocol based on sending XML over HTTP without using any well-known protocol framework like SOAP or XML-RPC.
First you have to define annotated JAXB classes for all XML request and response messages. If you have a schema, you can generate them with the xjc tool.
16 April 2010
How to implement RESTful JSON Web Services in Java
You can implement RESTful Web Services in Java using the JAX-RS framework.
JAX-RS is part of the JavaEE 6 platform. But if you are not using a JavaEE 6 application server, you can use the reference implementation Jersey and embed it in any web application server.
However, it’s quite awkward to produce JSON output from Jersey.
Jersey has some support for producing JSON via JAXB, but to get the NATURAL encoding (which you probably want) you need JAXB 2.
13 August 2009
java.util.Map is broken in Java 5
Java 5 added generics. The collection classes was modified to make use generics to provide compile-time type-safe collections. Sadly, this was not done properly.
The worst problem is in the interface java.util.Map:
public interface Map<K,V> { // more methods... V get(Object key); V remove(Object key); boolean containsKey(Object key); boolean containsValue(Object key); } The key parameters to these methods ought to be declared to be K and not Object. Now we don’t get any type-safety for those methods.
23 April 2009
Type safe JSP and JSTL
When using JavaServer Pages, you want to use JSTL to be able to to flow-control (iterations and conditionals) in a reasonable way. And the recommended way to use JSTL is to use the Expression Language (EL).
However, using EL is not a good idea at all. Contrary to Java and plain JSP, EL lacks static typing. This means that many errors which the compiler can catch is not detected until runtime when using EL.
23 April 2009
java -classpath *.jar
It’s quite annoying that you cannot use wildcards in the -classpath command line option to java and javac. Quite often you want to include all .jar files in one directory.
Here is a way to get that effect:
java -classpath `echo lib/*.jar | sed -e “s/ /:/g”` org.foo.MyApp
You can even include all .jar files in a whole hierarchy of directories:
java -classpath `find repository -name *.jar -printf %p:` org.foo.MyApp
16 December 2008
Configure web applications in JBoss
When you deploy a web application in a JavaEE application server, it usually consist of a .war archive.
Sometimes, the web application needs some configuration parameters. The most common way to do this is to have <context-param> in web.xml. That is simple and works fine except that the web.xml file needs to be inside the .war archive. This makes it inconvenient to change a configuration parameter since you have to repack the .
21 May 2007
Common mistakes with exceptions in Java
Unintentional catching of runtime exceptions Unfortunately, checked exceptions in Java are defined as all Exceptions which are not RuntimeExceptions. This makes it a bit tricky to catch all checked exceptions (but not any runtime exceptions). It would have been better if checked exceptions were defined by a specific class, CheckedException, but that’s too late to change now.
Too often Java programmers catch all exceptions when they really only should catch checked exceptions.
11 May 2006
Who needs rmiregistry?
Java Remote Method Invocation (RMI) contains a tool rmiregistry to run a stand-alone remote object registry. According to the RMI tutorial, rmiregistry is normally used in an RMI application.
I wonder why. It’s actually almost as simple to run the remote object registry within the RMI server. You only have to use java.rmi.registry.LocateRegistry#createRegistry(int port) method like this:
Registry registry = LocateRegistry.createRegistry(port); registry.bind("Foo", stub); Here is a complete example.
This is also more efficient since you don’t have to start a separate JVM for the registry.