Saturday, June 29, 2013

Why using Spring logout will redirect to session-timeout URL?

At first I have the most basic Spring security being configured in this way.
   <http auto-config="true">
        <intercept-url access="ROLE_ADMIN" pattern="/welcome*"/>
        <form-login authentication-failure-url="/loginfailed" default-target-url="/welcome" login-page="/login"/>
        <logout logout-success-url="/login"/>
   </http>
With this configuration, I can handle user login and logout request, where should the user land after successful login, and what will happen if the user failed to login. This is not enough, I want more. I would like to have a session control over the user. I want to stop the same user being login at the same time from different locations or different web browser. <session-management> could help me achieve this objective.
    <http auto-config="true">
        <intercept-url access="ROLE_ADMIN" pattern="/welcome*"/>
        <form-login authentication-failure-url="/loginfailed" default-target-url="/welcome" login-page="/login"/>
        <logout logout-success-url="/login"/>
        <session-management invalid-session-url="/sessionTimeout">
            <concurrency-control error-if-maximum-exceeded="true" max-sessions="1"/>
        </session-management>
    </http>
Anyhow, there is some problem with the code above, when I logout the application, it will redirect me to sessionTimeout page. Why this could happen? If I pay a close attention to the code, I could see that the problem is coming from <session-management invalid-session-url="/sessionTimeout">. Meanwhile, I've found something interesting in the code, by modifying the code as following will have my problem solved.
   <session-management>
      <concurrency-control error-if-maximum-exceeded="true" expired-url="/sessionTimeout" max-sessions="1"/>
   </session-management>
Now I know what is the real problem is happening. When a user logout, the session is first invalidate then only session management will get trigger. When session management come in, and found out the session has already gone, then sessionTimeout page will be redirect.

So if I want to stick to the invalid-session-url, I have to keep the session valid during logout. The code below showing details implementation.
   ...

   <logout invalidate-session="false" logout-success-url="/login"/>

   ...

Thursday, June 27, 2013

Using anonymous array to initialize an array in JAVA

There was a mistake when I'm declaring an array of integer first, and attempt to initialize it later will get a compiler error. The following code is what I'm trying to describe.

int[] theArray;
theArray = {1, 2};

It has to be either do it in this way:

int[] theArray = {1, 2};  // (1)

or this way:

int[] theArray;
theArray = new int[] (1, 2);  // (2)

In (1), theArray is an initializer block used to create and initialize the elements. In (2), an anonymous array expression is used.

Sunday, June 23, 2013

How could I implement session timeout in Spring?

What a mess?!! I spend the whole morning to figure out how could I implement a session control over a user today. Being able to authenticate a user in a system is a good start, what if I want to enforce some session rules, say logout a user when the user idle for 5 minutes. I though Spring have some kind of special session management? Nope, no such thing. Just define it in Deployment Descriptor as shown in the following code will do.

   5

Take note that the number in session-timeout tag represent in minute.

Saturday, June 22, 2013

javaws complaining java no such file or directory.

Just got my Ubuntu 12.01 installed. I have fed up with Fedora as it was just so sensitive because whenever there is a lib updated, it failed to boot up so easily. Switching back to Ubuntu, denotes this distro is more user friendly than others. At least it is less sensitive than Fedora. Anyhow there are some issue when I'm trying to launch a JNLP program using javaws in Ubuntu. I got the following error message when I issuing the javaws command:

/usr/lib/jvm/java-6-openjdk-amd64/jre/bin/java: No such file or directory

Well, according to the bug report, there is some problem with the /usr/bin/javaws file. Type this command head /usr/bin/javaws, following output should be seen:
#!/bin/bash

JAVA=/usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java
LAUNCHER_BOOTCLASSPATH="-Xbootclasspath/a:/usr/share/icedtea-web/netx.jar"
LAUNCHER_FLAGS=-Xms8m
CLASSNAME=net.sourceforge.jnlp.runtime.Boot
BINARY_LOCATION=/usr/bin/javaws
PROGRAM_NAME=javaws
CP=/usr/lib/jvm/java-7-openjdk-amd64/jre/lib/rt.jar

At line 3 and line 9, notice that the path was pointing to java-7-openjdk-amd64, when I dive into that path, I can see the java file was missing and the content of the directory wasn't as complete as in java-6-openjdk-amd64. So they suggest to change it to use java-6-openjdk-amd64 with following steps:

- Press Alt+F2
- enter the following (without paranthesis): "gksudo gedit /usr/bin/javaws"
- enter your password
- Change the "7" in the first line to a "6"
- Save and quit

It is not yet a perfect solution, this workaround will break whenever there is an update on the package. The correct workaround should be this way:

- sudo update-alternatives --config javaws

