Hibernate: could not locate named parameter

December 18, 2009

Today I got this exception. Pretty obvious? Well, no. The named parameter IS there. (Sidenote: this exception generally means that when trying to call setParameter(..) with a certain param name, that name is not found in the query, in the form :paramName)
The query is generated dynamically on different entities. And it works, except for one.
And that “one” turned out NOT to be an @Entity. But Hibernate wasn’t too helpful on that.

So to summarize, when you attempt to make a query on a non-entity, Hibernate will not complain that it is not an entity – it will complain about other things.

Advertisements

Custom exceptions thrown from service layer with spring transaction support

December 6, 2009

The title explains the preconditions:

  • spring beans (conforming to an interface), using @Transactional (or <tx:advice>)
  • custom exception is thrown from within the service methods
  • There is a little trick – if the exception is unckecked (extends RuntimeException), it is being wrapped in a TransactionRollbackException.

    So if you are expecting a custom exception (in a unit test, for example), it must be checked. Which is completely logical, of course, but people are often tempted by the easy usage of unchecked exceptions (no explicit need to declare or catch them).

A month on Stackoverflow

December 4, 2009

Stackoverflow is a programming Q & A site. There are all sorts of developers’ topics can be asked there, and most of them get answered pretty quickly. I won’t go into details about Stackoverflow itself, but rather my first month there.

The result of my first month there is 3200 reputation points, top ranks (during the last 30 days) in the tags: java, hibernate, spring, jsf, but, more importantly – more knowledge. Yes, I’ve asked only 5 questions, but in the process of answering questions, and seeing others’ answers, one gains better knowledge and understanding on various topics. Answering is both a race for a better and more complete answer, and a brainstorming on the exact context of the question. When providing an answer to a non-trivial question, you perfect yourself in quick problem-solving.

As for the questions asked – most of them can be answered by a simple google search. Most of the people are too lazy to read tutorials, and ask stupid questions instead. Unfortunately, the answers to the easiest questions let you gain more reputation, and the answers to the complex questions – less. Simply because few people are digging into the complex questions, let alone the complex answers.

So as a conclusion of my first month there – Stackoverflow is one of the best places for developers to go whenever bored, so that they can feed both their egos and heads a little.

Database integration testing / unit-testing with Spring, JPA, JUnit and Maven

November 22, 2009

The exact name for this tests is disputable. Whether it should be “database integration testing” or “unit testing”. But anyway, it is about this:
Many applications’ service layer relies heavily on database operations (through a JPA provider, for example), even though the access to the database is abstracted in a DAO layer.
An option for pure unit tests is to mock the DAO handler (using Mockito, EasyMock, etc), but in most cases this would be either a futile excercise, or it will be too complex to create well-behaving mocks.

So, using the following:
– spring 2.5.6
– hibernate entity manager
– junit 4.4
– maven2

we should achieve smooth database integration testing.
First, don’t try junit > 4.4, because spring 2.5.6 doesn’t work with it. Spring 3 will.

So, the steps.

  1. define your database access properties in .properites file and place it in src/main/resources (where the applicationContext.xml should reside as well). These properties should include: the dialect, the connection url, the username/password, the database driver.
  2. create src/test/resources, and create a properties file with the same name there, and set test-database parameters (using HSQLDB for example). Make the output folder for this source folder to be target/test-classes.
  3. in applicationContext.xml add
    <context:property-placeholder location="classpath:application.properties" />
  4. in src/test/java, in an appropriate package, create the following class:
    package com.tickets;
    
    import org.junit.runner.RunWith;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations="classpath:/applicationContext.xml")
    public abstract class BaseTest {
    
    }
    
  5. Make all your test classes extend BaseTest (or alternatively, add those annotations on all classes)
  6. For additional capabilities, transactions, autowiring, etc, refer to the Spring documentation
  7. Run your unit tests either from within your IDE, or via maven. It works both ways.

