Wednesday 28 July 2010

Postgres Transaction Deadlock

After some changes recently, my application began to hang. I run the Glassfish V2 application server and so went for a stacktrace to ascertain the responsible Java code:

asadmin generate-jvm-report --type=thread

This showed that the server was waiting on the database to return from an update query. This rang alarm bells - a locking wait I suspect...

I decided to check with Postgres which query was waiting:

SELECT procpid, current_query FROM pg_stat_activity;

This showed me that one particular update to my c_account table was waiting.

I was using two transactions: 1 & 2. The code which started tx1 then starts tx2 before committing tx1.

Transaction 1:
Inserts a logging record, referencing c_account with a foreign key.

Transaction 2:
Changes the account bar flag on c_account with an SQL update.

This scenario caused a deadlock, since tx1 takes a row-exclusive lock on the log table and any rows referenced by its foreign keys. When I go to modify the flag on c_account, then tx2 has to wait until tx1 has completed and of course, this will never happen.

Two methods to get around this:
1) Better transaction demarcation. Carefully avoid insert/update referencing the same entity.
2) More locking-aware table design. Have a one-one table for flags such that new records may reference the core entity, without locking the one-one tuple.

For now I am opting for option 1, but will keep option 2 in mind for future table design.

Monday 26 July 2010

Spring -Junit - Testing

Create unit tests the Spring way.

This requires version 4.4 of junit (for v2.5.6 of Spring)
Add the SpringTest module to the test libs

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/MyTestConfig.xml")
public class MyClassTest extends AbstractTransactionalJUnit4SpringContextTests // For Tx enabled tests

Can annotate methods with @NotTransactional to not have a TX created for a method in the test. Methods called inside will still
create TX if they require one.

Don't forget to create your own EntityManager of SessionManager for your persistance.


<context:annotation-config />
<context:component-scan base-package="com.stuff"/>
<aop:aspectj-autoproxy/>

<tx:annotation-driven transaction-manager="transactionManager" />

<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>


<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:persistence-test.xml"/>
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="SQL_SERVER" />
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value="jdbc:sqlserver://127.0.0.1:1433;databaseName=My-TEST" />
<property name="username" value="UserName" />
<property name="password" value="Password" />
</bean>

Monday 19 July 2010

Strange classloader bomb-out in Glassfish V2