and then choose the number in front of /usr/lib/jvm/java-6-openjdk-amd64/jre/bin/javaws.

Thursday, June 20, 2013

How to access getClass() in static method?

In order to read a file which have been pack into JAR, usually this is what I did:
    class MyClass {
       private void readFromFile() {
          getClass().getClassLoader().getResourceAsStream("file_path");
       }
    }
Somehow this will only work only if it is an instance object. What if I’m reading the file from a static method? The code below shows the solution:
    class MyClass {
       private static void readFromFile() {
          MyClass.class.getClassLoader().getResourceAsStream("file_path");
       }
    }

How to copy a folder with Ant JAR task?

When packaging a Jar using ANT, usually I’ll just don’t care the file structure and dump whatever thing into root directory of a package. The code below showing you a clear picture on how the real thing works:
<jar basedir="build/classes" destfile="${lib.dir}/MyPackage.jar">
    <fileset dir="${lib.dir}">
          <include name="*.jar">
    </fileset>
    
    ... 
But somehow there is a situation where the requirement from my superior was so stubborn that I have to follow the existing file structure as in the development. Meaning that all libraries must locate inside lib folder. Fortunately nothing much change in the build.xml, see the code:
    <jar basedir="build/classes" destfile="${lib.dir}/MyPackage.jar">
       <fileset dir=".">
          <include name="${lib.dir}/*.jar">
       </fileset>
    

Monday, June 10, 2013

Make a query in JPA

Recently I was doing some discovery on JPA. It was a real fun. I was totally switching my mindset to work with different terminology of my current work which involve a lot of XML code. With JPA, XML is useless. Let's say I have a table called Book, and a POJO object mapped on this table through annotation in the following way:
   public class Book {

         @Id
         private Integer isbn;

         @Column
         private String name;

         // getter and setter
   }
When I'm making a query on this table, there 2 ways on doing this:
1st way is to do it in SQL style (take note on line 4):
   EntityManagerFactory emf = Persistence.createEntityManagerFactory("book");
   EntityManager em = emf.createEntityManager();
   em.getTransaction().begin();
   Query q = em.createQuery("select b from Book b");
   List list = q.getResultList();
   em.getTransaction().commit();
   em.close();
2nd way is to do it through object-oriented way (take note on line 5):
   EntityManagerFactory emf = Persistence.createEntityManagerFactory("book");
   EntityManager em = emf.createEntityManager();
   EntityTransaction tx = em.getTransaction();
   tx.begin();
   Book book = em.find(Book.class, 1);
   tx.commit();
   em.close();

Cool huh!?! Happy Programming @!

Sunday, June 9, 2013

Cyclic reference error in ManagedBean

I hope this wasn't an accident. I have a managed bean A and a managed bean B referencing each other just like code shown below:
   @ManagedBean(name="BeanA")
   @SessionScoped
   public class ManagedBeanA {
      
      @ManagedProperty(value="#{BeanB}")
      private ManagedBeanB beanB;
   }

   @ManagedBean(name="BeanB")
   @SessionScoped
   public class ManagedBeanB {
      
      @ManagedProperty(value="#{BeanA}")
      private ManagedBeanA beanA;
   }
Notice that the code shown above have cause cyclic reference in between BeanA and BeanB. This problem will not show until BeanA is get invoke by the server and following stacktrace will be thrown.
Caused by: javax.faces.el.EvaluationException: javax.el.ELException: javax.el.ELException: Detected cyclic reference to managedBean BeanA
     at org.apache.myfaces.el.convert.ValueExpressionToValueBinding.getValue(ValueExpressionToValueBinding.java:169)
     at org.apache.myfaces.config.impl.digester.elements.ManagedProperty.getRuntimeValue(ManagedProperty.java:120)
     at org.apache.myfaces.config.ManagedBeanBuilder.initializeProperties(ManagedBeanBuilder.java:328)
     at org.apache.myfaces.config.ManagedBeanBuilder.buildManagedBean(ManagedBeanBuilder.java:169)
     at org.apache.myfaces.el.unified.resolver.ManagedBeanResolver.createManagedBean(ManagedBeanResolver.java:303)
     at org.apache.myfaces.el.unified.resolver.ManagedBeanResolver.getValue(ManagedBeanResolver.java:266)
     at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:55)
     at org.apache.myfaces.el.unified.resolver.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:142)
     at org.apache.myfaces.el.VariableResolverImpl.resolveVariable(VariableResolverImpl.java:65)
     at org.apache.myfaces.el.convert.VariableResolverToELResolver.getValue(VariableResolverToELResolver.java:116)
     at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:55)
     at org.apache.myfaces.el.unified.resolver.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:142)
     at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:71)
     at org.apache.el.parser.AstValue.getValue(AstValue.java:149)
     at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:283)
     at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:106)
     ... 40 more