Deep @Embedded Hibernate entity hierarchy with Oracle

November 13, 2009

If you want to have a deep @Embeddable Hibernate entity hierarchy with Oracle – you are not welcome. Oracle has a genious unconfigurable (at least after a lot of search) limit for column names – 30 characters.
Hibernate (JPA’s actually) @Embedded and @Embeddable annotations provide the possibility to have a deep hierarcy of objects that will be represented in one table in the database. (The reasons to use such hierarchy is beyond the scope of this post.). Hibernate generates the names for the columns using all property names down the hierarcy. For instance: person_address_street_number But these names often get long and oracle says “identifier too long”. You can set @Column(name=”something”) at the bottom of the hierarchy, but it is not a rare case that one class, or one column name is found twice in the same entity (ergo table). So a duplicate column name problem appears.

The resolution, although not very beautiful, is to write a custom NamingStrategy which abbreviates the columns. A sample would look like this:

public class PrefixNamingStrategy extends DefaultComponentSafeNamingStrategy {

    private static final int MAX_ORACLE_ALLOWED_CHARS = 30;
    private static final int MAX_PART_LENGTH = 4;
    private static final int MAX_PART_SHORT_LENGTH = 3;

    @Override
    public String propertyToColumnName(String propertyName) {
        // Take the last column name before calling propertyToColumnName
        // in order to preserve casing
        String lastPropertyName = propertyName;
        if (lastPropertyName.indexOf(".") != -1) {
            lastPropertyName = lastPropertyName.substring(lastPropertyName.lastIndexOf(".") + 1);
        }

        // Getting the fully qualified, component-safe name of the column
        String columnName = super.propertyToColumnName(propertyName);

        if (columnName.length() <= MAX_ORACLE_ALLOWED_CHARS) {
            return columnName;
        }

        String result = shortenColumnName(columnName, MAX_PART_LENGTH, lastPropertyName,
                false);

        if (result.length() > MAX_ORACLE_ALLOWED_CHARS) {
            result = shortenColumnName(columnName, MAX_PART_SHORT_LENGTH,
                    lastPropertyName, true);
        }

        return result;
    }

    private String shortenColumnName(String columnName, int maxPartLength,
            String lastPropertyName, boolean shortenLast) {
        String[] parts = columnName.split("_");
        for (int i = 0; i < parts.length - 1; i++) {
            parts[i] = parts[i].substring(0, parts[i].length() < maxPartLength ? parts[i]
                    .length() : maxPartLength);
        }

        if (shortenLast) {
            parts[parts.length - 1] = getAbbreviation(lastPropertyName);
        }

        String result = "";
        for (int i = 0; i < parts.length; i++) {
            if (i != 0) {
                result += "_";
            }
            result += parts[i];
        }

        return result;
    }

    private String getAbbreviation(String string) {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < string.length() - 1; i++) {
            if (Character.isUpperCase(string.charAt(i)) || i == 0) {
                buf.append(string.substring(i, i + MAX_PART_SHORT_LENGTH));
            }
        }

        return buf.toString();
    }
}

How to obtain signer’s details from a JavaScript signed data

July 2, 2009

In a previous post I described how to sign data with only javascript. Now, this data should be used on the server side for something. Here is how a Java developer can extract the signature details, and verify whether the content received from a form is really what has been signed. The general scenario is – a user submits a form, the data from which he signs. Then on the server the submitted data should be verified against the signed (PKCS7) data.

One needs the Bouncycastle libraries and apache commons codec:
commons-codec-1.3.jar
bcprov-jdk16-143.jar
bcmail-jdk16-143.jar

package com.materna.remedy.plugins;

