17 Aralık 2009 Perşembe

a bpel data manipulation tutor + I18N: BPCOR-3023: Selection Failure

i liked the tutor, so lets share the link:
http://www.oracle.com/technology/products/ias/bpel/pdf/orabpel-Tutorial3-DataManipulationTutorial.pdf

some other links:
http://jsexton0.blogspot.com/2009/01/openesb-bpel-assignment-tips.html
http://n2.nabble.com/ignoreMissingFromData-usage-td2474810.html

btw, all this research was due to the following error with open esb + glassfish combination:

Caused by: com.sun.jbi.engine.bpel.core.bpel.exception.StandardException: I18N: BPCOR-3023: Selection Failure occurred in BPEL({http://enterprise.netbeans.org/bpel/Balistika2010Bpel/IncidentRegistration}IncidentRegistration) at line 71!
BPCOR-6129:Line Number is 69
BPCOR-6130:Activity Name is AssignExtractDaimData
at com.sun.jbi.engine.bpel.core.bpel.engine.impl.BPELInterpreter.createVirtualFaultUnit(BPELInterpreter.java:235)
at com.sun.jbi.engine.bpel.core.bpel.engine.impl.BPELInterpreter.execute(BPELInterpreter.java:203)

issue about
ignoreMissingData attribute on assign element
https://open-jbi-components.dev.java.net/issues/show_bug.cgi?id=181

2 Aralık 2009 Çarşamba

sound problem in opensuse 11.2 for intel ich9

in my case, the problem is there is no sound..

and fortunately, the solution was simple.. i just run the following command as root:
cp /etc/modprobe.d/50-sound.conf /etc/modprobe.d/sound.conf

btw, prior to executing the command, there was no /etc/modprobe.d/sound.conf file..

also, i still can not get sound from the earphones at the front side of the tower, i use the one at the back..

some links:
http://medwinz.blogsome.com/2009/11/30/workaround-for-soundproblem-in-opensuse-112-for-intel-ich9/
http://en.opensuse.org/SDB:AudioTroubleshooting

smartctl

yesterday, unfortunately my computer crashed due to a raid failure (http://www.datarecovery.org/raid-failure.html) i still do not know why.. we assumed that one of the hard disks is problematic and took it off .
in order to figure out if there is a problem on hard disks, we have to test bothof them, before installing open suse on the machine again.. we used smartctl to do that.
an article on smart : http://www.linuxjournal.com/article/6983
some commands:

smartctl -t long /dev/sda : starts long test on specified disk
smartctl -t short /dev/sda : starts short test on specified disk
smartctl -l selftest /dev/sda : reports about all tests carried out on specified disk

btw, in my computer, starting a new test caused the previously started test on the same disk to abort..

19 Kasım 2009 Perşembe

increasing heap size of glassfish

In order to increase heap size for glassfish, follow th steps:
1) Open glassfish admin console from adress similar to http://localhost:4848/ 
(the default username: admin and password: adminadmin)
2) Select application server -> jvm settings -> jvm options
3) Update the parameters similar to the below ones according to your needs:

12 Kasım 2009 Perşembe

javax.xml.ws.WebServiceException: Unexpected response element ,,, error

Sometimes, you get javax.xml.ws.WebServiceException: Unexpected response element ,,, error while running a bpel process from a client. 
The error is well defined here: http://forums.netbeans.org/topic11185.html
One way to get rid of this error is adding namespace attribute to the operation definition in the wsdl of the bpel process as follows:
 <binding name="calculatorMtomWSDLPortTypeBinding" type="tns:calculatorMtomWSDLPortType">
        <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
        <operation name="calculatorMtomWSDLOperation">
            <soap:operation/>
            <input name="input1">
                <soap:body use="literal" namespace="http://j2ee.netbeans.org/wsdl/CalculatorMtom/calculatorMtomWSDL"/>
            </input>
            <output name="output1">
                <soap:body use="literal" namespace="http://j2ee.netbeans.org/wsdl/CalculatorMtom/calculatorMtomWSDL"/>
            </output>
        </operation>
    </binding>

in short, lack of the red stuff above, leads the mentioned problem..



monitoring soap messages in glassfish

in order to see oncoming and outgoing soap messages on glassfish, 

set the following jvm parameter in glassfish admin console:

-Dcom.sun.xml.ws.transport.http.client.HttpTransportPipe.dump=true

