Squareroot (sqrt) with BigDecimal

Recently I was refactoring some code from using double to using BigDecimal and suddenly needed a square root method.

I remembered years ago I was taught a simple “successive approximation” method; believe it was grammar school.

I searched the net and found the “Babylonian method” (which is actually a “Newton-Raphson method” implementation). This is the method I was taught and I present a BigDecimal-implementation here.
Continue reading

Posted in Java | Tagged , | 2 Comments

Implementing a simple database semaphore

In this article I will describe a simple technique that enables you to implement an “exclusive lock” in a distributed, even clustered, environment.

The technique works with all major databases, and should work with any database that has a reasonable implementation of the isolation level “READ COMMITTED”.

It works with PostgreSQL, DB2, Oracle and Apache Derby (JavaDB) and possibly others.

The technique can be used to serialize access to a specific entity or object graph in a system, where several application servers share a common database.
Continue reading

Posted in Databases, Java | Tagged , , , , , , , , | 9 Comments

Financial (monetary) computations using floating point arithmetic [in JAVA]

In this article, I will discuss some of the issues in doing financial calculations in JAVA.

The issues are not related to JAVA only, but to any calculation done in a “computer language” using binary floating point arithmetic, including calculations done in spreadsheets like Excel (see References).

In JAVA, the issues can be solved by using the java.math.BigDecimal type, that has been vastly improved in JAVA 5. But compared to similar implementations using the native double type, the code is clumsy and performance suffers.
Continue reading

Posted in Java | Tagged , | Leave a comment

Securing J[2]EE applications, part 3

In this third article, the samples are modified to be run on JBoss (4.0.3+) and JavaDB (Derby version 10.2).

The first article showed how to setup Glassfish authentication with only a single database table.

The second article evovled the simple setup into a more mature setup, where users, logins and roles/groups are separated.
Continue reading

Posted in Databases, Java, Open Source | Tagged , , , | Leave a comment

Securing J[2]EE applications, part 2

The first part, Securing J[2]EE applications, part 1, discusses a simple setup where a single database table, 2 views and a correctly configured jdbcRealm could handle the most basic authentication and authorization requirements.

This second article discusses a few enhancements to the first setup, enabling more complex user and group setup scenarios. This article discusses the possible difference between a user and a login and describes a setup where any user can be assigned to any group.

Last but not least, the 2 articles together show the strength of using views to encapsulate database infrastructure, as the jdbcRealm does not need any configuration changes at all, to accommodate the different setups.
Continue reading

Posted in Databases, Java, Open Source | Tagged , , , | Leave a comment

Securing J[2]EE applications, part 1

I’m writing a few articles about securing J2EE applications. The setup is a Glassfish v2 as application server and PostgreSQL v8.3 as database server, keeping it open-source and free 🙂

This first part discusses a simple setup where only a single table is used for storing user-information. It includes information about how to configure the standard Glassfish jdbcRealm to use the information for authentication and using views to hide database implementaion details.

Basically a simple application is secured, enabling only registered users access.
Continue reading

Posted in Databases, Java, Open Source | Tagged , , , | Leave a comment

Trusting any “secure” host

My main concern is developing server-side JAVA-applications: J[2]EE applications.

When working with hobby-projects, I’m often faced with situations where I need to call other “third-party” applications over HTTP, in order to obtain some information important to me in specific situations.

It is not uncommon for local/public organizations to publish sensitive information over HTTPS where the SSL-certificates are not signed by some known issuer.

Also when working with SSL in test-setups, one usually don’t spend time and money on “real” certificates, but uses self-signed certificates.

This is generally not a problem as I as a user can select to accept “invalid” certificates, when contacting a host that I trust.
Contacting hosts with invalid certificates using a browser is not a problem: one just accepts the invalid certificate or import the unknown issuer into the trust-store.