import java.security.Security;
import java.security.cert.CertStore;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.cms.CMSProcessable;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.SignerInformationStore;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class CertificateDataExctractor {
	private Map<String, Object> extractInfos(String base64EncodedPKCS7,
			String contentString, boolean isIe) {
		
		try {
			byte[] data = Base64.decodeBase64(base64EncodedPKCS7.trim().getBytes());

			Security.addProvider(new BouncyCastleProvider());

			CMSSignedData signedData = new CMSSignedData(data);

			if (signedData.getSignedContent() == null) {
				byte[] contentBytes;
				if (!isIe) {
					contentBytes = contentString.getBytes();
				} else {
					contentBytes = contentString.getBytes("UnicodeLittleUnmarked");
				}

				CMSProcessable cmsProcesableContent = new CMSProcessableByteArray(
						contentBytes);
				signedData = new CMSSignedData(cmsProcesableContent, data);
			}

			CertStore certsStore = signedData.getCertificatesAndCRLs(
					"Collection", "BC");
			SignerInformationStore signersStores = signedData.getSignerInfos();

			boolean verified = true;
			boolean validCertificate = true;
			Map<String, Object> signerData = null;

			for (Iterator<SignerInformation> iter = signersStores.getSigners()
					.iterator(); iter.hasNext();) {
				SignerInformation signer = iter.next();
				// emulate(signer);

				Collection certCollection = certsStore.getCertificates(signer
						.getSID());

				if (!certCollection.isEmpty()) {
					X509Certificate cert = (X509Certificate) certCollection
							.iterator().next();

					try {
						if (!signer.verify(cert.getPublicKey(), "BC")) {
							verified = false;
						}
					} catch (Exception ex) {
						ex.printStackTrace();
						// if this is an attempt to verify it assuming Firefox,
						// try assuming IE. If it is already IE - the
						// verification doesn't pass
						if (!isIe) {
							return extractInfos(base64EncodedPKCS7,
									contentString, true);
						}
						verified = false;
					}

					// If this is the last signer in the chain, obtain the data
					if (!iter.hasNext()) {
						signerData = extractSubjectInfos(cert);
					}
				}
			}
			return signerData;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}

	}
}

And of course, you provide your own implementation of getSubjectInfos method, putting whatever data you need from the certificate in the Map.

A really useful eclipse shortcut to configure

June 20, 2009

I wonder why it isn’t in the default set – “generate getters and setters”. This is one of the most frequent actions. I’m setting it to ALT+SHIFT+G (Generate).

NoScript and AdBlock plus – two sides to every story

May 2, 2009

(If you don’t want to read too much here, check the links below)

Recently a lot of crap has been written at many places against NoScript (reddit, slashdot, the addon page on mozilla’s site, etc).
We can easily call it a flame war, but that’s not the point – the point is to have a good-working protective solution for any web-behaviour. I don’t use AdBlock plus, but a friend of mine does, and she is pretty happy with it. I’m pretty happy with NoScript, so every train has its passengers. Again – that is not the point. The point is that obviously AdBlock plus developer(s) trying to drive users away from NoScript. As you are reading this, you have probably read the blog-post in ABP site : http://adblockplus.org/blog/attention-noscript-users.

But of course, there is two sides to every story:

http://forums.informaction.com/viewtopic.php?p=2777#p2777

http://noscript.net/faq#qa3_21
https://addons.mozilla.org/en-US/firefox/addon/722 saying:

Notice to AdBlock Plus users: after a targeted attack from EasyList which broke functionality like direct links to development builds on developer’s sites, NoScript 1.9.2.3 and above configure a regular filterset whitelisting them. As any filterset, you can easily disable it with two clicks if you prefer.

And so, I saw a pile of users removing NoScript just for the reason someone has mocked it. How rational. Good luck to those in not getting infected.

“Who started the flame war” is an irrelevant question here – the question is why people are so not-quite-intelligent. I will continue using NoScript.

How to create a digital signing solution with only JavaScript

April 16, 2009

Look at the js-signer project on GitHub

Go to the new version of this blog post