6 Kasım 2009 Cuma

testsuite for junit

i used org.junit package for developing unit tests and want to run all my tests in a suite..
in order to do that :

two sample test classes
import org.junit.Test;

public class Test1 {
    @Test
    public void TestCase1() {
   ...
   }
-------------------------------
import org.junit.Test;

public class Test2 {
    @Test
    public void TestCase2() {
   ...
   }

test suite
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({
    Test1.class,
    Test2.class
    })
public class AllTests {

}

(post by Arne V. at 10-06-2008, 03:18 AM)


5 Kasım 2009 Perşembe

named query

named query is a great tool provided by jpa while developing your dao classes.. (i mean it is used while developing dao classes, not tool for doing the job itself..)



4 Kasım 2009 Çarşamba

limitation: circular relationships in web services


object model can represent a graph at the server side and it must be serialized into an xml which can only represent a tree (not a graph especially with cycles) while using xml web services.. 



CycleRecoverable is an interface which detects cycles on the implementing object and executes the method onCycleDetected when the object is about to serialize into XML. Thus it gives you a chance to break the cycles in the object graph and make it a tree, thus representable by xml. 

import com.sun.xml.bind.CycleRecoverable;
import com.sun.xml.bind.CycleRecoverable.Context;

public class Clazz implements  CycleRecoverable {
// ...
@Override
    public Object onCycleDetected(Context arg0) {
        // do whatever you do
        return object;
    }

27 Ekim 2009 Salı

revisited : Troobleshooting: Date becomes XMLGregorianCalendar when stubs are generated at client side, how to prevent this?

lets revisit issue on http://hilaltarakci.blogspot.com/2009/06/troobleshooting-date-becomes.html
the problem is, although adapter interface is generated, the generated implementation for the interface is empty.. so, sould replace with own implementation..

btw, soln is discovered by someone in the team, not me.. lets share it :  https://jaxb.dev.java.net/guide/Using_different_datatypes.html


18 Ekim 2009 Pazar

Could not execute JDBC batch update

the error Could not execute JDBC batch update comes out when the entities are as follows and you are trying to save the parent entity:

parent entity
  @OneToMany(cascade = CascadeType.ALL)
   @JoinTable(name = "TBL_INCIDENT_ABSEVIDGRP", joinColumns = {
        @JoinColumn(name = "FLD_INCIDENT_ID")
    },
    inverseJoinColumns = {
        @JoinColumn(name = "FLD_ABSEVIDGRP_ID")
    })
private List childList = new ArrayList();

child entity
    @ManyToOne
    @JoinTable(name = "TBL_INCIDENT_ABSEVIDGRP", joinColumns = {
        @JoinColumn(name = "FLD_ABSEVIDGRP_ID")
    },
    inverseJoinColumns = {
        @JoinColumn(name = "FLD_INCIDENT_ID")
    })
private Parent parent;

the error is solved by commenting out the green and bold code portion..
the lack of red code portion leads to the following error while saving the parent entity:
Error while commiting the transaction
javax.persistence.RollbackException: Error while commiting the transaction
        at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:71)
...
Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: Child Entity
 

unit testing dao with actual postgre db settings

the environment is netbeans 6.5 ide, postgre db, junit for unit testing..
when i try to execute unit tests over postgre, i get the following error:
3196 [main] FATAL org.hibernate.connection.DatasourceConnectionProvider  - Could not find datasource: blshilaltarakci
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
        at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)
        at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
....

i think the reason for this is the lack of jndi properties file. when the project is deployed to any server, the server mostly already has a jndi properties file and this is not a problem..  ( i think..) in my case, there is no jndi properties file in classpath, since the (dao) project is not deployed to server in the time of testing.. 
so, i moved back to unit testing using an in memory database..

Edit on 05/11/2009 at 10:27 : Sometimes, the reason the error does not disappear is badly formed named queries.. 

15 Ekim 2009 Perşembe

soapui experience

well, i want to note down what i faced unexpected during my soapui usage..

first of all, soapui project is one big xml file which is a disadvantage.. i really have no idea how they handled svn usage, maybe it is similar to enterprise architect's solution. whatever, my concern is not svn at this moment..

secondly, i could not open the project after i closed netbeans, i don t know why.. soapui-project.xml file is just got emty with no reason.. so, i have to start from beginning, this is annoying actually :( the point is: pay special attention to taking backups..
and this warning comes up everytime i close netbeans.. 
Project file [...Test] has been modified externally, overwrite?

TODO: very soon..



13 Ekim 2009 Salı

soapui

well, lets start with testing web services using soapui
in a previous post at http://hilaltarakci.blogspot.com/2009/10/web-service-testing-in-netbeans.html a quick start has been made.. now, it is time to continue..
the following are good tutors to start up:

soapui vs jmeter for web service testing

this article is a good comparison of jmeter and soapui (and lucily a recent one) : http://www.developer.com/open/article.php/3839476/article.htm

according to this, soapui wins for two main reasons:
  •  from the article: A big difference from the SoapUI here is that you should have SOAP requests already to be supplied to JMeter, where as in SoapUI you can generate them.
this is a big deal in fact..
  • again from  the article: The learning curve of SoapUI is shorter then the JMeter, mostly because SoapUI automates a lot of tasks related to the creation of the Web services test plans.
 we are in a hurry, so shorter learning curve is attractive..

web service testing in netbeans

i have been looking for some tool to test (jax ws) web services developped with netbeans 6.5.  soapui at http://www.soapui.org/ is such a tool.. It is both available as standalone or as netbeans plugin.. well, i prefer the plugin (http://www.soapui.org/netbeans/index.html).. 
lets begin..

the very first step is installing the plugin.. just download the nbm from http://sourceforge.net/projects/soapui/files/soapui-netbeans-plugin/3.0 and follow the instructions at http://www.soapui.org/netbeans/installation.html


so, end of the quick start.. 

Edit on 13/10/2009 at 11.12 : 
btw, the command line tools of soapui does not come with the plugin.. so, if you want to use them, for instance launch testrunner inside netbeans or whatever, download soapui standalone version from http://sourceforge.net/projects/soapui/files/soapui/3.0.1 , run the executable for installation, and show the path soapUI-3.0.1/bin for testrunner exe or something..

Edit on 13/10/2009 at 12.03 :
moreover, it is possible to test bpel processes with soapui..
here are the examples:

6 Ekim 2009 Salı

notes on schuchert jpa tutor 4

finally the last tutor at http://schuchert.wikispaces.com/JPA+Tutorial+4+-+Inheritance+and+Polymorphic+Queries

lets move!
now, all tests should pass..
well, time to go to my own project, thanks to schuchert, tutors are really helpful :)

notes on schuchert jpa tutor 3

now the tutor i follow is http://schuchert.wikispaces.com/JPA+Tutorial+3+-+A+Mini+Application

lets see what happens..

so perfect, just in test methods of LibraryTest, the assertEquals methods used to compare floats that take 2 params are deprecated. Instead define a delta as follows and pass it as 3rd param to mentioned methods. Thus, tests will pass i think :)
private static final float DELTA = (float) 0.0;
...
assertEquals(.., .., DELTA);