LDR5207: EJBClassLoader EJBClassLoader :
doneCalled = true
doneSnapshot = EJBClassLoader.done() called ON EJBClassLoader :
urlSet = [URLEntry : file:/Users/neilbeveridge/Library/glassfish/domains/domain1/lib/classes/]
doneCalled = false
Parent -> ASChain parentCL :: Addons Chain parentCL :: Shared ClassLoader Chain parentCL :: sun.misc.Launcher$AppClassLoader@6d6f0472 URLs ::
, file:/Users/neilbeveridge/Library/glassfish/lib/javaee.jar, file:/System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home/lib/tools.jar, file:/Users/neilbeveridge/Library/glassfish/lib/install/applications/jmsra/imqjmsra.jar, file:/Users/neilbeveridge/Library/glassfish/lib/com-sun-commons-launcher.jar, file:/Users/neilbeveridge/Library/glassfish/lib/com-sun-commons-logging.jar, file:/Users/neilbeveridge/Library/glassfish/imq/lib/jaxm-api.jar, file:/Users/neilbeveridge/Library/glassfish/imq/lib/fscontext.jar, file:/Users/neilbeveridge/Library/glassfish/imq/lib/imqbroker.jar, file:/Users/neilbeveridge/Library/glassfish/imq/lib/imqjmx.jar, file:/Users/neilbeveridge/Library/glassfish/imq/lib/imqxm.jar, file:/Users/neilbeveridge/Library/glassfish/lib/webservices-rt.jar, file:/Users/neilbeveridge/Library/glassfish/lib/webservices-tools.jar, file:/Users/neilbeveridge/Library/glassfish/lib/mail.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-jstl.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jmxremote_optional.jar, file:/Users/neilbeveridge/Library/glassfish/lib/SUNWjdmk/5.1/lib/jdmkrt.jar, file:/Users/neilbeveridge/Library/glassfish/lib/activation.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-rt.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-admin.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-cmp.jar, file:/Users/neilbeveridge/Library/glassfish/updatecenter/lib/updatecenter.jar, file:/Users/neilbeveridge/Library/glassfish/jbi/lib/jbi.jar, file:/Users/neilbeveridge/Library/glassfish/imq/lib/imqjmx.jar, file:/Users/neilbeveridge/Library/glassfish/lib/ant/lib/ant.jar, file:/Users/neilbeveridge/Library/glassfish/lib/dbschema.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-deployment-client.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-ee.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-ext.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-jwsacc.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-launch.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-se.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-tags.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-ws.jar, file:/Users/neilbeveridge/Library/glassfish/lib/asm-3.1.jar, file:/Users/neilbeveridge/Library/glassfish/lib/j2ee.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jackson-asl-0.9.4.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jersey-bundle-1.0.3.1.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jesmf-plugin.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jettison-1.0.1.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jhall.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jmac-api.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jsf-impl.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jsr311-api-1.0.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jxta.jar, file:/Users/neilbeveridge/Library/glassfish/lib/Pack200Task.jar, file:/Users/neilbeveridge/Library/glassfish/lib/shoal-gms.jar, file:/Users/neilbeveridge/Library/glassfish/lib/toplink-essentials-agent.jar, file:/Users/neilbeveridge/Library/glassfish/lib/toplink-essentials.jar, file:/Users/neilbeveridge/Library/glassfish/
constituent CLs ::
constituent CLs ::
:: asimpl :: optionalChain
AT Mon Jul 19 16:08:56 BST 2010
BY :com.sun.enterprise.loader.EJBClassLoader.printStackTraceToString(EJBClassLoader.java:813)
com.sun.enterprise.loader.EJBClassLoader.done(EJBClassLoader.java:173)
com.sun.enterprise.deployment.backend.Deployer.releaseClassLoader(Deployer.java:585)
com.sun.enterprise.deployment.backend.Deployer.finish(Deployer.java:572)
com.sun.enterprise.deployment.backend.ModuleDeployer.doRequestFinish(ModuleDeployer.java:226)
com.sun.enterprise.deployment.phasing.J2EECPhase.runPhase(J2EECPhase.java:208)
com.sun.enterprise.deployment.phasing.DeploymentPhase.executePhase(DeploymentPhase.java:108)
com.sun.enterprise.deployment.phasing.PEDeploymentService.executePhases(PEDeploymentService.java:966)
com.sun.enterprise.deployment.phasing.PEDeploymentService.deploy(PEDeploymentService.java:283)
com.sun.enterprise.deployment.phasing.PEDeploymentService.deploy(PEDeploymentService.java:835)
com.sun.enterprise.management.deploy.DeployThread.deploy(DeployThread.java:187)
com.sun.enterprise.management.deploy.DeployThread.run(DeployThread.java:225)
Parent -> ASChain parentCL :: Addons Chain parentCL :: Shared ClassLoader Chain parentCL :: sun.misc.Launcher$AppClassLoader@6d6f0472 URLs ::
, file:/Users/neilbeveridge/Library/glassfish/lib/javaee.jar, file:/System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home/lib/tools.jar, file:/Users/neilbeveridge/Library/glassfish/lib/install/applications/jmsra/imqjmsra.jar, file:/Users/neilbeveridge/Library/glassfish/lib/com-sun-commons-launcher.jar, file:/Users/neilbeveridge/Library/glassfish/lib/com-sun-commons-logging.jar, file:/Users/neilbeveridge/Library/glassfish/imq/lib/jaxm-api.jar, file:/Users/neilbeveridge/Library/glassfish/imq/lib/fscontext.jar, file:/Users/neilbeveridge/Library/glassfish/imq/lib/imqbroker.jar, file:/Users/neilbeveridge/Library/glassfish/imq/lib/imqjmx.jar, file:/Users/neilbeveridge/Library/glassfish/imq/lib/imqxm.jar, file:/Users/neilbeveridge/Library/glassfish/lib/webservices-rt.jar, file:/Users/neilbeveridge/Library/glassfish/lib/webservices-tools.jar, file:/Users/neilbeveridge/Library/glassfish/lib/mail.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-jstl.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jmxremote_optional.jar, file:/Users/neilbeveridge/Library/glassfish/lib/SUNWjdmk/5.1/lib/jdmkrt.jar, file:/Users/neilbeveridge/Library/glassfish/lib/activation.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-rt.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-admin.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-cmp.jar, file:/Users/neilbeveridge/Library/glassfish/updatecenter/lib/updatecenter.jar, file:/Users/neilbeveridge/Library/glassfish/jbi/lib/jbi.jar, file:/Users/neilbeveridge/Library/glassfish/imq/lib/imqjmx.jar, file:/Users/neilbeveridge/Library/glassfish/lib/ant/lib/ant.jar, file:/Users/neilbeveridge/Library/glassfish/lib/dbschema.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-deployment-client.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-ee.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-ext.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-jwsacc.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-launch.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-se.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-tags.jar, file:/Users/neilbeveridge/Library/glassfish/lib/appserv-ws.jar, file:/Users/neilbeveridge/Library/glassfish/lib/asm-3.1.jar, file:/Users/neilbeveridge/Library/glassfish/lib/j2ee.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jackson-asl-0.9.4.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jersey-bundle-1.0.3.1.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jesmf-plugin.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jettison-1.0.1.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jhall.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jmac-api.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jsf-impl.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jsr311-api-1.0.jar, file:/Users/neilbeveridge/Library/glassfish/lib/jxta.jar, file:/Users/neilbeveridge/Library/glassfish/lib/Pack200Task.jar, file:/Users/neilbeveridge/Library/glassfish/lib/shoal-gms.jar, file:/Users/neilbeveridge/Library/glassfish/lib/toplink-essentials-agent.jar, file:/Users/neilbeveridge/Library/glassfish/lib/toplink-essentials.jar, file:/Users/neilbeveridge/Library/glassfish/
constituent CLs ::
constituent CLs ::
:: asimpl :: optionalChain
was requested to find class com.sun.enterprise.management.deploy.DeployThread.LogStrings_en after done was invoked from the following stack trace
java.lang.Throwable
at com.sun.enterprise.loader.EJBClassLoader.findClassData(EJBClassLoader.java:708)
at com.sun.enterprise.loader.EJBClassLoader.findClass(EJBClassLoader.java:628)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at java.lang.ClassLoader.loadClass(ClassLoader.java:296)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at java.util.ResourceBundle$Control.newBundle(ResourceBundle.java:2289)
at java.util.ResourceBundle.loadBundle(ResourceBundle.java:1364)
at java.util.ResourceBundle.findBundle(ResourceBundle.java:1328)
at java.util.ResourceBundle.findBundle(ResourceBundle.java:1282)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1224)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:952)
at java.util.logging.Logger.findResourceBundle(Logger.java:1257)
at java.util.logging.Logger.setupResourceInfo(Logger.java:1312)
at java.util.logging.Logger.getLogger(Logger.java:312)
at com.sun.enterprise.server.logging.BaseLogManager.doInitializeLogger(BaseLogManager.java:125)
at com.sun.enterprise.server.logging.BaseLogManager.addLogger(BaseLogManager.java:196)
at java.util.logging.LogManager.demandLogger(LogManager.java:393)
at java.util.logging.Logger.getLogger(Logger.java:274)
at com.sun.enterprise.management.deploy.DeployThread.trace(DeployThread.java:145)
at com.sun.enterprise.management.deploy.DeployThread.run(DeployThread.java:226)