No Hibernate session bound to thread

TransactionInterceptor is very useful when you want to ensure the data integrity and transaction consistency as it ensure the data from multiple tables are successfully updated to the database or rollback from the database when a fault has occured. What if I miss configure this in Spring? Take a look at the following code:
    <bean class="org.springframework.transaction.interceptor.TransactionInterceptor" id="matchTransaction">
        <property name="transactionManager">
            < ref bean="transactionManager"/>
        </property>
        <property name="transactionAttributes">
            <props>
                <prop key="add*">PROPAGATION_REQUIRED< /prop>
            </props>
        </property>
    </bean>

    <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
        <property name="beanNames">
            <list>
                <idref bean="theBo"/>
                <idref bean="theDao"/>
            </list>
        </property>
        <property name="interceptorNames">
            <list>
                <idref local="matchTransaction"/>
            </list>
        </property>
    </bean>
Following is the member function in my theDao class doing the update into the database:
    public void setSomethingToDb(String theNewValue) throws HibernateException {
  
    Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(ThePojoBean.class);

        ...

    update(thePojoBean); // assume this statement is executing Hibernate's saveAndUpdate() API to database
    }
Take a closer look at matchTransaction bean, I have register the function start with add*. This indicates whatever function that starts with the prefix, add will be intercepted by TransactionInterceptor to ensure database transactions are successful. But if I declare a function name with the prefix set as shown above, this is a disaster during the getCurrentSession() call and it will cause the following error being thrown.
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
 at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
 at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:687)
 at org.hauhsin.authentication.dao.impl.AuthenticationDaoImpl.fetchUsersDetailsByStatus(AuthenticationDaoImpl.java:23)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:597)
 at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
 at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
 at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
 at $Proxy0.fetchUsersDetailsByStatus(Unknown Source)
 at org.huahsin.authentication.bo.impl.AuthenticationBoImpl.fetchUsersDetailsByStatus(AuthenticationBoImpl.java:97)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:597)
 at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
 at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
 at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
 at $Proxy1.fetchUsersDetailsByStatus(Unknown Source)
 at org.huahsin.authentication.UsrStatusUpdService.updateUserStatus(UsrStatusUpdService.java:36)
 at org.huahsin.authentication.UsrStatusUpdService.main(UsrStatusUpdService.java:65)

Sunday, June 2, 2013

JAAS is not for human being

I have spend quite a number of months on this JAAS topic already, but at last I am still failed to configure it on the web project. I have been trying so hard to get it work, and have read tons of resources on the configuration, and now I damn tired with this JAAS (on the web). During this experiment, I found out that JAAS is just a low level security framework to secure the resources beyond the web application level. It just too low until the level that I am require to configure it in the server. Frankly speaking, such a low level configuration isn't my favorite due to its maintenance effort.

Take for example, I'm required to put the following code in catalina.policy under <tomcat_dir>/conf:

export JAVA_OPTS=-Djava.security.auth.login.config==$CATALINA_HOME/conf/login.config

I found this is so not programmer friendly when come to development. Anyhow there is a workaround, put the following code inside the Eclipse's server launch configuration under the VM arguments:

-Djava.security.auth.login.config= "&It;tomcat_dir>\conf\login.config"

Launch the server will see my expected login page, type in the correct username and password, the browser will redirect me to HTTP Status 403 - Access to the requested resource has been denied.

What else do I miss configure? I think I will just forget about JAAS thing since Spring Security can achieve my objective easily.

I was stun when Hibernate validation throwing indexOutOfBoundsException.

    <bean class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" id="sessionFactory">       
       <property name="dataSource">
           ...
       </property>

       <property name="hibernateProperties">
           ...
       </property>

       <property name="mappingResources">
           ...
       </property>
    </bean>

    <bean class="org.huahsin.dao.impl.TheDaoImpl" id="theDao">
       <property name="sessionFactory" ref="sessionFactory">
    </bean>