5 Ekim 2009 Pazartesi

notes on schuchert jpa tutor 2

the tutor is at http://schuchert.wikispaces.com/JPA+Tutorial+2+-+Working+with+Queries+1

lets follow..
  • comment out the exception in the  unsuccessfulSingleResultTooManyEntries  test case of QueriesTest.. thus, it will pass..
 @Test// (expected = NonUniqueResultException.class)
    public void unsuccessfulSingleResultTooManyEntries() {
insertPerson();
        insertPerson();

        // This will fail because we expect a single result
        // but in fact there are 2 results returned.
        em.createQuery("from Person").getSingleResult();
    }

this is because,  getSingleResult() does not get angry when there are more than one records and just picks the first one..



4 Ekim 2009 Pazar

notes on schuchert jpa tutor 1

i am following schuchert's jpa tutor 1 at http://schuchert.wikispaces.com/JPA+Tutorial+1+-+Getting+Started
however, my environment is netbeans 6.5 + glassfish v2 + postgre..
lets note down some drawbacks i faced:
  • i get the following error while trying to run PersonTest :
Testcase: emptyTest(entity.PersonTest):        Caused an ERROR
[PersistenceUnit: SchuchertJpaTutor1PU] Unable to build EntityManagerFactory
javax.persistence.PersistenceException: [PersistenceUnit: SchuchertJpaTutor1PU] Unable to build EntityManagerFactory
        at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:677)
        at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:126)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:51)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:33)
        at entity.PersonTest.initEmfAndEm(PersonTest.java:24)