====

After some searching I tracked the problem down to a syntax error in sun-web.xml. In my particular case I was using the following construct:

<property name="alternatedocroot_1" value="from=/resources/template/* dir=/Users/neilbeveridge/temp/extroot/admin"/>

I had mistakenly inserted an opening " following the dir sub-attribute. In this case the whole from=* dir=* construct must go inside the value attribute in XML.

Wednesday 16 June 2010

Spring - JUnit - Mocking JNDI

JNDI You are awful..

Oh ok, not that kind of mocking. But seriously if you are doing this in a spring bean:

@Resource
private String rootURL

Then you can use Spring to define a a bean to fill it in, then all is well. But what if you are doing:

@Resource(mappedName="rootURL")
private String rootURL

Well then you are most likely using something like a deployment descriptor (e.g. web.xml) to define the environment variable e.g.

    <env-entry>
        <description>Root URL for a blog</description>
        <env-entry-name>rootURL</env-entry-name>
        <env-entry-type>java.lang.String</env-entry-type>
        <env-entry-value>http://www.blogger.com</env-entry-value>
    </env-entry>


But what happens when you try to use JUnit, probably nothing bad, but what if you are using Spring to run your JUnit? Then you will most likely get this kind of error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'blogDAO':
Injection of resource fields failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'rootURL' defined in JNDI environment:
JNDI lookup failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial

This is down there not being the JNDI eniroment you were expecting, so how can you mock one up? Buy adding this to your JUnit test:

public static void buildJndi() {

        try {

            SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();

            String rootURL = "http://www.blogger.com";
            builder.bind("rootURL", rootURL);

        } catch (NamingException e) {

        }

    }

and calling it in the unit tests constructor.

For more information checkout:
http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/mock/jndi/SimpleNamingContextBuilder.html

Thursday 10 June 2010

JAX-WS 2.2 and Tomcat

I wanted to consume a web-service within a webapp on Tomcat, after being so used to using the Fish I deployed with thought to libraries and came up with this error:

NoSuchMethodError WebFault.messageName


After much hunting around I found that Netbeans had imported the Metro 2.0 library, so I changed this to JAX-WS 2.2 (jaxb-api.jar, jaxws-api.jar, jaxws-tools.jar) and everything is now fine..

Res:
http://weblogs.java.net/blog/ramapulavarthi/archive/2009/04/tip_for_using_j.html

Tuesday 8 June 2010

Accessing Spring Beans in Servlet

Sometimes you just have to do the do in a servlet. Here is a nice cheeky little way of getting to the applciation context:

WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext())

Then from there you can use getBean() etc...

Ref: http://forum.springsource.org/showthread.php?t=18833

Tuesday 6 April 2010

Quartz 1.6.1 and Spring FW 2.5.6 Jobs Stopping

So for a while I've been trying to track down why my jobs running on a org.springframework.scheduling.quartz.SchedulerFactoryBean seemingly stop quite arbitrarily and in groups of Triggers contained within each SchedulerFactoryBean. No exceptions are being thrown from application code and there is no advice setup on the application classes. Application code completes before the job not running correctly again.

I recently decided to try upgrading Quartz as the library I was using was rather old. Quartz 1.7.3 was installed and this problem has not been experienced since. Sorry for the lack of great insight into the cause here, but hopefully my experiences will help put the minds to rest of those being driven similarly insane by this problem.

Monday 8 March 2010

PersistenceUnit - PersistenceContext

But what does it all mean???

I don't know if it is because at this point in time I am suffering from a cold and a pair of ulcers are having a party in my mouth. But I am struggling to come to terms with the difference between and PU and PC...

After a quick Google on @PersistenceUnit vc @PersistenceContext I have deduced the following:
A PU will give you an EntityManagerFactory
A PC will give you an EntityManager

Now when to use either, really comes down to your TX strategy, who is managing your connections etcetc.
Using Spring I have always used PC to inject in a Spring managed EM to do the do with. However why is this?
  • @PersistenceUnit annotation is used in J5SE applications to handle Java Persistence API (JPA) persistence management. You may use a PeristenceUnit in an application inside a container, but it must be managed by the developer instead of the container.
  • @PersistenceContext annotation is used for Container Managed Persistence (CMP). This relieves the developer of having to worry about connection management.
and I think this link describes this nicely:

http://java.dzone.com/tips/how-use-glassfish-managed-jpa

Sunday 28 February 2010

Pretty URLs in Struts 2

I decided it would be nice to use pretty URLs for remote e-mail content fetched as part of an e-mail campaign generator.

This is simple with Struts 2:

STRUTS.XML
<action name="link/*/*" class="mm.linkController" method="execute">
<param name="id">{1}</param>
<param name="key">{2}</param>
<result name="success">/WEB-INF/jsp/link.jsp</result>
</action>

STRUTS.PROPERTIES
struts.enable.SlashesInActionNames = true

Add properties with javabean setters to your action class and away you go.

NB: ensure that the staticParams interceptor is switched on for your namespace.

Monday 8 February 2010

Soft keys in J2ME

When using a GameCanvas class override the keyPressed/Released/Repeated methods and capture key codes -7 (right soft key) and -6 (left soft key).

I have read that some hand manufacturers like to have different values, but these seem consistent with Nokia and Sony Ericsson atm...

Saturday 30 January 2010

OutOfMemoryError Exception caught in Display

Been developing with J2ME recently, fun as it is. Something changed in the code, ok so I changed something in the code and this error happened:

TRACE: , Exception caught in Display class
java.lang.OutOfMemoryError
   (stack trace incomplete)