Take a look at the above code, when I load it up in the Liberty Profile server, an error complaining that sessionFactory was failed to initialize. Before this was working fine, not sure why this error suddenly shows up? Below are the stack trace for this error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [spring/hibernate-spring.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Unable to get the default Bean Validation factory
     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1422)
     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:518)
     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
     at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
     at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
     at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
     at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
     at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:567)
     at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
     at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
     at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
     at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
     at org.huahsin.test.CertificateSearchActionTest.<init>(CertificateSearchActionTest.java:24)
     at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
     at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
     at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
     at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
     at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.createTestInstance(PowerMockJUnit44RunnerDelegateImpl.java:188)
     at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.createTest(PowerMockJUnit44RunnerDelegateImpl.java:173)
     at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:195)
     at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:148)
     at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
     at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
     at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
     at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
     at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:101)
     at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
     at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
     at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
     at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
    Caused by: org.hibernate.HibernateException: Unable to get the default Bean Validation factory
     at org.hibernate.cfg.beanvalidation.BeanValidationActivator.applyDDL(BeanValidationActivator.java:127)
     at org.hibernate.cfg.Configuration.applyBeanValidationConstraintsOnDDL(Configuration.java:1704)
     at org.hibernate.cfg.Configuration.applyConstraintsToDDL(Configuration.java:1654)
     at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1445)
     at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1375)
     at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:717)
     at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1479)
     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1419)
     ... 33 more
    Caused by: java.lang.reflect.InvocationTargetException
     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
     at java.lang.reflect.Method.invoke(Method.java:597)
     at org.hibernate.cfg.beanvalidation.BeanValidationActivator.applyDDL(BeanValidationActivator.java:118)
     ... 41 more
    Caused by: org.hibernate.HibernateException: Unable to build the default ValidatorFactory
     at org.hibernate.cfg.beanvalidation.TypeSafeActivator.getValidatorFactory(TypeSafeActivator.java:383)
     at org.hibernate.cfg.beanvalidation.TypeSafeActivator.applyDDL(TypeSafeActivator.java:109)
     ... 46 more
    Caused by: javax.validation.ValidationException: Could not create Configuration.
     at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:175)
     at javax.validation.Validation.buildDefaultValidatorFactory(Validation.java:50)
     at org.hibernate.cfg.beanvalidation.TypeSafeActivator.getValidatorFactory(TypeSafeActivator.java:380)
     ... 47 more
    Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
     at java.util.ArrayList.RangeCheck(ArrayList.java:547)
     at java.util.ArrayList.get(ArrayList.java:322)
     at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:173)
     ... 49 more
Searching on the stackoverflow.com I got this post by someone which also having the same problem similar to mine, but not exactly. He wrote:
3.6.0.Final seems to automatically turn on bean validation when an object is saved/updated through Hibernate. This is very bad because some of my tests don't bother setting all the properties - they just aren't needed.
This giving me a hints that it only happened in Hibernate 3.6.0 which is the same version as mine. In the mean time I got another post mention this:
By default Hibernate validator is set to auto, meaning if there is a validator in the classpath it will try to use it. GWT 2.3 and newer versions include the validation api inside the gwt-servlet.jar, so Hibernate ends up with a parcial validator and fails. If you don't want to use Hibernate Validation just turn it off in your properties (hibernate.cfg.xml, hibernate.properties or programatically).
Well, without thinking further, lets give it a try to turn off the Hibernate Validator, it might solve the problem. Putting this code into the hibernate configuration property:
    <property name="hibernateProperties">
       <props>
           ...
           <prop key="javax.persistence.validation.mode">none</prop>
       </props>
    </property>

Saturday, June 1, 2013

What will happen when JPA jar is missing in the classpath?

JPA jar is needed when using Hibernate version 3.6.0. Missing JPA jar in the classpath will have following error. No worry, the JPA jar is bundle together with the same distribution as the Hibernate package, include it into your classpath now!!
Exception in thread "main" java.lang.NoClassDefFoundError: javax/persistence/EntityListeners
 at org.hibernate.cfg.annotations.reflection.JPAMetadataProvider.getDefaults(JPAMetadataProvider.java:96)
 at org.hibernate.annotations.common.reflection.java.JavaReflectionManager.getDefaults(JavaReflectionManager.java:226)
 at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1385)
 at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1856)
 at org.huahsin.MainApp.main(MainApp.java:12)
Caused by: java.lang.ClassNotFoundException: javax.persistence.EntityListeners
 at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
 ... 5 more

Apache Derby UI plugin error in Eclipse Juno

Oh no! This is so not good. There are some problem with the Apache Derby plugin in Eclipse. When I trying to add Apache Derby nature into the project, I got the following error:
Apache Derby Ui Plug-in
Error adding Derby jars to the project:
org.eclipse.ui.internal.WorkbenchWindow cannot be cast to
org.eclipse.jface.window.ApplicationWindow
There is a workaround on this issue from stackoverflow.com but it seem quite a lot of work to me as it require me to recompile from the source code again. No way, if I do this, this will divert my time to Derby development.

Derby plugin for Eclipse was missing in version 10.10

I have downloaded Derby version 10.10.1.1. Unfortunately the Derby for Eclipse plugins was not bundle together. It took me quite some time searching where is the plugin. Until I land on the download page with release version 10.8.2.2, then only I found the plugin there. And it was a separate download, not bundle together in the same package.