Caused by: org.hibernate.HibernateException: Could not find datasource
        at org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:56)
        at org.hibernate.connection.ConnectionProviderFactory.newConnectionProvider(ConnectionProviderFactory.java:124)
        at org.hibernate.ejb.InjectionSettingsFactory.createConnectionProvider(InjectionSettingsFactory.java:29)
        at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:62)
        at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2009)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1292)
        at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
        at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669)
Caused by: 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
        at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)
        at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
        at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:325)
        at javax.naming.InitialContext.lookup(InitialContext.java:392)
        at org.hibernate.connection.DatasourceConnectionProvider.configure(DatasourceConnectionProvider.java:52)

Testcase: emptyTest(entity.PersonTest):        Caused an ERROR
null
java.lang.NullPointerException at entity.PersonTest.cleanup(PersonTest.java:31)
Test entity.PersonTest FAILED

to fix:
- use in memory database in unit tests with persistence.xml as follows:
<?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="SchuchertJpaTutor1TestPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <non-jta-data-source></non-jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
        <property name="hibernate.connection.url" value="jdbc:hsqldb:mem:unit-testing-jpa"/>
        <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
        <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
        <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
        <property name="hibernate.connection.username" value="sa"/>
        <property name="hibernate.connection.password" value=""/>
    </properties>
  </persistence-unit>
</persistence>
- add hsqldb.jar and (possibly) servlet.jar to test libs 

and run the test again, it should pass now..

  • when Address is added to Person, delete the final keyword from getter and setter methods for address.(it results in compile error..)

i will continue with the next tutorial, so see you at the next blog entry :)

29 Eylül 2009 Salı

jpa annotation reference documentation

for jpa annotations 

A cycle is detected in the object graph. This will cause infinitely deep XML

while trying to call a web service with the explained structure, such an error pops up at the client side:
com.sun.istack.internal.SAXException2: A cycle is detected in the object graph. This will cause infinitely deep XML: 

Parent.java
package deepxml;

import java.util.ArrayList;
import java.util.List;

public class Parent {

    private String name;
    private List childList = new ArrayList();

    public List getChildList() {
        return childList;
    }

    public void setChildList(List childList) {
        this.childList = childList;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Child.java
package deepxml;

public class Child {

    private String name;
    private Parent myParent;

    public Parent getMyParent() {
        return myParent;
    }

    public void setMyParent(Parent myParent) {
        this.myParent = myParent;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

DeepXml.java
package deepxml.service;

import deepxml.Child;
import deepxml.Parent;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

@WebService()
public class DeepXml {

    @WebMethod(operationName = "deepXml")
    public Parent deepXml(@WebParam(name = "parent")
    Parent parent, @WebParam(name = "childList")
    List childList) {
        parent.setChildList(childList);
        
        for(Child child: childList) {
            child.setMyParent(parent);
        }

        return parent;
    }
}

Main.java for client side
package deepxmlclient;

import deepxml.service.Child;
import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {
        try { // Call Web Service Operation
            deepxml.service.DeepXmlService service = new deepxml.service.DeepXmlService();
            deepxml.service.DeepXml port = service.getDeepXmlPort();
            deepxml.service.Parent parent = new deepxml.service.Parent();
            parent.setName("Parent");

            java.util.List childList = new ArrayList();
            Child child1 = new Child();
            child1.setMyParent(parent);
            child1.setName("Child1");

            Child child2 = new Child();
            child2.setMyParent(parent);
            child2.setName("Child2");

            parent.getChildList().add(child1);
            parent.getChildList().add(child2);

            deepxml.service.Parent result = port.deepXml(parent, childList);
            System.out.println("Result = "+result);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

The bold lines in the client code results in the specified error, if you try with those lines commented out, there will be no problem at all.. Lucyly, this works in our situation :)

However, this may not be the correct solution in all cases, so lets try to find a real solution..
Here is the offered solution to the condition: https://jaxb.dev.java.net/guide/Mapping_cyclic_references_to_XML.html



18 Eylül 2009 Cuma

java deep clone library

http://robust-it.co.uk/clone/index.php

TODO: details will be given soon.. DONE!

Edit on 28/09/2009, 11:02:

maybe beanlib is a better, more talented alternative: http://beanlib.sourceforge.net/

here is call sample for both:

for cloner..
    Cloner cloner = new Cloner();
     cloner.nullInsteadOfClone(SessionImplementor.class,
                    JDBCTransaction.class,
                    SessionImpl.class,
                    org.hibernate.collection.PersistentBag.class); 

     List cloneResult = cloner.deepClone(result);

for beanlib..
    HibernateBeanReplicator r = new Hibernate3BeanReplicator();
     List cloneResult = r.deepCopy(result);

and 

10 Eylül 2009 Perşembe

read/write file with web service

after a totally sleepless night, this morning i was googling to find a binding for java.io.File in web services with an unclear mind and very upset since i was not even close to my intention :((

you know, type of the file parameter in the following service becomes string in the client side..

@WebMethod(operationName = "retrieveFile")
@Oneway
public void retrieveFile(@WebParam(name = "file")
File file) {
}

the wsdl

<xs:complexType name="retrieveFile"
>
<xs:sequence>
<xs:element name="file" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>

so, what to do ?
lucily, a friend in the team has searched for it before and came back with a solution:

http://m-button.blogspot.com/2008/07/building-jax-rpc-or-jax-ws-webservices.html

it is checked, guaranteed to work..

9 Eylül 2009 Çarşamba

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role- no session or session was closed

the exception is:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.example.ws.Library.bookList, no session or session was closed


so, one possible solution is to clone the entity if it will be used out of session..

a simple example web service project:

Book.java

package com.example.ws;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String title;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Book)) {
return false;
}
Book other = (Book) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}

@Override
public String toString() {
return "com.example.ws.Book[id=" + id + "]";
}

}

Library.java

package com.example.ws;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Library implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String name;

@OneToMany(fetch = FetchType.LAZY, cascade= CascadeType.ALL)
private List bookList = new ArrayList();

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public List getBookList() {
return bookList;
}

public void setBookList(List bookList) {
this.bookList = bookList;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Library)) {
return false;
}
Library other = (Library) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}

@Override
public String toString() {
return "com.example.ws.Library[id=" + id + "]";
}

}