...upon deploying to the emulator.

Turns out when I added the Motorola SDK to my configurations I had modified my canvas class overiding showNofity method:
/* How it was */    
protected void showNotify() {
 super.showNotify();
// My shizzles of code
}

However the Moto SDK declared this an error in someway and in my haste to go play hockey (game was cancelled btw :( ) I change the method to be this


protected void showNotify() {
 showNotify();
// My shizzles of code 
}

And this loop ( atleast I think it was a recursive loop) was causing the issue. I guess it was recursive calling... Bah!

Thursday 28 January 2010

Nokia S40 5th Edth Not Fullscreen

If you are using the gamecanvas avoid being clever and putting the call to setFullScreen(true) and Display.getDisplay(midlet).setCurrent(this); in the contructor.

It appears different implementations of J2ME initalise at different times. So do the above stuff after GameCanvas has been created.

AJAX XMLHTTP on the Opticon H15 Device

After some wrangling, Opticon came up with a patch. MSXML_AJAX.ARMV4I.CAB. Contact me for it.

Wednesday 27 January 2010

Hibernate Libraries

This one is a massive Gar...

It all started with the installation of the Fish v2.1.1 distribution. Because of updated libraries supplied by the fish installation, certain versions of hibernate won't work - mainly the one that is shipped with the Beans.

So this led me to download and manually add the libraries to the Fish (I decided that all my apps use Hibernate JPA so might as well have a mutual library), this is where the fun begins. To begin with there is no single download that will give you all the libs with dependencies required for Hibernate JPA. I will add that there are notes saying from 3.5.x this will all change.

Anyhoo, I figured out I needed the:

Annotations
Core
Entitymanager

downloads, take all the libs from here and place them in the lib folder of the fish. Then deploy an app, you will probably get an error like this:


.NoSuchMethodError: org.objectweb.asm.ClassWriter

That is because another library is required. At time of writing I don't know why this is, but anyhoo download the slf4j distribution and copy the following lib into the folder:

slf4j-jdk14-1.5.10.jar

...

Full list of libs:
antlr-2.7.6.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
javassist-3.9.0.GA.jar
jta-1.1.jar
slf4j-api-1.5.8.jar
cglib-2.2.jar
hibernate3.jar
hibernate-annotations.jar
hibernate-commons-annotations.jar
hibernate-core.jar
slf4j-api.jar
dom4j.jar
ejb3-persistence.jar
hibernate-entitymanager.jar
javassist.jar
jta.jar
slf4j-jdk14-1.5.10.jar

Also posted a question about this on the hibernate forums... Lets see how many responses I get:

https://forum.hibernate.org/viewtopic.php?f=1&t=1002285

SSL client authentication with local CA

This post describes how mutual authentication, specifically client authentication, can be implemented with Glassfish. A CA is created using OpenSSL and a root certificate for the CA is created and trusted by Glassfish. Client certificates are then created and signed by the CA such that multiple client certificates may be created and trusted transitively.

Steps:

1, Create the client certificate, register the CA cert as trusted.

As registering a new trusted client certifice into the truststore requires a Glassfish restart, we register a trusted Certificate Authority (CA) certificate instead, once and for all. Then each new client can get its certificate from the trusted CA, and become "transitively" trusted. To be exact, it is normaly the client who creates a public-private keypair, then submits the public part in the form of a Certificate Signing Request to the Certificate Authority, who then creates the certificate by signing it with its own private key. This certifies that tha CA trusts the certificate holder to be who he claims to be. Confusing at first, but rather straight forward once you get the hang of Public Key Infrastructure.

2, Establish a CA (assuming you don't have one already): source: http://www.madboa.com/geek/openssl/

openssl req \ -x509 -nodes -days 365 \ -newkey rsa:1024 -keyout cakey.pem -out cacert.pem

Edit openssl.cnf, create directories and files referenced there: mkdir demoCA echo '100001' > ./demoCA/serial mkdir ./demoCA/newcerts mkdir demoCA/private cp cacert.pem demoCA/ cp cakey.pem demoCA/private/

Enable signing foreign keys in openssl.cnf:

policy = policy_anything

3, Sign the certificate of the client key:

Create client key pair and certification request. This is normaly done by the client. The information provided here becomes part of the certificate, and will be included in the audit logs as "user principal":

openssl genrsa -out somekey.pem 2048 openssl req -new -key somekey.pem -out somekey.csr

sign (done by the CA): openssl ca -config openssl.cnf -in somekey.csr -out somekey.crt

4, package key and cert for browser consumption: openssl pkcs12 -export -out somekey.pfx -in somekey.crt -inkey somekey.pem -name "Some Cert"

5, Add own CA cert to truststore:

keytool -import -v -keystore /opt/glassfish/domains/domain1/config/cacerts.jks -storepass changeit -alias localCA -file cacert.pem

6, Restart Glassfish. Importing somekey.pfx into a browser should enable it to access your web service again at this point.

--

With thanks to:

Gabor Szokoli
Sirius Cybernetics Corporation Complaints division

Tuesday 19 January 2010

Sony Ericsson + XP x64

I just bought a Sony Ericsson Yari (U100i) phone. Unfortunately the drivers are no longer supplied on a CD (not at least with the one bought direct from SE). They make you install the PC suite then tell you, you can't use the device.

However I did find the drivers in the PC suite cab. If you look on the memory card that comes with the device look in the folder marked OTHER, unzip the pcsuite cab. Connect the phone and select the option to use with a different OS. XP x64 will then detect it and want the drivers, point it to the PCSuite\Drivers\SignedPhones directory and then click your way through.

Wednesday 13 January 2010

Java as a windows service

Good tutorial
http://blog.platinumsolutions.com/node/234
Apache stuff...
http://commons.apache.org/daemon/procrun.html
You can download the binaries without downloading Tomcat (or to get 64 bit versions) here:
http://svn.apache.org/repos/asf/tomcat/tc6.0.x/trunk/res/procrun/

Saturday 9 January 2010

Spring - PostConstruct

Found that using @PostConstruct doesn't have transactional ability. Looking around I found this link:

http://forum.springsource.org/showthread.php?t=81832

So by implementing the app listener you can have it bootstrap the configuration once the context has finished loading.

@Repository
public class MyDAOImpl implements ApplicationListener, MyDAO {

    @Transactional(propagation=Propagation.REQUIRED)
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ContextRefreshedEvent) {
            postCreate();
        }

    }

    public void postCreate() {
      //Code
      
        }
    }