It is sometimes required to have the user sign a text in order to certify that he is the one who has done the operation. For example, in an e-banking software, the user might have to sign a text describing the transaction (“Transfer 300 dollars to IBAN xxxxxxxxx”), or sign a request for a governmental eService. This could be achieved by a java-applet, but as JRE owners are not a majority, it is preferable to use other ways.

Of course, the preconditions are, that the user has a digital signature, issued by a CA, and has followed the CA’s manual for installing the certificate in a browser. If these steps are not completed successfully, the solution below wouldn’t work.

Also, note that this uses PKCS7 (java developers: use bouncy castle to verify it), instead of the XAdES standard. Internet Explorer has support for XAdES, but FireFox doesn’t.

Let’s see a simple HTML page that should sign a given text:


<script src="sign.js" type="text/javascript"></script>

<input id="text" type="text" />
<input onclick="signDigest(document.getElementById('text').value);" type="button" value="Sign" />

and then the JavaScript itself:


function signDigest(text)
{
if(window.event)
window.event.cancelBubble = true;

var dest = sign(text); //TODO
alert(dest);
return dest;
}

// CAPICOM constants
var CAPICOM_STORE_OPEN_READ_ONLY = 0;
var CAPICOM_CURRENT_USER_STORE = 2;
var CAPICOM_CERTIFICATE_FIND_SHA1_HASH = 0;
var CAPICOM_CERTIFICATE_FIND_EXTENDED_PROPERTY = 6;
var CAPICOM_CERTIFICATE_FIND_TIME_VALID = 9;
var CAPICOM_CERTIFICATE_FIND_KEY_USAGE = 12;
var CAPICOM_DIGITAL_SIGNATURE_KEY_USAGE = 0x00000080;
var CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME = 0;
var CAPICOM_INFO_SUBJECT_SIMPLE_NAME = 0;
var CAPICOM_ENCODE_BASE64 = 0;
var CAPICOM_E_CANCELLED = -2138568446;
var CERT_KEY_SPEC_PROP_ID = 6;

function IsCAPICOMInstalled()
{
if(typeof(oCAPICOM) == "object")
{
if( (oCAPICOM.object != null) )
{
// We found CAPICOM!
return true;
}
}
}

function FindCertificateByHash()
{

try
{
// instantiate the CAPICOM objects
var MyStore = new ActiveXObject("CAPICOM.Store");
// open the current users personal certificate store
MyStore.Open(CAPICOM_CURRENT_USER_STORE, "My", CAPICOM_STORE_OPEN_READ_ONLY);

// find all of the certificates that have the specified hash
var FilteredCertificates = MyStore.Certificates.Find(CAPICOM_CERTIFICATE_FIND_SHA1_HASH, strUserCertigicateThumbprint);

var Signer = new ActiveXObject("CAPICOM.Signer");
Signer.Certificate = FilteredCertificates.Item(1);
return Signer;

// Clean Up
MyStore = null;
FilteredCertificates = null;
}
catch (e)
{
if (e.number != CAPICOM_E_CANCELLED)
{
return new ActiveXObject("CAPICOM.Signer");
}
}
}

function sign(src)
{
if(window.crypto &amp;&amp; window.crypto.signText)
return sign_NS(src);

return sign_IE(src);
}

function sign_NS(src)
{
var s = crypto.signText(src, "ask" );
return s;
}

function sign_IE(src)
{
try
{
// instantiate the CAPICOM objects
var SignedData = new ActiveXObject("CAPICOM.SignedData");
var TimeAttribute = new ActiveXObject("CAPICOM.Attribute");

// Set the data that we want to sign
SignedData.Content = src;
var Signer = FindCertificateByHash();

// Set the time in which we are applying the signature
var Today = new Date();
TimeAttribute.Name = CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME;
TimeAttribute.Value = Today.getVarDate();
Today = null;
Signer.AuthenticatedAttributes.Add(TimeAttribute);

// Do the Sign operation
var szSignature = SignedData.Sign(Signer, true, CAPICOM_ENCODE_BASE64);
return szSignature;
}
catch (e)
{
if (e.number != CAPICOM_E_CANCELLED)
{
alert("An error occurred when attempting to sign the content, the errot was: " + e.description);
}
}
return "";
}