HibernateUtil.java

package util;

import com.example.ws.Book;
import com.example.ws.Library;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;

/**
*
* @author hilal.tarakci
*/
public class HibernateUtil {

@PersistenceUnit(unitName = "HibernateLazyInitFixPU")
private EntityManagerFactory emf = null;

public EntityManager getEntityManager() {
if (emf == null) {
emf = Persistence.createEntityManagerFactory("HibernateLazyInitFixPU");
}
return emf.createEntityManager();
}

public void create(Library item) throws Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(item);
em.getTransaction().commit();
} catch (Exception ex) {
try {
if (em != null) {
em.getTransaction().rollback();
}
} catch (Exception re) {
re.printStackTrace();
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}

public List retrieveRecordsOfBook() {

EntityManager em = getEntityManager();
try {
Query q = em.createQuery("select object(o) from Book as o");

List bookList = new ArrayList();
List tempBookList = q.getResultList();

for (Book tempBook : tempBookList) {
Book book = new Book();
book.setId(tempBook.getId());
book.setTitle(tempBook.getTitle());

bookList.add(book);
}

return bookList;
} finally {
em.close();
}

}

public List retrieveRecordsOfLibrary() {

EntityManager em = getEntityManager();
try {
Query q = em.createQuery("select object(o) from Library as o");

List libList = new ArrayList();

List tempLibList = q.getResultList();

for (Library tempLib : tempLibList) {
Library lib = new Library();
lib.setId(tempLib.getId());
lib.setName(tempLib.getName());

List bookList = new ArrayList();

for(Book tempBook: tempLib.getBookList()) {
Book book = new Book();
book.setId(tempBook.getId());
book.setTitle(tempBook.getTitle());

bookList.add(book);
}

lib.setBookList(bookList);

libList.add(lib);
}

return libList;

} finally {
em.close();
}

}
}

HibernateLazyInit.java
package com.example.ws.service;

import com.example.ws.Book;
import com.example.ws.Library;
import java.util.List;
import javax.jws.Oneway;
import javax.jws.WebMethod;
import javax.jws.WebService;
import util.HibernateUtil;