Friday 8 January 2010

JPA + The Cat + Spring

App context:

<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL" />
<property name="showSql" value="false" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
</props>
</property>
</bean>

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>

Persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="myPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
      <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
      <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
    </properties>
  </persistence-unit>
</persistence>

JPA + The Fish + Spring

In the app context
<context:annotation-config />
<tx:jta-transaction-manager />
<tx:annotation-driven transaction-manager="transactionManager" />
<jee:jndi-lookup id="entityManagerFactory" jndi-name="persistence/myPU"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>

In the web.xml

<persistence-unit-ref>
<persistence-unit-ref-name>persistence/myPU</persistence-unit-ref-name>
<persistence-unit-name>myPU</persistence-unit-name>
</persistence-unit-ref>

In the persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="myPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/myDatasource</jta-data-source>
<properties>
<property name="hibernate.bytecode.provider" value="cglib"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>

Then to access in code:

@PersistenceContext
private EntityManager entityManager;

Thursday 7 January 2010

SNMP In Java

Tools to create an SNMP agent:

http://www.snmp4j.org/ - Java code
http://www.mibdesigner.com/ - Design the MiB
http://www.agentpp.com/ - Convert a MiB into Java code to utilize with the snmp4j agent.

Remote EJB access in Spring

<jee:jndi-lookup id="mySpringId" jndi-name="ejb/garBean">
<jee:environment>
//This tells spring to look here for the bean, if these aren't specified default to the localhost and 3700
org.omg.CORBA.ORBInitialHost=192.168.1.20
org.omg.CORBA.ORBInitialPort=3700

</jee:environment>
</jee:jndi-lookup>

 @Stateless(name="garBean", mappedName="ejb/garBean")
@Remote(GarBeanRemote.class)
public class GarBean implements GarBeanRemote

java.lang.NoSuchMethodError - Spring - SpringBeanAutowiringSupport

SEVERE: WSSERVLET11: failed to parse runtime descriptor: java.lang.NoSuchMethodError: org.springframework.web.context.ContextLoader.getC urrentWebApplicationContext()Lorg/springframework/web/context/WebApplicationContext;

Was thrown when using auto-wiring a service to a web-service class.

Fixed by moving to 2.5.6