When contacting those hosts using JAVA, one is faced with a SSLHandshakeException:

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1611)
	at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:187)
	at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:181)
	at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1035)
	at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:124)
	at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:516)
	at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:454)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:884)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1112)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1139)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1123)
	at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:434)
	at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:166)
	at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:133)

Continue reading

Posted in Java | Tagged , , | Leave a comment

Writing JDBC code: resource cleanup and exception handling

No matter how nice an ORM tool used in the project, CMP, Hibernate or JPA, You will eventually have to start writing “low-level” JDBC code. Most often for performance reasons, sometimes just to utilize some database-vendor-specific feature.

Or calling stored procedures…

I’ve written lots of “low-level” JDBC code – most done in the days of 1.0..2.1 EJB CMP where some fastlane pattern was often necessary to deal with complex queries.

Most “query” code looks familiar to the sample below:

Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
	con = getConnection();
	ps = con.prepareStatement(sql);
	//... set parameters
	rs = ps.executeQuery();
	while (rs.next()) {
		//...handle result
} catch (SQLException e) {
	//...exception handling
} finally {
	if (rs != null) {
	if (ps != null) {
	if (con != null) {

This particular piece of code has always been a nuiscance to me, for the following reasons:
Continue reading

Posted in Databases, Java | Tagged , | 1 Comment

The “changing the database” experience

I have been involved in Enterprise JAVA projects since 1998. Almost all projects have had an RDBMS “behind” it, mostly Oracle and DB2.

All the projects have been some custom defined application often based on existing infrastructure, and the database vendor and version has been predefined from the beginning.

Still, there has almost always been a more or less explicit demand that the application being developed should be easily ported to another database vendor. Until now, this has never happened to me; I have never been in a situation where the customer suddenly decides to change their entire database infrastructure from one major database vendor to another.

Except for one situation: I was involved in a project where we were developing a version-2 of an existing application. The original application was based on Microsoft tools and databases; the new application was to be based on J2EE and Oracle.

The demand that the application should be easily portable to another database basically has the following impact on the development:

  • Use a good, preferably a standard-, ORM tool can help hide technical details about the database integration, and can enable you to write your queries in an “abstract query language”.
  • Minimize the use of native SQL, vendor specific database features, stored procedures, triggers and user defined functions. They will have to be portable and a database specialist is often needed. Some features in one RDBMS might not have comparable features in other RDBMS’.
  • Hard coding SQL in the application is forbidden – all SQL must be in configuration files external to the code to ease translation.

Of course, if the application is a general component or a product to be used by many different customers or users, the demands on the database integration is even harder – you can only rely on the most basic features common to all the supported databases.

There are other good reasons for points mentioned above, but in this article I’m taking the perspective of creating applications that are easily ported to other databases.

In the following I will discuss some of the experiences that I have had with a recent project, where we ported the entire persistence layer from Oracle to PostgreSQL.

Continue reading

Posted in Databases, Java | Tagged , , , , , , , , , | Leave a comment

Real world distributed transactions in J2EE – Not ?

I’m on this project where we develop a component. This is a J2EE component, it has its own database and it does some mainframe communication. This component is to be deployed on a WebSphere application server, version 6.1 (WAS).

The component is to be used by a specific J2EE application. This application is to be deployed on an Oracle Application Server (OC4J) – possibly version The application also has its own database…

Transactions are really important to this component. The “local” database has to be “in sync” with the mainframe, and we are taking care to have 2-phase commit (2PC) between the component, the database and the mainframe. Note that the mainframe is allowed to rollback a transaction during transaction completion.

Transactions are really important to the entire application; the application database, the “component local” database and the mainframe has to be “in sync”. Basically the global transactions are started in the application, propagated over the component into the mainframe and back…

Now, everything except the mainframe is Java and J2EE so the question about how to have the different subsystems participate in global distributed transactions should have an obvious answer: use session beans and RMI/IIOP.


Continue reading

Posted in Java | Tagged , , , , | Leave a comment