@WebService()
public class HibernateLazyInit {

private HibernateUtil util = new HibernateUtil();

@WebMethod(operationName = "insertRecords")
@Oneway
public void insertRecords() {
try {
Book book1 = new Book();
book1.setTitle("A Good Story");

Book book2 = new Book();
book2.setTitle("A Bad Story");

Library library1 = new Library();
library1.setName("An Excellent Library");

library1.getBookList().add(book1);
library1.getBookList().add(book2);

util.create(library1);

} catch (Exception ex) {
ex.printStackTrace();
}
}

@WebMethod(operationName = "retrieveRecordsOfBook")
public List retrieveRecordsOfBook() {
return util.retrieveRecordsOfBook();
}

@WebMethod(operationName = "retrieveRecordsOfLibrary")
public List retrieveRecordsOfLibrary() {
return util.retrieveRecordsOfLibrary();


}
}

.. and the client call
public class Main {

void insertRecords() {

try { // Call Web Service Operation
com.example.ws.service.HibernateLazyInitService service = new com.example.ws.service.HibernateLazyInitService();
com.example.ws.service.HibernateLazyInit port = service.getHibernateLazyInitPort();
port.insertRecords();
} catch (Exception ex) {
// TODO handle custom exceptions here
ex.printStackTrace();
}

}

int retrieveRecordsOfBook() {

try { // Call Web Service Operation
com.example.ws.service.HibernateLazyInitService service = new com.example.ws.service.HibernateLazyInitService();
com.example.ws.service.HibernateLazyInit port = service.getHibernateLazyInitPort();
// TODO process result here
java.util.List result = port.retrieveRecordsOfBook();
System.out.println("Result = "+result);

return result.size();
} catch (Exception ex) {
// TODO handle custom exceptions here
ex.printStackTrace();

return 0;
}

}

int retrieveRecordsOfLibrary() {

try { // Call Web Service Operation
com.example.ws.service.HibernateLazyInitService service = new com.example.ws.service.HibernateLazyInitService();
com.example.ws.service.HibernateLazyInit port = service.getHibernateLazyInitPort();
// TODO process result here
java.util.List result = port.retrieveRecordsOfLibrary();
System.out.println("Result = "+result);

return result.size();

} catch (Exception ex) {
// TODO handle custom exceptions here
ex.printStackTrace();

return 0;
}

}

public static void main(String[] args) {
// TODO code application logic here

Main client = new Main();
client.insertRecords();
System.out.println("Size of books : " + client.retrieveRecordsOfBook() );
System.out.println("Size of library : " + client.retrieveRecordsOfLibrary() );
}

btw, the ide is netbeans 6.5.1 with glassfish.

Edit on 11:14 :
the above solution is good when you want to use standard jpa and stay away from hibernate specific solutions..
but if it is ok to use hibernate specific annotations, you can try @Fetch(FetchType.JOIN)..

Edit on 14/12/2010 :
HibernateBeanReplicator is also a solution.. see http://hilaltarakci.blogspot.com/2009/09/java-deep-clone-library.html for details..

7 Eylül 2009 Pazartesi

jpa inheritance mechanism

i do not reinvent the wheel by explaning jpa inheritance mechanism here, it is already well documented at many places one of which http://windhood.wordpress.com/2009/03/03/jpa-inheritance-overview/

instead, i mention a bug i have met.. i think it is a bug, correct me if i am wrong :)

assume there is a root class ClassA which ClassB inherits from.. and there is a ClassC which inherits from ClassB..

@Inheritance(strategy=InheritanceType.JOINED)
public ClassA {
...
}

@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public ClassB extends ClassA {
...
}

public ClassC extends ClassB {
...
}

It does not matter which inheritance type you specified for ClassB, for all hierarchy, the inheritance type specified for ClassA, the very root class, is used. 
In above case, the inheritance strategy is JOINED for all..

well, that is all.. 

3 Eylül 2009 Perşembe

bpel fault handling - 2

i mentioned a bug in my previous post: http://hilaltarakci.blogspot.com/2009/09/bpel-fault-handling.html
(just read the lines in red ).. however, i was wrong, that was not the real bug..

the problem:
Lets repeat the scenario. There is a web service throwing some exception and there is a bpel process delegating exactly the same exception. Unfortunately, at the client side, the details of the exception comes null even though the exception is properly catched..


catch (FaultCatchWsdlOperationFault ex) {
MyException2 exc = ex.getFaultInfo();
}


the reason:
If the bpel process uses the same exception type with the invoked web service's exception, than there is something wrong and the detail of the exception (detail comes from the web service) does not come with exception.getFaultInfo() method in your client app.

the solution:
The workaround is using different types in web service and bpel faults.
i hope the explanation is clear enough :)