And that should do the stuff – the signed text can be sent to the server, where it can be verified (in case, of course, the server has the public part of the user’s certificate)

P.S. One important note when verifying afterward – Internet Explorer uses UnicodeLittleUnmarked (UTF-16LE) to encode the signed data, before signing it. So when verifying, use this encoding.

How to iterate over java.util.Set in JSF

March 3, 2009

Go to the new version of this blog post

I spent quite some time trying to find a solution for the following JSF issue: it is not possible to iterate over a java.util.Set.
– ui:repeat (facelets) doesn’t work
– a4j:repeat (richfaces) doesn’t work
– c:forEach works..only in case it does not rely on a variable defined by a parent component (rich:dataTable for instance)

All above are pretty logical phenomena, as UIData relies on ordered data, and generally a Set is not ordered.

In my case I had to use a Set defined in the Hibernate (JPA) object (PersistentSet).
An important note: you should use a set in case the view order is of no matter to you.

The solution..is pretty simple. And I’ll suggest it to be a part of facelets/richfaces for the next version, unless of course there is some valid specific reason for it not to be.

1. Define your own UI component extending an existing repeater component. I used a4j:repeat (HtmlAjaxRepeat)
2. Override the metohd getDataModel
3. Define your component in your faces-config
4. create a custom facelets tag definition
5. Define a context-variable in web.xml pointing to the facelet tag definition.

Note: for use with JSP instead of Facelets, you should define a .tld and a Tag handler, which is not an ojbect of this post.

Now let’s see the steps in detail:

1,2. Here some code:

package com.myproject.components;
import java.util.ArrayList;
import java.util.Set;

import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

import org.ajax4jsf.component.html.HtmlAjaxRepeat;
import org.ajax4jsf.model.SequenceDataModel;

public class UIIterator extends HtmlAjaxRepeat {

   @SuppressWarnings("unchecked")
   @Override
   protected DataModel getDataModel() {
      Object current = getValue();
      if(current instanceof Set){
          return new SequenceDataModel(new ListDataModel(
                new ArrayList((Set) current)));
      }
      return super.getDataModel();
   }
}

So, as we don’t care about the order of the elements, we just create a new ArrayList out of the Set. And we can now easily return the appropirate DataModel.

3. Add this to your faces-config. (I copied it from the a4j definition)

<component>
		<description />
		<display-name>Iterator</display-name>
		<component-type>com.myproject.Iterator</component-type>
		<component-class>com.myproject.components.UIIterator</component-class>

		<component-extension>
			<component-family>javax.faces.Data</component-family>
			<renderer-type>org.ajax4jsf.components.RepeatRenderera</renderer-type>
		</component-extension>
	</component>

4. Here is the tag definition for facelets

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE facelet-taglib PUBLIC
"-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"
"http://java.sun.com/dtd/facelet-taglib_1_0.dtd">
<facelet-taglib xmlns="http://java.sun.com/JSF/Facelet">
<namespace>http://myproject.com/cust</namespace>

<tag>
<tag-name>repeat</tag-name>
<component>
<component-type>com.myproject.Iterator</component-type>
<renderer-type>org.ajax4jsf.components.RepeatRenderer</renderer-type>
</component>
</tag>

</facelet-taglib>

Save this file as /WEB-INF/facelets/custom.taglib.xml

5. Add to your web.xml

<context-param>
<param-name>facelets.LIBRARIES</param-name>
<param-value>/WEB-INF/facelets/custom.taglib.xml</param-value>
</context-param>

6. It is now ready to use

xmlns:cust=”http://myproject.com/cust&#8221;

<cust:repeat var=”myVar” value=”${aSet}”>

</cust:repeat>

I think it is way neater than other workarounds, like defining a custom EL Resolver.