AMIS Oracle and Java Blog » Jeroen van Wilgenburg https://technology.amis.nl Friends of Oracle and Java Fri, 24 Apr 2015 10:03:11 +0000 en-US hourly 1 http://wordpress.org/?v=4.2 Running a BPEL process created with Netbeans in Apache ODE https://technology.amis.nl/2008/08/26/running-a-bpel-process-created-with-netbeans-in-apache-ode/ https://technology.amis.nl/2008/08/26/running-a-bpel-process-created-with-netbeans-in-apache-ode/#comments Tue, 26 Aug 2008 14:32:18 +0000 http://technology.amis.nl/blog/?p=3355 Share this on .. A BPEL process without using vendor specific extensions should run everywhere without much hassle. But unfortunately it doesn’t. In this article I will show you how to create a BPEL process with Netbeans and what changes you have to make to make it run on Apache ODE.   A while ago [...]

The post Running a BPEL process created with Netbeans in Apache ODE appeared first on AMIS Oracle and Java Blog.

]]>
Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

A BPEL process without using vendor specific extensions should run everywhere without much hassle. But unfortunately it doesn’t. In this article I will show you how to create a BPEL process with Netbeans and what changes you have to make to make it run on Apache ODE.

....
 

A while ago I wrote an article about testing BPEL-processes on ODE with SoapUI. When I started that article the idea was to create my own process with the Eclipse BPEL-editor. At that moment it took me enough time to deploy an example process on ODE, so I decided to skip that part.
Recently I found out Netbeans also has a BPEL-editor. I tried to deploy a process on Glassfish and again that didn’t work as easy as it should.

The only solution to these kind of problems is dissecting example files and reading tutorials. Reading tutorials is of course the first step. Unfortunately there isn’t much to read for beginners. A blog by a guy named Julien got me started, but it after a while I gave up and looked for the example files.

Dissecting the HelloWorld2 example

I used the HelloWorld2 example from my previous blog about BPEL and decided to print out the deploy.xml, HelloWorld2.bpel and HelloWorld2.wsdl files and compare them with the files Netbeans creates.
I won’t bother you with the comparisons, I’ll just show you what you have to add to make the files ODE-compliant.

Creating a BPEL process in Netbeans

For this article I used Netbeans 6.1 (make sure you download the largest version, this one includes the SOA plugins)
Create a new BPEL module by creating a new project (in the SOA folder). Call this process the LsoModule. Now we have to create a WSDL to define the input and output parameters. Right click the LsoModule, New, WSDL Document

Call the file lsoWsdl and change the target namespace:

click next and change the input and output parameter names:

Click finish and your WSDL is created

The file lsoWSDL.wsdl is opened. The next step is creating a service. We need a service to group portTypes and assign a url for ODE. This can be done by right clicking the services folder. Also add a port and a soap address. Change the names of the object so it matches this screenshot:


The address must match the address of your ODE deployment suffixed with /processes/procesName

The service must be bound to the process with a binding. A binding defines the interface and protocol details for the outside world. Right click bindings and add a binding and click ok. Right click the LsoPort and set the binding to the binding you just created.

Now we can create the BPEL process. Right click the LsoModule, New,  BPEL Process
Name the process lsoProcess with namespace http://www.amis.nl/bpel/LsoModule/lsoProcess

The BPEL-file opens and is of course empty.
To give the process an interface (the WSDL we created a minute ago) drag the .wsdl to the center of a swimlane (the grey things at the right and left of the process). An orange dot will appear, meaning you can release your mouse button

When your mouse button is released a PartnerLink will appear. Double click this partner link to change its name to LsoPartnerLink.

The process now needs to be connected to the partner link. Drag a Receive from the web palette to the center of the process. An icon with an envelope will appear. Drag this envelope to the envelope of the LsoPartnerLink. A green arrow will point from the LsoPartnerLink to the Receive.
You’ll probably also noticed the red circle with a white x in it. These errors should never be ignored, your process won’t work properly when there are errors.
When you click the error you will be informed a reply is missing and there is no input variable.

To add a variable click the envelope, a small edit icon will appear above the Receive.
Click the create button to create a new variable. For now it’s okay to use the name LsoWSDLOperationIn so it’s clear where this variable is coming from.

Drag a reply from the palette just under the Receive (an orange dot indicates the release point). Connect to the LsoPartnerLink by dragging from the center of the Reply to the LsoPartnerLink.
Create an output variable the same way as you created the input variable (call it LsoWSDLOperationOut)

Now our process takes input and gives output. Normally your process would do something with this input and output, this process doesn’t. It just returns the input,
To do this you’ll need an Assign operation. Drag an Assign between the Receive and Reply. Now connect the input to the output:

Our process is now finished. Now the deploy.xml for ODE needs to be created.

Creating the deploy.xml
It’s a lot of manual work to create the deploy.xml and you have to be very precise. I took the deploy.xml from the HelloWorld2 example from ODE and changed it.
The first change is the pns (probably stands for process name space). This is the namespace you use in the .bpel file (the targetNamespace in the root element).
The following change is the wns (WSDL name space). This is the targetNamespace from the .wsdl file.
Next we have the process name. This is pns followed by a colon and the process name from the .bpel file.
The fourth change is the partner link. The link name can be found in the .bpel file.
The final changes are in the service tag. The values can be found in the .wsdl file

After all the changes are applied you will have this xml file:

 

<p>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;<br /><br />&lt;deploy xmlns=&quot;http://www.apache.org/ode/schemas/dd/2007/03&quot;<br /><br />&nbsp;&nbsp; &nbsp;xmlns:pns=&quot;http://www.amis.nl/bpel/LsoModule/lsoProcess&quot;<br /><br />&nbsp;&nbsp; &nbsp;xmlns:wns=&quot;http://www.amis.nl/wsdl/lsoWSDL&quot;&gt;<br /><br />&nbsp;&nbsp; &nbsp;&lt;process name=&quot;pns:lsoProcess&quot;&gt;<br /><br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&lt;active&gt;true&lt;/active&gt;<br /><br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&lt;provide partnerLink=&quot;LsoPartnerLink&quot;&gt;<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;service name=&quot;wns:LsoService&quot; port=&quot;LsoPort&quot;/&gt;<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/provide&gt;<br /><br />&nbsp;&nbsp; &nbsp;&lt;/process&gt;<br /><br />&lt;/deploy&gt; <br /></p>

Deploying the files

To deploy the process create a directory named LsoService under <tomcat-dir>/webapps/ode/WEB-INF/processes (assuming you already have ODE running). Copy the three files (deploy.xml, lsoProcess.bpel and lsoWSDL.wsdl) to this directory.
When your deployment was successful you’ll see the lsoService at http://localhost:8080/ode/services/listServices. The link to the lsoService can be used with SoapUI to test this service:

>

When you update the files in the directory the changes are not detected. To redeploy the process you have to remove LsoService.deployed in the processes directory (it immediately will re-appear because the process is deployed again).

Sources

http://home.izforge.com/index.php/2007/01/09/314-the-other-netbeans-bpel-tutorial
https://technology.amis.nl/blog/?p=3026
http://www.w3schools.com/WSDL/default.asp
http://www.w3.org/TR/wsdl

Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

The post Running a BPEL process created with Netbeans in Apache ODE appeared first on AMIS Oracle and Java Blog.

]]>
https://technology.amis.nl/2008/08/26/running-a-bpel-process-created-with-netbeans-in-apache-ode/feed/ 2
Mapping composite primary keys in JPA How to work around a bug in Hibernate Annotations https://technology.amis.nl/2008/05/18/mapping-composite-primary-keys-in-jpa-how-to-work-around-a-bug-in-hibernate-annotations/ https://technology.amis.nl/2008/05/18/mapping-composite-primary-keys-in-jpa-how-to-work-around-a-bug-in-hibernate-annotations/#comments Sun, 18 May 2008 18:45:34 +0000 http://technology.amis.nl/blog/?p=3177 Share this on .. A table without single-column primary key, Java developers don’t like them because it’s more work than just putting @Id on a field. When you’re using Hibernate Annotations you might also run into an annoying bug. In this article I will explain how to map a composite primary key with JPA-annotations and [...]

The post Mapping composite primary keys in JPA How to work around a bug in Hibernate Annotations appeared first on AMIS Oracle and Java Blog.

]]>
Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

A table without single-column primary key, Java developers don’t like them because it’s more work than just putting @Id on a field. When you’re using Hibernate Annotations you might also run into an annoying bug. In this article I will explain how to map a composite primary key with JPA-annotations and how to work around the bug in Hibernate Annotations.

On the AMIS SOA training program we got a nice assignment. The instructors gave us a WSDL, a database and some instructions. We had to create something with the SOA Suite based on the WSDL and the instructors would connect to our service to test whether we succeeded. Our team (Alex, Patrick B. and me) decided to make a ‘something’ with BPEL and PL/SQL.
When I came home after the training I thought why not also do it in java, just to refresh my knowledge. I generated some Java classes based on the WSDL with XFire, that went quite smooth (thanks to earlier experience with XFire [AM1]:).
The next step was connecting to the database with Hibernate Annotations. I used all the standard JPA annotations, so this should also work with Toplink Essentials or any other JPA-implementation. I forgot that some tools exist to generate the mapping, so I did it by hand.

These are the database tables:

After some simple tables a table with a composite Id was in my way. I usually avoid those tables, but now I had no control over the tables (well actually I have, but that’s considered cheating the assignment ūüėČ )
After searching on google and dzone I didn’t get any further, the closest thing to a solution was a piece of information in the Hibernate manual [HI1]. That link got me confused and it isn’t really clear what you have to do. I guess I’m also a bit rusty with Hibernate. To clean off rust you can use Cola, so I opened a can, drank it and I almost immediately had a result. I remembered I wrote a blog about generating annotated classes for JPA [AM2]. So let’s give that a shot.
My idea was to create a mapping for the annoying table and see what was generated. After that I can probably remove some annotations and attributes on existing annotations. The table in the way was the CC_REGISTRATIONS table. To create a solution I just created mappings for the primary key columns (att_id and ssn_id) and a random normal column (status).¬† This way you don’t have to scroll through pages of code and it’s easier for me to see a solution.

The result of the generating process was two classes (yes, I also expected one): CcRegistrationsEntity and  CcRegistrationsEntityPK. The CcRegistrationsEntity is just like your normal entity. The only differences are an extra annotation on the class definition: @IdClass(CcRegistrationsEntityPK.class) and two @Id annotations (on attId and ssnId) instead of one.

package nl.amis.csi;


import javax.persistence.*;
import java.math.BigInteger;


@Entity
@IdClass(CcRegistrationsEntityPK.class)
@Table(schema = "CCSI", name = "CC_REGISTRATIONS")
public class CcRegistrationsEntity {
    private BigInteger ssnId;
    private BigInteger attId;
    private String status;

    @Id
    @Column(name = "SSN_ID", nullable = false, length = 10)
    public BigInteger getSsnId() { ... }

    public void setSsnId(BigInteger ssnId) { ... }

    @Id
    @Column(name = "ATT_ID", nullable = false, length = 10)
    public BigInteger getAttId() { ... }

    public void setAttId(BigInteger attId) { ... }

    @Basic
    @Column(name = "STATUS", length = 1)
    public String getStatus() { ... }

    public void setStatus(String status) { ... }

    public boolean equals(Object o) { ... }

    public int hashCode() { ... }
}



The CcRegistrationsEntityPK class has the primary key fields of the table and -very important- an overridden equals and hashCode method.

package nl.amis.csi;

import java.io.Serializable;

public class CcRegistrationsEntityPK implements Serializable {
    private java.math.BigInteger ssnId;
    private java.math.BigInteger attId;

    public java.math.BigInteger getSsnId() { ... }

    public void setSsnId(java.math.BigInteger ssnId) { ... }

    public java.math.BigInteger getAttId() { ... }

    public void setAttId(java.math.BigInteger attId) { ... }

    public boolean equals(Object o) {... }

    public int hashCode() { ... }
}

Now this all looks quite reasonable, but I got an error:
Caused by: java.sql.SQLException: ORA-00904: “CSIREGISTR0_”.”SSNID”: invalid identifier
That’s strange, there should be an underscore. Renaming the getSsnId to getSsn_id is a solution, but a very ugly one. After some searching I found out this actually is a bug in Hibernate Annotations [HI2]. Luckily there is a comment on that bug that is very helpful. When you move the @Column annotations for the Id columns to the IdClass everything works fine.

** Update 20-05 √Ę‚ā¨‚Äú How you really should do it **

After the comment of p3t0r I contacted him and the word ‘prefer’ was a real understatement. With the @IdClass annotation you have redundant information in your classes and there is a much cleaner solution (which I didn’t get at the time). But here it is (I actually did it myself, p3t0r just gave me a lot of directions). First the CsiRegistrations2 class:

package nl.amis.hibernate.tables;

import javax.persistence.*;

@Entity
@Table(name = "CC_REGISTRATIONS")
public class CsiRegistrations2 {

    private CsiRegistrations2PK pk;

    private String status;

    @EmbeddedId
    public CsiRegistrations2PK getPk() {...}

    public void setPk(CsiRegistrations2PK pk) {...}

    @Column
    public String getStatus() {...}

    public void setStatus(String status) {...}
}

As you can see the id’s are replaced with a CsiRegistrations2PK object and annotated with an @EmbeddedId. The CsiRegistrations2 class:

package nl.amis.hibernate.tables;

import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.io.Serializable;
import java.math.BigInteger;

@Embeddable
public class CsiRegistrations2PK implements Serializable {

    private BigInteger sessionId;
    private BigInteger attendeeId;

    @Column(name = "SSN_ID", nullable = false, length = 10)
    public BigInteger getSessionId() {...}

    public void setSessionId(BigInteger sessionId) {...}

    @Column(name = "ATT_ID", nullable = false, length = 10)
    public BigInteger getAttendeeId() {...}

    public void setAttendeeId(BigInteger attendeeId) {...}
}

This is almost the same as the previous example, but with an @Embeddable.
The reason why the bu
g on Hibernate Annotations is o
pen for so long is because there is a better solution I guess. And again a confirmation my theory: blaming a bug is just a sign of a bad developer ūüėČ

** end of update **

Conclusion

It’s very educational to write JPA-annotations yourself, but when you’re stuck don’t try for too long, let a generator do the work for you and try to figure out why a piece of code is generated. It’s a pity that there is a bug in Hibernate Annotations, but on the other hand it’s the first real bug I found. I found it very hard to find a blog/article that explains how to map composite primary keys, it isn’t that difficult after all, so I probably used the wrong keywords.

Sources

[HI1] http://www.hibernate.org/hib_docs/annotations/reference/en/html/entity.html#d0e1662
[HI2] http://opensource.atlassian.com/projects/hibernate/browse/EJB-286
[AM1]  https://technology.amis.nl/blog/?p=2533
[AM2] https://technology.amis.nl/blog/?p=2361

Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

The post Mapping composite primary keys in JPA How to work around a bug in Hibernate Annotations appeared first on AMIS Oracle and Java Blog.

]]>
https://technology.amis.nl/2008/05/18/mapping-composite-primary-keys-in-jpa-how-to-work-around-a-bug-in-hibernate-annotations/feed/ 2
Wicket √Ę‚ā¨‚Äú It can do Ajax without writing any line of Javascript! https://technology.amis.nl/2008/03/29/wicket-it-can-do-ajax-without-writing-any-line-of-javascript/ https://technology.amis.nl/2008/03/29/wicket-it-can-do-ajax-without-writing-any-line-of-javascript/#comments Sat, 29 Mar 2008 19:19:22 +0000 http://technology.amis.nl/blog/?p=3066 Share this on .. Wicket is around for a while, but lately it is getting more and more attention. A few years ago I attended a presentation about Wicket. It looked like a nice framework, but at that time I didn’t see much differences with Tapestry and put it on my list of nice frameworks. [...]

The post Wicket √Ę‚ā¨‚Äú It can do Ajax without writing any line of Javascript! appeared first on AMIS Oracle and Java Blog.

]]>
Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

Wicket is around for a while, but lately it is getting more and more attention. A few years ago I attended a presentation about Wicket. It looked like a nice framework, but at that time I didn’t see much differences with Tapestry and put it on my list of nice frameworks. A few weeks ago a colleague told me some site was comparing Wicket with GWT. We both found that a bit strange, so I took a look at Wicket to see what became of it. It seems like Wicket can create Ajax-things for you without writing any Javascript (just like GWT, but that’s probably one of the few similarities). That’s what this blog is about. It gives a short introduction to Wicket and shows you how to create your first Ajax-call. This isn’t a getting started guide, there are many guides around (which can be found in the conclusion), I just focus on the Ajax-functionality here.
....

Wicket is a web framework that is a little bit different than most web frameworks we know. It doesn’t use jsp, but instead you can annotate html tags with a wicket attribute. The wicket attributes are referenced from within java code and the annotated tags become java objects.

The easiest way to get started with Wicket is creating a Wicket archetype with Maven 2. On the Wicket site you can generate a command to create a Maven 2 project.

You can set the groupId and artifactId and after that you have to pick a version. All you have to do now is copy the command and run it in a command line window (Maven 2 needs to be installed). This is the first time I’ve seen this and I hope other frameworks/libraries will copy this, it’s always a bit of a hustle to get started with a new framework and now it only takes a few seconds!
The final step is creating the files for  your IDE (http://wicket.apache.org/quickstart.html scroll down to the bottom) and open your IDE to browse the generated project.

The first thing that catches the eye is that there is no servlet for Wicket inside the web.xml, most web frameworks use a servlet, Wicket only needs a filter. The filter points to a class that is the heart of your application, in this case WicketApplication.
WicketApplication is a class that extends the WebApplication class. Inside the WicketApplication you have to override the getHomePage method. This is the starting point of your application and determines the first page the user will see.
With the archetype you get a page called HomePage. The page consists of a .java and .html file. The java file is the class that is returned inside the getHomePage method in WicketApplication. The .html is just an ordinary .html file with some the earlier mentioned wicket attributes. The HomePage page has a wicket:id=√Ę‚ā¨¬Ěmessage√Ę‚ā¨¬Ě on a span. This message is referenced inside HomePage.java:
add(new Label("message", "If you see this message wicket is properly configured and running"));
The first argument of the Label object is the id of the element (in the .html), the second argument is the value of Label as we will see it in the browser. Of course this text is displayed when we compile and deploy the application. Open the root of the web application (in my case http://localhost:8080/wicket) to see the result.

Now add comment slashes to skip the call to the add method in HomePage.java. After recompiling we get a very useful error message (and I’m not being ironic, I really like it when developers pay attention to their error messages):

WicketMessage: Unable to find component with id ‘message’ in [Page class = nl.amis.HomePage, id = 0, version = 0]. This means that you declared wicket:id=message in your markup, but that you either did not add the component to your page at all, or that the hierarchy does not match.
[markup = file:/D:/Documents/wicket-test/target/wicket-test/WEB-INF/classes/nl/amis/HomePage.html
Ok let’s put the add back and add Ajax to the page.

Adding ajax behaviour to your pages

And now the reason why I’m writing this blog, ajax behaviour without one line of Javascript!
On my page I want to display the status of the system (this is a String that lives in a static class). The initial status says √Ę‚ā¨Ňďthe application is started√Ę‚ā¨¬Ě and after a click on a link the status  must say: √Ę‚ā¨Ňďthe application is still running√Ę‚ā¨¬Ě, without refreshing the page of course!

Add a link to your HomePage.html: <a href="#" wicket:id="link">click me</a>

The java file needs some changes, in fact so many that I just paste my new class and explain what I’ve done:


public class HomePage extends WebPage {
    private static final long serialVersionUID = 1L;

    public HomePage(final PageParameters parameters) {

        final Model model = new Model() {
            public Object getObject() {
                return StatusService.getStatus();
            }
        };

        final Label label = new Label("message", model);
        label.setOutputMarkupId(true);

        add(label);

        add(new AjaxFallbackLink("link") {
            public void onClick(AjaxRequestTarget target) {
                System.out.println("onclick");
                StatusService.setStatus("Application is still running");
                target.addComponent(label);
            }
        });
    }
}

The link we just added to the .html needs to become an AjaxFallbackLink. A method must be invoked when the onclick event in Javascript is fired. With the AjaxFallbackLink there is an onclick method we can override. In this method the status is updated. When the status is updated the component must be added to the page again, with the addComponent method.
The Model object seems a bit strange, but in Wicket almost everything is an object, in this case the message of the Label is an Object and not a String.

When we load the page for the first time we see the initial state:

After clicking the link the status is updated:

Note that the page is not reloaded. Let’s analyze the ajax request:
<ajax-response>
<component id="message2">
<span wicket:id="message" id="message2">Application is still running</span>
</component>
</ajax-response>

This response is very clear, the component with id message2 needs to be refreshed with a new text. The AJAX-request can be analyzed in Firebug (when you see no response, click with the middle mouse button on the url, there are some problems rendering xml in Firebug I guess). Another option is the √Ę‚ā¨ŇďWICKET AJAX DEBUG√Ę‚ā¨¬Ě on the bottom right corner of your page. Because we’re running in developer mode we can analyze the ajax traffic, very neat!

Conclusion

It seems Wicket really has evolved since the first time I saw it. I really like the way they ‘do’ Ajax. I  think I have some trouble getting used to using objects for everything (the Model object on the Label for example), but maybe it’s because I just started with Wicket. When you’re used to frameworks like Struts, Spring and Stripes you really have to take your time to get used to the component based structure of Wicket. It might be a bit difficult at first, but after a while you’ll see that it is very useful and the Wicket guys really thought about it.
The documentation and error messages are really good, they really helped me understand Wicket better.
If you want to start with Wicket I suggest reading the article on The Server Side and also don’t forget to check out the excellent samples on the Wicket page.

Sources

http://wicket.apache.org/index.html
http://wicket.apache.org/quickstart.html

Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

The post Wicket √Ę‚ā¨‚Äú It can do Ajax without writing any line of Javascript! appeared first on AMIS Oracle and Java Blog.

]]>
https://technology.amis.nl/2008/03/29/wicket-it-can-do-ajax-without-writing-any-line-of-javascript/feed/ 2
Using SoapUI on Apache ODE to test your BPEL processes more quickly https://technology.amis.nl/2008/03/24/using-soapui-on-apache-ode-to-test-your-bpel-processes-more-quickly/ https://technology.amis.nl/2008/03/24/using-soapui-on-apache-ode-to-test-your-bpel-processes-more-quickly/#comments Mon, 24 Mar 2008 16:02:13 +0000 http://technology.amis.nl/blog/?p=3026 Share this on .. On the SOA-training I’m following we’re using the Oracle SOA Suite, a very nice product, but the time needed between saving changes and deploying the process takes way too long. I also want to know exactly what’s happening and have control over the external web services. In this blog I will [...]

The post Using SoapUI on Apache ODE to test your BPEL processes more quickly appeared first on AMIS Oracle and Java Blog.

]]>
Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

On the SOA-training I’m following we’re using the Oracle SOA Suite, a very nice product, but the time needed between saving changes and deploying the process takes way too long. I also want to know exactly what’s happening and have control over the external web services. In this blog I will show you how you to deploy a process on ODE and how to use SoapUI to test a BPEL process.
....

Together with some colleagues we’re slowly becoming SOA-experts, we’re almost half way the SOA training and we learned a lot. Creating and deploying BPEL processes with JDeveloper is quite easy and the diagrams alone are a reason to learn BPEL ūüėČ
I do however have the feeling I’m not really knowing what’s happening. I want to know which files are needed for a BPEL process and have more control over the input and output. Of course I can ask the instructors which files are needed and what each file does, but it’s more educational to find out yourself.

What I needed was a simple BPEL virtual machine. My only requirements were that it had to work within a few minutes,  has proper documentation and work on Tomcat. A search for BPEL engine on google gave quite some results. I picked Apache ODE because that was the easiest to pronouce. After reading the documentation and deploying the HelloWorld process it fulfilled all my requirements.
You probably think this is a strange way to pick software, but what I’m about to do will never run in a production environment and is only needed to help me develop quicker and learn more about BPEL.

Running ODE inside Tomcat

The first step is downloading ODE and deploy the war on Tomcat.
Dowload ODE here. Unzip the zip file and you will find ode.war inside the first directory. Copy this file to your Tomcat webapps directory (while Tomcat is running) and watch the log file, you should see that the BPEL Server and ODE Service are both started. Now visit http://localhost:8080/ode/ in your browser and you should see the start page:

It might be a bit strange that you see Axis 2 and not ODE, but this is ok, Axis 2 is also something with WSDL’s ūüėČ

BPEL processes will be listed under Services. Right now there are some admin serivces, we want to add an Hello World example.

Deploying the Hello World example

The ODE zip file ships with some examples. Of course we start with the Hello World sample. You can find this sample in the examples\HelloWorld2 directory. The testRequest.soap file is used with a command line utility to test the process. We will skip this utility because there is an easier way to test.
The deploy.xml describes how the partner link in the .bpel file is connected to the service in the .wsdl file.
HelloWorld2.bpel is the actual process. It takes an input variable and outputs it suffixed with World. The .wsdl file describes the input and output message for the process (a BPEL process is invoked just like a web service)
In a diagram this is the process:

Now that you have a basic understanding of the process it is time to deploy it. Copy the HelloWorld2 directory to the webapps\ode\WEB-INF\processes directory of your running Tomcat instance. Deploying a process takes a few seconds so you can immediately see the result on http://localhost:8080/ode/. Click on services and you should see a helloWorld process.
Righ click the helloWorld link and copy the url, you need this url to test the process.

SoapUI

Since a BPEL process publishes a WSDL  it is easy to connect to the process. On JavaPolis I was quite impressed by SoapUI. It’s a tool for web service testing. You can give it a WSDL and it will generate an XML message which you can send to the endpoint of the WSDL. Of course the XML answer can also be reviewed.

SoapUI can be downloaded or started via Java Web Start
Click on the File menu, New WSDL Project and paste the url at the Initial WSDL text field. Give your project a useful name and click ok

After the wsdl is finished loading you see a tree. Expand the branches helloWorldSOAP12Binding and hello and double click on Request 1. soapUI now generates a request to the webservice (your Hello World process). This request is the same as the testRequest.soap we skipped earlier. You can change the details of the request. Let’s change the contents of the TestPart tag. Enter Hello instead of a question mark. Now hit the green play button to invoke the process.
The result will appear in the right pane:

&lt;soapenv:Envelope <br />&nbsp;&nbsp; &nbsp;xmlns:soapenv=&quot;http://www.w3.org/2003/05/soap-envelope&quot;&gt;<br />&nbsp;&nbsp; &lt;soapenv:Body&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;axis2ns2:helloResponse <br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;xmlns:axis2ns2=&quot;http://ode/bpel/unit-test.wsdl&quot;&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;TestPart <br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;xmlns:soap=&quot;http://www.w3.org/2003/05/soap-envelope&quot; <br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;xmlns:unit=&quot;http://ode/bpel/unit-test.wsdl&quot;&gt;Hello World&lt;/TestPart&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/axis2ns2:helloResponse&gt;<br />&nbsp;&nbsp; &lt;/soapenv:Body&gt;<br />&lt;/soapenv:Envelope&gt;

Conclusion

Of course this example is pretty basic, but it shows you how easy it can be to deploy and test a BPEL process.
I also tried to get my BPEL processes created with JDeveloper running inside ODE, but that wasn’t as easy as I thought. There were some challenges with name spaces and older versions of the WSDL files. I spent a lot of time analyzing the .wsdl and .bpel files to find out what went wrong. So far no results, but I learned a lot about .wsdl and .bpel. I haven’t given up on it yet, I just need a break ūüėČ When I found out how to do it I will write an article on this weblog about it.
With soapUI it is also possible to create test cases with asserts in it, this way you can automate the testing of your BPEL processes.
Apache ODE is a nice tool to work with. Earlier I mentioned that I’m not going to use it in a production environment, but maybe it’s mature enough to run in a production environment, I haven’t looked into that.

Sources

Soap UI
Soap UI web start link
Eclipse BPEL
Apache ODE

Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

The post Using SoapUI on Apache ODE to test your BPEL processes more quickly appeared first on AMIS Oracle and Java Blog.

]]>
https://technology.amis.nl/2008/03/24/using-soapui-on-apache-ode-to-test-your-bpel-processes-more-quickly/feed/ 7
Opening and extracting Zip files in java – It’s there for a while, but I just found out https://technology.amis.nl/2007/11/20/opening-and-extracting-zip-files-in-java-its-there-for-a-while-but-i-just-found-out/ https://technology.amis.nl/2007/11/20/opening-and-extracting-zip-files-in-java-its-there-for-a-while-but-i-just-found-out/#comments Tue, 20 Nov 2007 14:44:11 +0000 http://technology.amis.nl/blog/?p=2609 Share this on .. A while ago I found out that it was possible to open Zip files with Java. Just open a regular java.io.File and pass it to the java.util.zip.ZipFile constructor. It is possible for a long time (at least since version 1.3), but I didn’t expect this kind of functionality in an SDK. [...]

The post Opening and extracting Zip files in java – It’s there for a while, but I just found out appeared first on AMIS Oracle and Java Blog.

]]>
Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

A while ago I found out that it was possible to open Zip files with Java. Just open a regular java.io.File and pass it to the java.util.zip.ZipFile constructor.
It is possible for a long time (at least since version 1.3), but I didn’t expect this kind of functionality in an SDK. I was looking for a library to do it when a javadoc page from Sun showed up.

After analysis of that page I came up with a small piece of code. Again no rocket science, but it can save you some time and when I have to do something with zip files I just search for this blog ūüėČ
I created an application that uses xml files. Those xml files can be uploaded, but they can grow very big. The largest file I had to handle was about 83MB. Internet is fast but you still have to wait for these file sizes to be uploaded. A solution is zipping the file and let the server extract it.

<code>
<span style="color: #7f0055;"><strong>public </strong></span><span style="color: #7f0055;"><strong>void </strong></span><span style="color: #000000;">extractFile</span><span style="color: #000000;">(){</span>
<span style="color: #ffffff;">  </span><span style="color: #000000;">File file = </span><span style="color: #7f0055;"><strong>new </strong></span><span style="color: #000000;">File</span><span style="color: #000000;">(</span><span style="color: #2a00ff;">"c:\\temp\\ZipFileWithManyFiles.zip"</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">  </span><span style="color: #000000;">ZipFile zipFile = </span><span style="color: #7f0055;"><strong>new </strong></span><span style="color: #000000;">ZipFile</span><span style="color: #000000;">(</span><span style="color: #000000;">file</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">  </span><span style="color: #000000;">Enumeration&lt;? </span><span style="color: #7f0055;"><strong>extends </strong></span><span style="color: #000000;">ZipEntry&gt; enumeration = zipFile.entries</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">  </span><span style="color: #7f0055;"><strong>while </strong></span><span style="color: #000000;">(</span><span style="color: #000000;">enumeration.hasMoreElements</span><span style="color: #000000;">()) {</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">ZipEntry zipEntry = enumeration.nextElement</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">String zipFileName = zipEntry.getName</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>

<span style="color: #ffffff;">    </span><span style="color: #000000;">InputStream inputStream = zipFile.getInputStream</span><span style="color: #000000;">(</span><span style="color: #000000;">zipEntry</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">OutputStream out = </span><span style="color: #7f0055;"><strong>new </strong></span><span style="color: #000000;">FileOutputStream</span><span style="color: #000000;">(</span><span style="color: #2a00ff;">"c:\\temp\\extracted\\" </span><span style="color: #000000;">+ zipFileName</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">writeInputStreamToOutputStream</span><span style="color: #000000;">(</span><span style="color: #000000;">inputStream, out</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">out.close</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">inputStream.close</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">  </span><span style="color: #000000;">}</span>
<span style="color: #000000;">}</span>

<span style="color: #7f0055;"><strong>private </strong></span><span style="color: #7f0055;"><strong>void </strong></span><span style="color: #000000;">writeInputStreamToOutputStream</span><span style="color: #000000;">(</span><span style="color: #000000;">InputStream inputStream, OutputStream out</span><span style="color: #000000;">) </span><span style="color: #7f0055;"><strong>throws </strong></span><span style="color: #000000;">IOException </span><span style="color: #000000;">{</span>
<span style="color: #ffffff;">    </span><span style="color: #3f7f5f;">// Transfer bytes from the ZIP file to the output file</span>
<span style="color: #ffffff;">    </span><span style="color: #7f0055;"><strong>byte</strong></span><span style="color: #000000;">[] </span><span style="color: #000000;">buf = </span><span style="color: #7f0055;"><strong>new </strong></span><span style="color: #7f0055;"><strong>byte</strong></span><span style="color: #000000;">[</span><span style="color: #990000;">1024</span><span style="color: #000000;">]</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">    </span><span style="color: #7f0055;"><strong>int </strong></span><span style="color: #000000;">len;</span>
<span style="color: #ffffff;">    </span><span style="color: #7f0055;"><strong>while </strong></span><span style="color: #000000;">((</span><span style="color: #000000;">len = inputStream.read</span><span style="color: #000000;">(</span><span style="color: #000000;">buf</span><span style="color: #000000;">)) </span><span style="color: #000000;">&gt; </span><span style="color: #990000;">0</span><span style="color: #000000;">) {</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">out.write</span><span style="color: #000000;">(</span><span style="color: #000000;">buf, </span><span style="color: #990000;">0</span><span style="color: #000000;">, len</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">}</span>
<span style="color: #000000;">}</span></code>

A ZipFile is not a File when you follow the Object Oriented inheritance rules, that’s a bit strange, but I can live with it. Once you instansiated the ZipFile you can call the entries() method and you will receive a list with all files in the archive.
You can get an InputStream for every entry, note that you have to get the InputStream from ZipFile, not ZipEntry.
To write the InputStream to an OutputStream I wrote a small method (does anyone know a better solution?, my method doesn’t feel right). And finally you have to close the out and inputStream.

The ZipFile classes are very useful, the API is a bit odd, but does the trick.

Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

The post Opening and extracting Zip files in java – It’s there for a while, but I just found out appeared first on AMIS Oracle and Java Blog.

]]>
https://technology.amis.nl/2007/11/20/opening-and-extracting-zip-files-in-java-its-there-for-a-while-but-i-just-found-out/feed/ 2
Compile and invoke your webservice client (generated by XFire) in a running JVM https://technology.amis.nl/2007/11/09/compile-and-invoke-your-webservice-client-generated-by-xfire-in-a-running-jvm/ https://technology.amis.nl/2007/11/09/compile-and-invoke-your-webservice-client-generated-by-xfire-in-a-running-jvm/#comments Fri, 09 Nov 2007 14:19:03 +0000 http://technology.amis.nl/blog/?p=2533 Share this on .. Generating XFire client files isn’t that special, but with Java 6 it is possible to compile those files immediately and invoke the webservice within one application. When I told this idea to a colleague he was a bit worried, because there are tools out there that can do this for you. [...]

The post Compile and invoke your webservice client (generated by XFire) in a running JVM appeared first on AMIS Oracle and Java Blog.

]]>
Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

Generating XFire client files isn’t that special, but with Java 6 it is possible to compile those files immediately and invoke the webservice within one application. When I told this idea to a colleague he was a bit worried, because there are tools out there that can do this for you. But it’s just an exercise. I don’t play enough with XFire and testing new Java 6 features is also something that’s on my list for a very long time.
What I want to do is provide a WSDL url, generate the client files, compile them and invoke a method on that client. Of course without any manual steps!

In this blog we take the following steps:

  • dissect the XFire command line WsGen application
  • generate the client files
  • compile the client files
  • invoke the web service

Dissecting WsGen

WsGen is the class you invoke when client files need to be generated from a WSDL. A detailed description of WsGen and the command parameters can be found here. I wanted to generate the files from within my application (without doing a Runtime.exec), so I had to find out how the XFire guys did it. Luckily XFire is open source and their subversion repository is browsable. What WsGen basically does is checking the command line parameters, returning errors or print a help message. Well that’s just what we don’t need for now, let’s throw that away. After removing that code this is the code we need:

<code>
<span style="color: #000000;">Wsdl11Generator generator = </span><span style="color: #7f0055;"><strong>new </strong></span><span style="color: #000000;">Wsdl11Generator</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>
<span style="color: #000000;">generator.setOutputDirectory</span><span style="color: #000000;">(</span><span style="color: #000000;">outputDirectory</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #000000;">generator.setWsdl</span><span style="color: #000000;">(</span><span style="color: #000000;">wsdl</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #000000;">generator.setExplicitAnnotation</span><span style="color: #000000;">(</span><span style="color: #000000;">explicit</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #000000;">generator.setOverwrite</span><span style="color: #000000;">(</span><span style="color: #000000;">overwrite</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #000000;">generator.setGenerateServerStubs</span><span style="color: #000000;">(</span><span style="color: #000000;">serverStubs</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>

<span style="color: #7f0055;"><strong>try </strong></span><span style="color: #000000;">{</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">generator.generate</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>
<span style="color: #000000;">} </span><span style="color: #7f0055;"><strong>catch </strong></span><span style="color: #000000;">(</span><span style="color: #000000;">Exception e</span><span style="color: #000000;">) {</span>
<span style="color: #ffffff;">    </span><span style="color: #7f0055;"><strong>throw new </strong></span><span style="color: #000000;">BuildException</span><span style="color: #000000;">(</span><span style="color: #000000;">e</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #000000;">}</span></code>

The overwrite, explicitAnnotation and generateServerStubs are not needed for this example, so we can set them to false. That leaves us with the output location and the WSDL url.

Generate the client files

When we run this piece of code generation code it generates a list of files deep inside some directories. Since our compiler needs every file (with its location) we have to list all the files. Now I can show you something I learned in school (yes that happens and I think it is so special that I wanted to tell it). When things with trees (a directory tree) need to be done you can do it the difficult way or the recursive way. Let’s do it the recursive way. I have a List of File objects that needs to be filled recursively:

<code>
<span style="color: #7f0055;"><strong>private </strong></span><span style="color: #7f0055;"><strong>void </strong></span><span style="color: #000000;">listFilesRecursive</span><span style="color: #000000;">(</span><span style="color: #000000;">List&lt;File&gt; fileList, </span><span style="color: #7f0055;"><strong>final </strong></span><span style="color: #000000;">File dir</span><span style="color: #000000;">) {</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">File</span><span style="color: #000000;">[] </span><span style="color: #000000;">files = dir.listFiles</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">    </span><span style="color: #7f0055;"><strong>for </strong></span><span style="color: #000000;">(</span><span style="color: #000000;">File f : files</span><span style="color: #000000;">) {</span>
<span style="color: #ffffff;">        </span><span style="color: #7f0055;"><strong>if </strong></span><span style="color: #000000;">(</span><span style="color: #000000;">f.isDirectory</span><span style="color: #000000;">()) {</span>
<span style="color: #ffffff;">            </span><span style="color: #000000;">listFilesRecursive</span><span style="color: #000000;">(</span><span style="color: #000000;">fileList, f</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">} </span><span style="color: #7f0055;"><strong>else </strong></span><span style="color: #000000;">{</span>
<span style="color: #ffffff;">            </span><span style="color: #7f0055;"><strong>if </strong></span><span style="color: #000000;">(</span><span style="color: #000000;">f.getName</span><span style="color: #000000;">()</span><span style="color: #000000;">.endsWith</span><span style="color: #000000;">(</span><span style="color: #2a00ff;">".java"</span><span style="color: #000000;">)) {</span>
<span style="color: #ffffff;">                </span><span style="color: #000000;">fileList.add</span><span style="color: #000000;">(</span><span style="color: #000000;">f</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">            </span><span style="color: #000000;">}</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">}</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">}</span>
<span style="color: #000000;">}</span></code>

The function calls itself when it finds a directory and the stop-condition is a file that is not a directory, when that file name ends with .java we add it to fileList and otherwise nothing happens.

Compile the client files

The list of files must be compiled in the next step. I found this great blog entry about compiling files in Java 6.
However, one very important part is missing. When you watch closely you see that the cl variable is not defined. This is where things can get horribly wrong. I got so stuck that I almost gave up. The Java class loader is a strange thing. There actually is a whole hierarchy that defines which class loader is loading your files. When you compiled your classes with Class Loader Y and you want to load them with Class Loader X it might not happen. It’s very complicated and I couldn’t find much information about the class loaders.

After adding the class loader
an
d my listFilesRecursive method to the Juixe code I ended up with this piece of code:

<code><span style="color: #000000;">JavaCompiler jc = ToolProvider.getSystemJavaCompiler</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>
<span style="color: #000000;">ClassLoader cl = Thread.currentThread</span><span style="color: #000000;">()</span><span style="color: #000000;">.getContextClassLoader</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>
<span style="color: #000000;">StandardJavaFileManager sjfm = jc.getStandardFileManager</span><span style="color: #000000;">(</span><span style="color: #000000;">null, null, </span><span style="color: #7f0055;"><strong>null</strong></span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>

<span style="color: #000000;">File dir = </span><span style="color: #7f0055;"><strong>new </strong></span><span style="color: #000000;">File</span><span style="color: #000000;">(</span><span style="color: #000000;">filesLocation</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>

<span style="color: #000000;">List&lt;File&gt; files = </span><span style="color: #7f0055;"><strong>new </strong></span><span style="color: #000000;">ArrayList&lt;File&gt;</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>
<span style="color: #000000;">listFilesRecursive</span><span style="color: #000000;">(</span><span style="color: #000000;">files, dir</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>

<span style="color: #000000;">Iterable&lt;? </span><span style="color: #7f0055;"><strong>extends </strong></span><span style="color: #000000;">JavaFileObject&gt; fileObjects = sjfm.getJavaFileObjects</span><span style="color: #000000;">(</span><span style="color: #000000;">files.toArray</span><span style="color: #000000;">(</span><span style="color: #7f0055;"><strong>new </strong></span><span style="color: #000000;">File</span><span style="color: #000000;">[]{}))</span><span style="color: #000000;">;</span>
<span style="color: #000000;">jc.getTask</span><span style="color: #000000;">(</span><span style="color: #000000;">null, sjfm, null, null, null, fileObjects</span><span style="color: #000000;">)</span><span style="color: #000000;">.call</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>
<span style="color: #000000;">sjfm.close</span><span style="color: #000000;">()</span></code>

 

Invoking the Web Service

This last step is a bit strange because I haven’t really thought about what I want to do now. A possible idea is to extract all the methods from the webservice and display the input parameters on a form on a web page. This is a lot of work and I’m already creating an application that already exists.

I make use of a publicly available web service. The WSDL can be found here.

When you access a web service you invoke a method on a Client object. What we know from XFire is that a the class name of the client ends with Client. So we look up the client class and make an instance of that object:

<code>
<span style="color: #000000;">String cn = generator.getClientClassName</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>
<span style="color: #000000;">Object client = Class.forName</span><span style="color: #000000;">(</span><span style="color: #000000;">cn</span><span style="color: #000000;">)</span><span style="color: #000000;">.newInstance</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span></code>

getClientClassName is a method that searches for the client class. The client class has a method called getEndpoints. This method must be invoked to receive a Collection with end points:

<code>
<span style="color: #000000;">Class clientClass = client.getClass</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>
<span style="color: #000000;">Method method = clientClass.getMethod</span><span style="color: #000000;">(</span><span style="color: #2a00ff;">"getEndpoints"</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #000000;">Collection&lt;Endpoint&gt; col = </span><span style="color: #000000;">(</span><span style="color: #000000;">Collection</span><span style="color: #000000;">) </span><span style="color: #000000;">method.invoke</span><span style="color: #000000;">(</span><span style="color: #000000;">client</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>

<span style="color: #000000;">System.out.println</span><span style="color: #000000;">(</span><span style="color: #2a00ff;">"End points:"</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #7f0055;"><strong>for </strong></span><span style="color: #000000;">(</span><span style="color: #000000;">Endpoint e : col</span><span style="color: #000000;">) {</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">System.out.println</span><span style="color: #000000;">(</span><span style="color: #2a00ff;">"  " </span><span style="color: #000000;">+ e.getName</span><span style="color: #000000;">())</span><span style="color: #000000;">;</span>
<span style="color: #000000;">}</span></code>

The web services I tried all returned an end points that ends with LocalEndPoint and another one, we need the other one. This method/endpoint needs to be invoked:

<code>
<span style="color: #ffffff;">        </span><span style="color: #000000;">Method call = clientClass.getMethod</span><span style="color: #000000;">(</span><span style="color: #2a00ff;">"getMidnightTraderSoap"</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">Object o = call.invoke</span><span style="color: #000000;">(</span><span style="color: #000000;">client</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>

<span style="color: #ffffff;">        </span><span style="color: #000000;">System.out.println</span><span style="color: #000000;">(</span><span style="color: #000000;">o</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">Method</span><span style="color: #000000;">[] </span><span style="color: #000000;">methods = o.getClass</span><span style="color: #000000;">()</span><span style="color: #000000;">.getMethods</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>

<span style="color: #ffffff;">        </span><span style="color: #7f0055;"><strong>for </strong></span><span style="color: #000000;">(</span><span style="color: #000000;">Method method1 : methods</span><span style="color: #000000;">) {</span>
<span style="color: #ffffff;">            </span><span style="color: #000000;">System.out.println</span><span style="color: #000000;">(</span><span style="color: #2a00ff;">"   :" </span><span style="color: #000000;">+ method1</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">}</span></code>

From this method we need to get the correct method(s). Let’s remove the methods that belong to java.lang.Object and the methods that do something with java.lang.reflect are also not needed
We end up with the following list:

   :public final com.strikeiron.ServiceInfoOutput $Proxy21.getServiceInfo(com.strikeiron.ws.LicenseInfo,javax.xml.ws.Holder)
   :public final void $Proxy21.getRemainingHits(com.strikeiron.ws.LicenseInfo)
   :public final com.strikeiron.StatusCodeOutput $Proxy21.getAllStatuses(com.strikeiron.ws.LicenseInfo,javax.xml.ws.Holder)
   :public final com.strikeiron.MidnightTraderOutput
$Proxy21.lookupFinancialNews(com.strikeiron.MidnightTraderRequest,com.strikeiron.ws.LicenseInfo,javax.xml.ws.Holder)

These methods

can also be invoked the way I described earlier, you just have to decide where to get your parameters from and what you want to do with the result.

Conclusion

At first sight it seems a waste of time to generate something that already exists. But these kind of exercises give a good insight in what is possible with Java 6 and I learned a lot about how web services work. I also think it’s really cool that you can make changes to the classes in your JVM. It’s like changing the wheels of your car when you run at full speed on a motor way.

Sources

http://xfire.codehaus.org/Client+and+Server+Stub+Generation+from+WSDL
http://fisheye.codehaus.org/browse/~raw,r=2183/xfire/trunk/xfire/xfire-generator/src/main/org/codehaus/xfire/gen/WsGen.java
http://www.juixe.com/techknow/index.php/2006/12/13/java-se-6-compiler-api/

Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

The post Compile and invoke your webservice client (generated by XFire) in a running JVM appeared first on AMIS Oracle and Java Blog.

]]>
https://technology.amis.nl/2007/11/09/compile-and-invoke-your-webservice-client-generated-by-xfire-in-a-running-jvm/feed/ 0
Battle of the Geeks 2007 – An eyewitness report https://technology.amis.nl/2007/09/26/battle-of-the-geeks-2007-an-eyewitness-report/ https://technology.amis.nl/2007/09/26/battle-of-the-geeks-2007-an-eyewitness-report/#comments Wed, 26 Sep 2007 12:57:46 +0000 http://technology.amis.nl/blog/?p=2412 Share this on .. Yesterday I attended the Battle of the Geeks. It was hosted by Finalist at the Netherlands Architecture Institute in Rotterdam. There were four presentations about different subjects. CMS Container, Google Guice, Gruby on Grails and Mule. A former colleague of mine (Peter Maas) was giving the presentation about Groovy and Grails. [...]

The post Battle of the Geeks 2007 – An eyewitness report appeared first on AMIS Oracle and Java Blog.

]]>
Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

Yesterday I attended the Battle of the Geeks. It was hosted by Finalist at the Netherlands Architecture Institute in Rotterdam. There were four presentations about different subjects. CMS Container, Google Guice, Gruby on Grails and Mule. A former colleague of mine (Peter Maas) was giving the presentation about Groovy and Grails. At the end of every presentation we had to rate the presentation (1-5 stars). The presentation with the best rating was rewarded with the battle of the geeks award, a plastic viking helmet and a paper with the name of the speaker on it.

CMS Container

The first presentation was about CMS container, an open source CMS based on MMBase. The demo’s looked cool but the presentation was a bit superficial. I wanted to hear more technical details (there were only geeks after all) to get a good view of the product.

Google Guice

The  second presentation was about Google Guice. I once wrote a blog about Guice and know something about the subject.  This presentation was given by Che Schneider, a developer at Finalist. He started his presentation with asking our opinion on drinking beer, when you use Google Guice there is more time to drink beer.
Guice is a dependency injection framework developed by Google. It doesn’t use configuration files and everything is configured by annotations. Che claimed that this saves a lot of time and that you don’t have to bother with large xml files any more. After that he showed us how to inject objects into other objects and how easy it was to switch to a unit test context. This presentation was very clear and I learned some knew things, but I still don’t¬† have a good reason to switch from Spring to Guice.

Gruby on Grails

Now it was Peter’s turn to score some points. Peter’s supporters screamed and applauded even before he started. The first thing Peter pointed out was that the term Gruby is very wrong, we have to use Groovy and were not allowed to compare Rails with Grails.
Groovy is a programming language that compiles to jvm byte code and is interchangeable with Java. Grails is a collection of very famous frameworks:¬† Spring, Hibernate, Lucene and some others. There also is a Groovy ORM framework (GORM) included in grails. The developer hasn’t got to know anything about the underlying frameworks, this is al hidden by Grails. The power of Grails is the ability to generate database tables and CRUD-web pages based on domain objects. When you develop a standard CRUD application it’s blazingly fast. Peter even showed us how to make changes to the generated pages (something that’s often left out of presentations to impress people) and that was fairly easy too.
This presentation definitely was the funniest one to watch and listen to, Peter was the only one who brought fans with him, that might have helped too.

Mule

The final presentation was about Mule, an open source ESB (Enterprise Service Bus). The speaker wasn’t well prepared and forgot to explain what an ESB was.¬† Despite of the bad preparation I got an idea what Mule was about (maybe because I attended an ESB-presentation at AMIS) Mule is pretty cool and it’s something we have to take serious. The discussion afterwards was more valuable than the presentation itself.

Conclusion

This battle was really worth spending two hours in rainy traffic jams. The main reason I attended was the presentation of Peter, but the Google Guice presentation alone was worth the traffic jam. The geek-factor wasn’t very high, the term geeks probably scared the other AMIS-employees to join this evening ūüėČ
Giving short presentations (30 minutes) is a good idea. It is short, but long enough to introduce one to a new subject.
I learned that Grails and Guice are both subjects to watch closely and that we will hear a lot more about them.

Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

The post Battle of the Geeks 2007 – An eyewitness report appeared first on AMIS Oracle and Java Blog.

]]>
https://technology.amis.nl/2007/09/26/battle-of-the-geeks-2007-an-eyewitness-report/feed/ 0
How to Unit-test private methods https://technology.amis.nl/2007/09/24/how-to-unit-test-private-methods/ https://technology.amis.nl/2007/09/24/how-to-unit-test-private-methods/#comments Mon, 24 Sep 2007 18:52:02 +0000 http://technology.amis.nl/blog/?p=2411 Share this on .. I know it’s kind of wrong to test private methods and there are a lot of articles and books that will explain you why. But sometimes you have an old code base where you have to unit-test some private methods to speed up development time. Today I got such a code [...]

The post How to Unit-test private methods appeared first on AMIS Oracle and Java Blog.

]]>
Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page


I know it’s kind of wrong to test private methods and there are a lot of articles and books that will explain you why. But sometimes you have an old code base where you have to unit-test some private methods to speed up development time. Today I got such a code base. It’s wasn’t that old, but I needed to change a private method that was called by some other methods. Those other methods had some parameters that needed to be set up depending on the user and the actions that user  took in the application.

....

This was way too much work for this simple method I had to change. I knew from a presentation at AMIS that is was possible to change the method accessor at runtime, but I just didn’t knew how. Time to go to our library. I checked some books and no results. On google I found some big articles (I listed the best one at the sources section, definitely a good thing to read when you want to know more about it)

But enough talking, let me show you what I did after some reading and debugging:

<code><br /><font color="#7f0055"><strong>public&nbsp;</strong></font><font color="#7f0055"><strong>void&nbsp;</strong></font><font color="#000000">testSecretIngredient</font><font color="#000000">()&nbsp;</font><font color="#7f0055"><strong>throws&nbsp;</strong></font><font color="#000000">Exception&nbsp;</font><font color="#000000">{</font><br /><font color="#ffffff">&nbsp;&nbsp;&nbsp; </font><font color="#000000">CoffeeMachine&nbsp;machine&nbsp;=&nbsp;</font><font color="#7f0055"><strong>new&nbsp;</strong></font><font color="#000000">CoffeeMachine</font><font color="#000000">()</font><font color="#000000">;</font><br /><br /><font color="#ffffff">&nbsp;&nbsp;&nbsp; </font><font color="#000000">Class&nbsp;machineClass&nbsp;=&nbsp;machine.getClass</font><font color="#000000">()</font><font color="#000000">;</font><br /><font color="#ffffff">&nbsp;&nbsp;&nbsp; </font><font color="#000000">Method&nbsp;method&nbsp;=&nbsp;machineClass.getDeclaredMethod</font><font color="#000000">(</font><font color="#2a00ff">&quot;getSecretIngredient&quot;</font><font color="#000000">)</font><font color="#000000">;</font><br /><font color="#ffffff">&nbsp;&nbsp;&nbsp; </font><font color="#000000">method.setAccessible</font><font color="#000000">(</font><font color="#7f0055"><strong>true</strong></font><font color="#000000">)</font><font color="#000000">;</font><br /><font color="#ffffff">&nbsp;&nbsp;&nbsp; </font><font color="#000000">Object&nbsp;result&nbsp;=&nbsp;method.invoke</font><font color="#000000">(</font><font color="#000000">machine</font><font color="#000000">)</font><font color="#000000">;</font><br /><font color="#ffffff">&nbsp;&nbsp;&nbsp; </font><br /><font color="#ffffff">&nbsp;&nbsp;&nbsp; </font><font color="#000000">System.out.println</font><font color="#000000">(</font><font color="#000000">result.getClass</font><font color="#000000">())</font><font color="#000000">;</font><br /><font color="#000000">}</font></code> <br />

First I created a CoffeeMachine object and invoked the getClass() method on it. When you analyze this object in the debugger you get lots of interesting information:

In the declaredMethods field you can see there are two methods. The getSecretIngredient() and getCoffee() method. The getCoffee methods is testable, but we’re interested in the secret ingredient!
Create a Method object to get the method (it took me some time to grasp that a Method is an Object)
Now the magic method I was looking for: setAccessible. This method makes the getSecretIngredient public so we can invoke it.
Because the compiler doesn’t allow us to do a machine.getSecretIngredient(); (which is now technically possible) we have to invoke the method via the invoke method. You have to pass the object on which you want to invoke the method and you’re ready to go.

Unfortunately I’m now allow to tell you what secret ingredient the AMIS Coffee Machine uses so you have to believe me that the unit test returns the right Object.

Testing with parameters

It’s also possible to pass parameters to the methods. Assume we have a Long and Integer parameter on our getSecretIngredient method.

The getDeclaredMethod method then looks like this:

<code><br /><font color="#000000">Method&nbsp;method=machineClass.getDeclaredMethod</font><font color="#000000">(</font><font color="#2a00ff">&quot;getSecretIngredient&quot;</font><font color="#000000">,&nbsp;</font><font color="#7f0055"><strong>new&nbsp;</strong></font><font color="#000000">Class</font><font color="#000000">[]{</font><font color="#000000">Long.class,&nbsp;Integer.</font><font color="#7f0055"><strong>class</strong></font><font color="#000000">})</font><font color="#000000">;</font></code>

and the invoke:

<code><br /><font color="#000000">Object&nbsp;result=method.invoke</font><font color="#000000">(</font><font color="#000000">machine,&nbsp;</font><font color="#990000">10L</font><font color="#000000">,&nbsp;</font><font color="#990000">20</font><font color="#000000">)</font><font color="#000000">;</font></code>

Conclusion

Fortunately the Reflection API is very slow, maybe Sun did this on purpose. Think of the evil things you can do with this API. You can screw up refactorings and access methods that were hidden on purpose. So promise me you won’t tell this to junior developers, they will use this API in production code and break all the encapsulation you introduced to protect themselves.

When you want to know more about testing private methods I recommend this article.

Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

The post How to Unit-test private methods appeared first on AMIS Oracle and Java Blog.

]]>
https://technology.amis.nl/2007/09/24/how-to-unit-test-private-methods/feed/ 2
Minify all your JavaScript and Stylsheets automatically with YUI Compressor and a Servlet Filter https://technology.amis.nl/2007/09/09/minify-all-your-javascript-and-stylsheets-automatically-with-yui-compressor-and-a-servlet-filter/ https://technology.amis.nl/2007/09/09/minify-all-your-javascript-and-stylsheets-automatically-with-yui-compressor-and-a-servlet-filter/#comments Sun, 09 Sep 2007 09:08:49 +0000 http://technology.amis.nl/blog/?p=2392 Share this on .. In this article I will explain how to minify all your .js and .css files automatically with a servlet filter. This means you only have to define a servlet filter in your web.xml and everything works! In the project I’m currently working on we have some pretty large JavaScripts and CSS [...]

The post Minify all your JavaScript and Stylsheets automatically with YUI Compressor and a Servlet Filter appeared first on AMIS Oracle and Java Blog.

]]>
Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

In this article I will explain how to minify all your .js and .css files automatically with a servlet filter. This means you only have to define a servlet filter in your web.xml and everything works!

In the project I’m currently working on we have some pretty large JavaScripts and CSS files. Those files also contain comments that the users don’t need to use the application. So I wanted to be able to remove unnecessary whitespace, line breaks and comments. When I read an article on Ajaxian about the YUI Compressor library I got curious. I assumed the library was written in C or another language that doesn’t start with J and ends with ava. But I got lucky, it was a Java library!

....

I hate to do thing manually or create setup files, so I came up with a solution: a Servlet Filter for .css and .js files. That idea sounds so simple that there has to be someone who already did that. I searched for a while and the only thing I found was someone who said he was going to make it and it seems he wants to see some money for it! Well that’s not so cool. YUI Compressor is free and when you make a simple thing like a servlet filter you should donate it to the community. I’m sure someone already created a servlet filter, but that person should’ve posted the article on DZone or javablogs so other people know it exists.

But enough talking let me show you what I did. I won’t describe every little detail, I only want to give you an idea what I did. I will provide the source code so you can see what’s done exactly and if you have any questions about that I will answer them (in the comments of this article).

Servlet Filter

The first step is setting up the servlet filter and find out what the input and output of the filter is. A Servlet Filter is nothing more than a class that implements the javax.servlet.Filter interface.
A servlet filter consists of three methods:

public void init(FilterConfig filterConfig)<br />public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)<br />public void destroy()<br />

The init method is the place where you can read input parameters and setup the filter. This method acts as a setter for a private filterConfig field and reads the filter init parameters. The filter init parameters are the same parameters you can pass to the YUI Compressor library. I choose not to use all the parameters, just a subset with the most important ones.

The doFilter() method checks whether the compressed file already is in our cache and writes it to the ServletOutputStream. The input for the YUI Compressor is a java.io.Reader object. We can get a Reader object with the following code:

String requestURI = request.getRequestURI();<br />InputStream inputStream = context.getResourceAsStream(requestURI);<br />InputStreamReader isr = new InputStreamReader(inputStream);

The isr object can be passed to the compressor. The compressor writes the output to the cache (with a StringWriter object). When a file is found in the cache it’s written to the ServletOutputStream:

ServletOutputStream servletOutputStream = response.getOutputStream();

The servletOutputStream is a parameter of the Compressor.

The destroy() method is empty, because we have no sepcial things that need to be cleaned up (like open files or connections to external resources).

YUI Compressor

The second step was understanding the YUI Compressor.  I used the 2.1.2 version, but everything I’m about to tell should work with older and newer versions. In the download on the page the source code is included. The YUI Compressor class is the class we will use as a reference for the Filter, it contains all the important information we need.
The primary goal is compressing some input. The input the YUIC needs is a java.io.Reader object and an ErrorReporter object.

JavaScriptCompressor compressor = new JavaScriptCompressor(in, new ErrorReporter() { ... });<br />

The ErrorReporter object is something I created myself. My class is called CompressorFilterErrorReporter and it implements the ErrorReporter interface. I will skip this class, it’s quite straightforward what needs to be done and you can look it up in the source code. You only need to know that it prints some error messages.
The last step of the compressor is invoking the compress method. You have to pass the command line parameters and the Write you want to write to. Because we make use of a cache we write to a String with a StringWriter.

The CSS compressor works basically the same as the JavaScriptCompressor, but needs fewer parameters.

Caching

It turned out the compressor was pretty slow (on my laptop it almost took 1 second to compress the jQuery library). Of course it’s a bit useless to compress a script everytime a request is made so had to introduce caching anyway. I use a Hashtable (yes, with a lower case t)  to cache the scripts, the cache won’t expire, there’s no round robin etc. You usally won’t have hundreds of scripts and stylesheets in the cache so a normal Hashtable will be enough.
Instead of writing directly to the ServletOutputStream I now write to a String and put this String with the Request URI in the Hashtable. It’s a simple caching mechanism, but it works pretty good.
The first time the scripts are compressed it might take a little longer to load the page but every new request is pretty fast (maybe even faster than a normal request because this one doesn’t need to be read from disk)

Configuration
You have to put the filter in your web.xml. The simplest configuration looks like this:

&lt;filter&gt;<br />&nbsp;&nbsp;&nbsp; &lt;display-name&gt;Yahoo Compressor Filter&lt;/display-name&gt;<br />&nbsp;&nbsp;&nbsp; &lt;filter-name&gt;CompressorFilter&lt;/filter-name&gt;<br />&nbsp;&nbsp;&nbsp; &lt;filter-class&gt;nl.amis.filter.CompressorFilter&lt;/filter-class&gt;<br />&lt;/filter&gt;<br /><br />&lt;filter-mapping&gt;<br />&nbsp;&nbsp;&nbsp; &lt;filter-name&gt;CompressorFilter&lt;/filter-name&gt;<br />&nbsp;&nbsp;&nbsp; &lt;url-pattern&gt;*.js&lt;/url-pattern&gt;<br />&nbsp;&nbsp;&nbsp; &lt;dispatcher&gt;REQUEST&lt;/dispatcher&gt;<br />&lt;/filter-mapping&gt;<br /><br />&lt;filter-mapping&gt;<br />&nbsp;&nbsp;&nbsp; &lt;filter-name&gt;CompressorFilter&lt;/filter-name&gt;<br />&nbsp;&nbsp;&nbsp; &lt;url-pattern&gt;*.css&lt;/url-pattern&gt;<br />&nbsp;&nbsp;&nbsp; &lt;dispatcher&gt;REQUEST&lt;/dispatcher&gt;<br />&lt;/filter-mapping&gt;

I decided to work with the default values of YUI Compressor. You only need parameters when you don’t want to use the defaults. When you want to use the parameters you have to put them between </filter-class> and </filter>

&nbsp;&nbsp;&nbsp; &lt;init-param&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;param-name&gt;preserve-semi&lt;/param-name&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;param-value&gt;true&lt;/param-value&gt;<br />&nbsp;&nbsp;&nbsp; &lt;/init-param&gt;

Is used to preserve all the semi colons. Other parameters you can use are line-break, warn and nomunge. Consult the YUI Compressor to see what these parameters do.

Conclusion and download

Click here to download the files. You have to download the YUI Compressor yourself. I also make use of Log4J. When you don’t want to use Log4j you just have to replace it with your own logging library or System.out. There are only 5 logging statements, so it shouldn’t be too much work.
Many thanks to the guy(s) tha
t created the YUI Compressor, i
t’s easy to use and does a great job.
You’re free to use the source code in your application, just don’t remove my name from the Javadoc ūüėČ
I’d really appreciate some feedback on this piece of code, it probably can be improved.

Sources

http://www.julienlecomte.net/blog/2007/08/13/introducing-the-yui-compressor/
http://www.julienlecomte.net/yuicompressor/

Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

The post Minify all your JavaScript and Stylsheets automatically with YUI Compressor and a Servlet Filter appeared first on AMIS Oracle and Java Blog.

]]>
https://technology.amis.nl/2007/09/09/minify-all-your-javascript-and-stylsheets-automatically-with-yui-compressor-and-a-servlet-filter/feed/ 9
A quick introduction to the jQuery tablesorter plugin https://technology.amis.nl/2007/08/24/a-quick-introduction-to-the-jquery-tablesorter-plugin/ https://technology.amis.nl/2007/08/24/a-quick-introduction-to-the-jquery-tablesorter-plugin/#comments Fri, 24 Aug 2007 12:07:56 +0000 http://technology.amis.nl/blog/?p=2376 Share this on .. A few days ago version 2.0 of the tablesorter plugin was released. Before 2.0 the tablesorter worked fine but I never did anything with it. Today I thought it was time to see whether this was a good solution for the table sorting we need. In this article I will show [...]

The post A quick introduction to the jQuery tablesorter plugin appeared first on AMIS Oracle and Java Blog.

]]>
Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

A few days ago version 2.0 of the tablesorter plugin was released. Before 2.0 the tablesorter worked fine but I never did anything with it. Today I thought it was time to see whether this was a good solution for the table sorting we need. In this article I will show you how to enable sorting on any table (yes it’s that simple) and how to create custom sort functions.

....

In our last project we used (and still using) Dojo. Dojo is a great framework but I’m starting to like jQuery more and more. A great advantage of jQuery is the great documentation and the plugin section on their website. This section contains all the plugins that are useful and matured (no pre-alpha versions with loads of bugs for example). A few days ago I read about the tablesorter plugin and decided to give it a shot, it eventually solved an old Javascript problem I had!

Let’s take a look at this simple table:

&lt;table id=&quot;myTable&quot;&gt;<br />&nbsp;&nbsp;&nbsp; &lt;thead&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;tr&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;th&gt;City&lt;/th&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;th&gt;Distance (km)&lt;/th&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/tr&gt;<br />&nbsp;&nbsp;&nbsp; &lt;/thead&gt;<br />&nbsp;&nbsp;&nbsp; &lt;tbody&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;tr&gt;&lt;td&gt;Amsterdam&lt;/td&gt;&lt;td&gt;0&lt;/td&gt;&lt;/tr&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;tr&gt;&lt;td&gt;Utrecht&lt;/td&gt;&lt;td&gt;1&lt;/td&gt;&lt;/tr&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;tr&gt;&lt;td&gt;Eindhoven&lt;/td&gt;&lt;td&gt;100&lt;/td&gt;&lt;/tr&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;tr&gt;&lt;td&gt;Rotterdam&lt;/td&gt;&lt;td&gt;11&lt;/td&gt;&lt;/tr&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;tr&gt;&lt;td&gt;Enschede&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;tr&gt;&lt;td&gt;Den Haag&lt;/td&gt;&lt;td&gt;2&lt;/td&gt;&lt;/tr&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;tr&gt;&lt;td&gt;Groningen&lt;/td&gt;&lt;td&gt;-1&lt;/td&gt;&lt;/tr&gt;<br />&nbsp;&nbsp;&nbsp; &lt;/tbody&gt;<br />&lt;/table&gt;<br /> <br />

This is just a normal table, nothing special about it. It contains a column with Dutch cities and a column with distances. Those distances don’t mean anything, they’re just there to prove something. What that something is I’ll explain later (readers of my previous blog entry probably know what I’m talking about).

When we look at this table we see an ugly table. Let’s include the stylesheet for the tablesorter and put the tablesorter class on the table tag and refresh the browser:

That already looks much better. To add sorting we have to include jQuery and the tablesorter plugin:

&lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery-1.1.3.1.pack.js&quot;&gt;&lt;/script&gt;<br />&lt;script type=&quot;text/javascript&quot; src=&quot;js/jquery.tablesorter.pack.js&quot;&gt;&lt;/script&gt;<br />&lt;script type=&quot;text/javascript&quot;&gt;<br />&nbsp;&nbsp;&nbsp; $(document).ready(function()<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $(&quot;#myTable&quot;).tablesorter();<br />&nbsp;&nbsp;&nbsp; });<br />&lt;/script&gt;

The ready function adds the tablesorter to the table with id myTable when the DOM-tree is finished loading.

Now refresh the browser and the sorting works!

The next step is to make sure the distance field gets sorted correctly. You can add sorter types when you add the tablesorter in javascript:

$(&quot;#myTable&quot;).tablesorter({ headers: { <br />&nbsp;&nbsp;&nbsp;&nbsp; 1: { sorter:'text' } <br />&nbsp;&nbsp; } });

This means the second column (counting starts at 0) is treated as a text column.
It’s also possible to add the sorter on the class attribute :
Use <th class="{sorter: ‘text’}">Distance (km)</th>
But I personally prefer to use the class only for css styling.

Other choices for the sorter are procent, text, currency, integer and number. Let’s take number and you’ll notice the empty cell behaves very unpredictable.

The problem and partial solution is described in this. For tablesorter we can define a custom parser, this is a kind of interface you have to implement which invokes the sort function on the background. I really like this construction, so nice and clean.

The example describes what you have to do and my ‘implementation’ looks like this:

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $.tablesorter.addParser({<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // set a unique id<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; id: 'nullInt',<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; is: function(s) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // return false so this parser is not auto detected<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return false;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; },<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; format: function(s) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // format your data for normalization<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (!s) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return -0.000000001;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } else {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return s;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; },<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // set type, either numeric or text<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; type: 'numeric'<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; });

The addParser function is invoked with some parameters. For now we only need the id and format function which replaces null vales with -0.000000001. The format function ‘normalizes’ the data for you and sorts that
normalized data (with leaving the original values untouched, of course).

Now the nullInt (the id of the parser) can be chosen as a parameter for the sorter.

Well, that also works pretty good and is much cleaner than implementing your own sort function.

Conclusion

I really love the tablesorter plugin. It’s very easy to use and the code looks so clean! Every sortable table I create from now on will use the tablesorter plugin. The Dojo widget also works fine, but I like clean and simple structure of jQuery.

I didn’t tell you about the multi-column sort (with the shift key) and pagination (see screenshot). But you can all find out how to do that on the tablesorter site This site also has some great code examples.

Source

http://tablesorter.com/

Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

The post A quick introduction to the jQuery tablesorter plugin appeared first on AMIS Oracle and Java Blog.

]]>
https://technology.amis.nl/2007/08/24/a-quick-introduction-to-the-jquery-tablesorter-plugin/feed/ 7
How to fix your number-sorting problems in Javascript https://technology.amis.nl/2007/08/24/how-to-fix-your-number-sorting-problems-in-javascript/ https://technology.amis.nl/2007/08/24/how-to-fix-your-number-sorting-problems-in-javascript/#comments Fri, 24 Aug 2007 11:56:03 +0000 http://technology.amis.nl/blog/?p=2373 Share this on .. Did you ever wanted to sort [1, 10, null, 20] in Javascript and were the results unpredictable? It’s not a bug, but more something that’s not implemented. I came across this problem when testing some table sorting plugins for Dojo and jQuery. First I thought it were bugs, but the real [...]

The post How to fix your number-sorting problems in Javascript appeared first on AMIS Oracle and Java Blog.

]]>
Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

Did you ever wanted to sort [1, 10, null, 20] in Javascript and were the results unpredictable? It’s not a bug, but more something that’s not implemented. I came across this problem when testing some table sorting plugins for Dojo and jQuery. First I thought it were bugs, but the real problem lies in Javascript and the function you pass to the sort() method.

....

I’m using the Dojo filteringTable widget when I want to sort tables. It works fine but I had a problem with sorting a collection of numbers which contain null/empy values. The cells with null values appeared in the most strange places after sorting a column. First I thought it was a bug in Dojo (I’m sorry Dojo guys, but I had to blame someone ūüėČ ) and I did some investigation and got a bit stuck. A few months later I found out what my problem was (note that I did some other things in this period other than solving this problem)

To sort arrays in Javascript you use the sort method on an array.

var a = [0,null,10,11,null,20,100,null,-10,-1,111,2, null, 5];<br />a.sort();<br />console.log(a); 

The result:

[-1, -10, 0, 10, 100, 11, 111, 2, 20, 5, null, null, null, null]<br /><br /><br />

Well that looks fine. I prefer to have null values just before the 0, but that’s just because of the data I’m currently working with.
To do more advanced sorting you can add a sort function as a parameter

function numberAsc(a, b) {<br />&nbsp;&nbsp;&nbsp;&nbsp; return a - b;<br />}<br /><br />var a = [0,null,10,11,null,20,100,null,-10,-1,111,2, null, 5];<br /><br />a.sort(numberAsc);<br />console.log(&quot;asc: &quot;, a);

The result could be

asc: [-10, -1, null, null, null, 0, null, 2, 5, 10, 11, 20, 100, 111]

I said could because it’s quite fuzzy what happens. Let’s add a descending number function to illustrate this:

function numberAsc(a, b) {<br />&nbsp;&nbsp;&nbsp; return a - b;<br />}<br /><br />function numberDesc(a, b) {<br />&nbsp;&nbsp;&nbsp; return b - a;<br />}<br /><br />var a = [0,null,10,11,null,20,100,null,-10,-1,111,2, null, 5];<br /><br />a.sort(numberAsc);<br />console.log(&quot;asc: &quot;, a);<br />a.sort(numberDesc)<br />console.log(&quot;desc: &quot;, a);<br />a.sort(numberAsc);<br />console.log(&quot;asc: &quot;, a);<br />a.sort(numberDesc)<br />console.log(&quot;desc: &quot;, a);<br /><br />

The result:

asc: [-10, -1, null, null, null, 0, null, 2, 5, 10, 11, 20, 100, 111]<br />desc: [111, 100, 20, 11, 10, 5, 2, 0, null, null, null, null, -1, -10]<br />asc: [-10, -1, null, null, null, null, 0, 2, 5, 10, 11, 20, 100, 111]<br />desc: [111, 100, 20, 11, 10, 5, 2, null, null, null, 0, null, -1, -10]

Wow! The second and third result look fine, but the first and last don’t. And because everything should look the same this is bad!

What you have to do to solve this problem is assigning a number to the null value in the sort function. I want null to appear just before 0, so I pick -0.00000001 (assuming there are no numbers with this many digits in the fraction part of a number)

The new function:

var ALMOST_ZERO = -0.00000001;<br /><br />function numberAsc(a, b) {<br />&nbsp;&nbsp;&nbsp; var left = a != null ? a : ALMOST_ZERO;<br />&nbsp;&nbsp;&nbsp; var right = b != null ? b : ALMOST_ZERO;<br /><br />&nbsp;&nbsp;&nbsp; return left - right;<br />}<br /><br />

The terniary operator might be a bit confusing at first, but saves a lot of space. The lines with left en right assign -0.00000001 to the left or the right when any of these values is null.

When we run the script again the results look good:

asc: [-10, -1, null, null, null, null, 0, 2, 5, 10, 11, 20, 100, 111]<br />desc: [111, 100, 20, 11, 10, 5, 2, 0, null, null, null, null, -1, -10]<br />asc: [-10, -1, null, null, null, null, 0, 2, 5, 10, 11, 20, 100, 111]<br />desc: [111, 100, 20, 11, 10, 5, 2, 0, null, null, null, null, -1, -10]

When you want null to appear on front you need a very low value (ie. -999999999) and when null should appear on the end you take a very large number (ie.  999999999)

I’m quite happy I finally solved this problem. I started working on this issue again because I tried the new jQuery tablesorter plugin. In this article you can read more about it and how to apply the solution of this article to a beautiful table.

Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

The post How to fix your number-sorting problems in Javascript appeared first on AMIS Oracle and Java Blog.

]]>
https://technology.amis.nl/2007/08/24/how-to-fix-your-number-sorting-problems-in-javascript/feed/ 0
Getting started with JPA mapping : How IntelliJ can map your data with a few clicks https://technology.amis.nl/2007/08/01/getting-started-with-jpa-mapping-how-intellij-can-map-your-data-with-a-few-clicks/ https://technology.amis.nl/2007/08/01/getting-started-with-jpa-mapping-how-intellij-can-map-your-data-with-a-few-clicks/#comments Wed, 01 Aug 2007 10:30:35 +0000 http://technology.amis.nl/blog/?p=2361 Share this on .. With JPA, there finally is an ORM standard and every major IDE has support for it. Today I will show you how to map your data with IntelliJ IDEA. I also use the brand new TopLink 11g preview (a JPA implementation), but you can try this at home with every JPA-implementation. [...]

The post Getting started with JPA mapping : How IntelliJ can map your data with a few clicks appeared first on AMIS Oracle and Java Blog.

]]>
Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

With JPA, there finally is an ORM standard and every major IDE has support for it. Today I will show you how to map your data with IntelliJ IDEA. I also use the brand new TopLink 11g preview (a JPA implementation), but you can try this at home with every JPA-implementation.

A few weeks ago Peter showed some AMIS employees (including me) the TopLink workbench. I really was amazed how good is was. And I felt a bit bad that I didn√Ę‚ā¨‚ĄĘt knew that such a tool existed. I wanted to use the tool myself. I fiddled around with it and really love it. But I wanted to get JPA-annotations, not the TopLink XML files. Whilst searching on how to do that I discovered that every major IDE supported JPA annotation generation. Last year I mainly used iBatis and Spring-JDBC and kind of forgot about JPA, so the √Ę‚ā¨ňúamazing new things√Ę‚ā¨‚ĄĘ I√Ę‚ā¨‚ĄĘm about to tell might be pretty ancient by now ūüėČ

Creating the mapping and data sources

Create a project in IntelliJ and add libraries for JUnit, Oracle JDBC (OJDBC14.jar) and the libraries for your JPA-implementation. I√Ę‚ā¨‚ĄĘm using¬† TopLink 11g preview so I have to add persistence.jar, toplink.jar and xmlparserv2.jar

To validate your persistence classes and queries properly you have to add a data source. Go to Tools, Data Sources. Click on the plus icon in the upper left corner of the dialog.

Click on the plus icon and search for your JDBC-driver. It√Ę‚ā¨‚ĄĘs usually sufficient to hit the √Ę‚ā¨ňúFind Driver Classes√Ę‚ā¨‚ĄĘ button, but sometimes you have to look up the driver yourself.
The next step is the database url, user name, password and schema name. You can click the test connection to test the connection and with the refresh tables button you can test some more.

Right click your project, new, add persistence unit. My persistence unit is called Scott. IntelliJ generates the XML for you. You have to add some properties to make sure the application works outside IntelliJ. Overwrite the <persistence-unit> with

<code>
<span style="color: #000000;">&lt;persistence-unit name=</span><span style="color: #2a00ff;">"scott"</span><span style="color: #000000;">&gt;</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">&lt;properties&gt;</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">&lt;property name=</span><span style="color: #2a00ff;">"toplink.jdbc.driver" </span><span style="color: #000000;">value=</span><span style="color: #2a00ff;">"oracle.jdbc.OracleDriver"</span><span style="color: #000000;">/&gt;</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">&lt;property name=</span><span style="color: #2a00ff;">"toplink.jdbc.url" </span><span style="color: #000000;">value=</span><span style="color: #2a00ff;">"jdbc:oracle:thin:@127.0.0.1:1521:orcl"</span><span style="color: #000000;">/&gt;</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">&lt;property name=</span><span style="color: #2a00ff;">"toplink.jdbc.user" </span><span style="color: #000000;">value=</span><span style="color: #2a00ff;">"scott"</span><span style="color: #000000;">/&gt;</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">&lt;property name=</span><span style="color: #2a00ff;">"toplink.jdbc.password" </span><span style="color: #000000;">value=</span><span style="color: #2a00ff;">"tiger"</span><span style="color: #000000;">/&gt;</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">&lt;property name=</span><span style="color: #2a00ff;">"com.intellij.javaee.persistence.datasource" </span><span style="color: #000000;">value=</span><span style="color: #2a00ff;">"Scott"</span><span style="color: #000000;">/&gt;</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">&lt;/properties&gt;</span>
<span style="color: #000000;">&lt;/persistence-unit&gt;</span></code>

Note that the last property is needed for proper validation of the persistence classes and queries, otherwise you wil  see red underlinings everywhere. You can remove the line when you deploy your project to a web server.

To create the mappings you just have to do some clicking. Right click your project, Generate persistence mapping and pick by database schema.
In the dialog that pops up you have to add some things:

  • choose Datasource: Scott
  • package: nl.amis.domain.scott
  • tick add to persistence unit and pick scott
  • deselect Bonus and Salgrade because we only want the Emp and Dept table.

Note that the deptno field of emp is deselected. This is because it√Ę‚ā¨‚ĄĘs a foreign key (hence the fk on the table icon) and JPA knows you probably don√Ę‚ā¨‚ĄĘt want to use that foreign key. And JPA is right, we want a department object in our employee object.
Select the Emp table and click on the plus icon to add a relation.

In the Employee object we want to select a Department, so add an attribute department and leave type on <entity>. In the department section we want to be able to select a list of employees. Change the Type to java.util.List and enter the attribute name employees.
When you√Ę‚ā¨‚ĄĘre using an ancient database without relations you can enter a source an target column, but that isn√Ę‚ā¨‚ĄĘt necessary becasue JPA is pretty smart.

Select src directory when you can choose between the resources and src directory.

Go to the package nl.amis.domain.scott and look what IntelliJ did for you. Of course there are a lot of annotations that aren√Ę‚ā¨‚ĄĘt really necessary, but they won√Ę‚ā¨‚ĄĘt hurt performance and now it√Ę‚ā¨‚ĄĘs more clear what is actually happening.

In the DeptEntity class you can see there is a one to many relation to employee:

<code>
<span style="color: #ffffff;">    </span><span style="color: #646464;">@OneToMany</span><span style="color: #000000;">(</span><span style="color: #000000;">mappedBy = </span><span style="color: #2a00ff;">"department"</span><span style="color: #000000;">)</span>
<span style="color: #ffffff;">    </span><span style="color: #7f0055;"><strong>public </strong></span><span style="color: #000000;">List&lt;EmpEntity&gt; getEmployees</span><span style="color: #000000;">() {</span>
<span style="color: #ffffff;">        </span><span style="color: #7f0055;"><strong>return </strong></span><span style="color: #000000;">employees;</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">}</span></code>

The final step is adding the used classes to persistence.xml (copy these tags just above <properties>)

<code>
<span style="color: #ffffff;">    </span><span style="color: #000000;">&lt;</span><span style="color: #7f0055;"><strong>class</strong></span><span style="color: #000000;">&gt;nl.amis.domain.scott.EmpEntity&lt;/</span><span style="color: #7f0055;"><strong>class</strong></span><span style="color: #000000;">&gt;</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">&lt;</span><span style="color: #7f0055;"><strong>class</strong></span><span style="color: #000000;">&gt;nl.amis.domain.scott.DeptEntity&lt;/</span><span style="color: #7f0055;"><strong>class</strong></span><span style="color: #000000;">&gt;</span></code>

Querying your data

Now it√Ę‚ā¨‚ĄĘs finally time to query the data. Let√Ę‚ā¨‚ĄĘs have a look at this simple test case

<code>
<span style="color: #7f0055;"><strong>public
 class
 </strong></span><span style="color: #000000;">TestTopLinkJPA </span><span style="color: #7f0055;"><strong>extends </strong></span><span style="color: #000000;">TestCase </span><span style="color: #000000;">{</span>
<span style="color: #ffffff;">    </span><span style="color: #7f0055;"><strong>private static final </strong></span><span style="color: #000000;">Logger log = Logger.getLogger</span><span style="color: #000000;">(</span><span style="color: #000000;">TestTopLinkJPA.</span><span style="color: #7f0055;"><strong>class</strong></span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">    </span><span style="color: #7f0055;"><strong>private </strong></span><span style="color: #000000;">EntityManagerFactory emf = </span><span style="color: #7f0055;"><strong>null</strong></span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">    </span><span style="color: #7f0055;"><strong>private </strong></span><span style="color: #000000;">String s;</span>

<span style="color: #ffffff;">    </span><span style="color: #7f0055;"><strong>protected </strong></span><span style="color: #7f0055;"><strong>void </strong></span><span style="color: #000000;">setUp</span><span style="color: #000000;">() {</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">emf = Persistence.createEntityManagerFactory</span><span style="color: #000000;">(</span><span style="color: #2a00ff;">"scott"</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">log.debug</span><span style="color: #000000;">(</span><span style="color: #2a00ff;">"EntityManagerFactory created"</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">}</span>

<span style="color: #ffffff;">    </span><span style="color: #7f0055;"><strong>protected </strong></span><span style="color: #7f0055;"><strong>void </strong></span><span style="color: #000000;">tearDown</span><span style="color: #000000;">() </span><span style="color: #7f0055;"><strong>throws </strong></span><span style="color: #000000;">Exception </span><span style="color: #000000;">{</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">emf.close</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">log.debug</span><span style="color: #000000;">(</span><span style="color: #2a00ff;">"EntityManagerFactory closed"</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">}</span>

<span style="color: #ffffff;">    </span><span style="color: #7f0055;"><strong>public </strong></span><span style="color: #7f0055;"><strong>void </strong></span><span style="color: #000000;">testScott</span><span style="color: #000000;">() </span><span style="color: #7f0055;"><strong>throws </strong></span><span style="color: #000000;">Exception </span><span style="color: #000000;">{</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">EntityManager em =  emf.createEntityManager</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">Query query = em.createQuery</span><span style="color: #000000;">(</span><span style="color: #2a00ff;">"select e from EmpEntity e"</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">List&lt;EmpEntity&gt; list = query.getResultList</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>

<span style="color: #ffffff;">        </span><span style="color: #7f0055;"><strong>for </strong></span><span style="color: #000000;">(</span><span style="color: #7f0055;"><strong>int </strong></span><span style="color: #000000;">i = </span><span style="color: #990000;">0</span><span style="color: #000000;">; i &lt; list.size</span><span style="color: #000000;">()</span><span style="color: #000000;">; i++</span><span style="color: #000000;">) {</span>
<span style="color: #ffffff;">            </span><span style="color: #000000;">EmpEntity e = list.get</span><span style="color: #000000;">(</span><span style="color: #000000;">i</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">            </span><span style="color: #000000;">System.out.println</span><span style="color: #000000;">(</span><span style="color: #000000;">e.getEname</span><span style="color: #000000;">() </span><span style="color: #000000;">+ </span><span style="color: #2a00ff;">", dept location: " </span><span style="color: #000000;">+ e.getDepartment</span><span style="color: #000000;">()</span><span style="color: #000000;">.getLoc</span><span style="color: #000000;">())</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">}</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">}</span>
<span style="color: #000000;">}</span></code>

The coolest thing about IntelliJ is that √Ę‚ā¨ňúthey√Ę‚ā¨‚ĄĘ validate your queries! Lets add √Ę‚ā¨ňúwhere e.√Ę‚ā¨‚ĄĘ and hit ctrl-space

How cool is that!? Let√Ę‚ā¨‚ĄĘs change EmpEntity to EmpEntaty:

This will make your work so much easier, no more stupid typo√Ę‚ā¨‚ĄĘs or hours of searching because you always write Entaty and don√Ę‚ā¨‚ĄĘt know what√Ę‚ā¨‚ĄĘs wrong with that.

Conclusion

After a few hours with JPA I really love it. I√Ę‚ā¨‚ĄĘm always a bit conservative and stuck to iBatis and Spring-JDBC for too long. Not that there√Ę‚ā¨‚ĄĘs anything wrong with those two, but JPA can make you job easier (and of course it always good to check out other tools). The four major IDE√Ę‚ā¨‚ĄĘs (Eclipse, IntelliJ, NetBeans and JDeveloper) are really competing with each other and we as users get betters tools because of that competition. A few years ago it would√Ę‚ā¨‚ĄĘve taken ages to get some proper tooling for new frameworks and now I√Ę‚ā¨‚ĄĘm suprised good tools are already out there.

Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

The post Getting started with JPA mapping : How IntelliJ can map your data with a few clicks appeared first on AMIS Oracle and Java Blog.

]]>
https://technology.amis.nl/2007/08/01/getting-started-with-jpa-mapping-how-intellij-can-map-your-data-with-a-few-clicks/feed/ 3
Do you really know how for-loops work? How to speed up your for loops https://technology.amis.nl/2007/07/15/do-you-really-know-how-for-loops-work-how-to-speed-up-your-for-loops/ https://technology.amis.nl/2007/07/15/do-you-really-know-how-for-loops-work-how-to-speed-up-your-for-loops/#comments Sun, 15 Jul 2007 10:23:26 +0000 http://technology.amis.nl/blog/?p=2308 Share this on .. Did you know that the second parameter of a three parameter for loop gets executed on every loop? When this parameter is an expensive operation this could slow down your application. Of course I knew the second parameter gets executed every time, but I didn√Ę‚ā¨‚ĄĘt realize what kind of impact this [...]

The post Do you really know how for-loops work? How to speed up your for loops appeared first on AMIS Oracle and Java Blog.

]]>
Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

Did you know that the second parameter of a three parameter for loop gets executed on every loop? When this parameter is an expensive operation this could slow down your application. Of course I knew the second parameter gets executed every time, but I didn√Ę‚ā¨‚ĄĘt realize what kind of impact this had until I read an article and ran some tests. This √Ę‚ā¨ňútheory√Ę‚ā¨‚ĄĘ applies to every programming language with for-loops so it may be useful to every programmer/scripter.
When I ran some tests on Javsascript I discovered some for loops could be a 100 times faster!
....

Probably every programmer knows the second parameter is executed on every loop. But I think a lot of developers don√Ę‚ā¨‚ĄĘt realize the impact of this. I recently read an article about improving Javascript that opened my eyes. The tip in the article had something to do with assigning function pointers to local variables when you use them a lot, with a for-loop as an example.
Let me demonstrate what happens with a simple java example. I know everybody knows the outcoume, but you can√Ę‚ā¨‚ĄĘt see it enough.

public void testLoop() {<br />    for (int i = 0; i &lt; getLength(); i++) {<br />        // do nothing<br />    }<br />}<br /><br />private int getLength() {<br />    System.out.println(&quot;Are we there yet?&quot;);<br />    return 10;<br />} <br />

√Ę‚ā¨ŇďAre we there yet?√Ę‚ā¨¬Ě is printed 10 times. In this case (and most cases for for-loops) we only need to execute the getLength() method 1 time because we know it√Ę‚ā¨‚ĄĘs value stays the same. When the getLength() method was a very expensive operation it was executed 9 times too much (with a cheap operation too, but you wouldn√Ę‚ā¨‚ĄĘt have noticed)

I ran some test on Javascript and that really scared me. I created a table with 72 cells and looped through every cell with:

document.getElementById('t').getElementsByTagName('td')

Stupid as I am my for loop looks like this:

for (var i = 0; i &lt; document.getElementById('t').getElementsByTagName('td').length; i++) {<br />     }<br />

And it should like this:

var l = document.getElementById('t').getElementsByTagName('td').length;<br />for (var i = 0; i &lt; l; i++) {<br />}<br />

So let√Ę‚ā¨‚ĄĘs cut to the case. These two snippets produce exactly the same result, the second example though runs about a 160 times faster in my FireFox and about 100 times faster in Internet Explorer. Wow! And this doesn√Ę‚ā¨‚ĄĘt look like an expensive operation in my opinion. Note that I ran the test several times and the for-loops were nested inside another for loop (the first set ran 5000 times and the second set 50000 to get a good idea of how long it took)

In java I created an ArrayList with about 40 Strings in it and did the same for-loop test. The list.size(); test was about 6 times slower than assinging a local variable.

Don√Ę‚ā¨‚ĄĘt think you can speed up every for loop 6 times (or 100 times), usually for loops are not empty, but assigning a local variable might improve things a bit, especially for a huge load of loops. The slow empty for-loop in Javascript took 1.6ms each time, with 72 cells this is already noticable.

Conclusion

So what should you do know? Search for for-loops throughout your application and search for expensive operations in your for loop. When you√Ę‚ā¨‚ĄĘre a Javascripter check al DOM-operations in for-loops, these operations are relatively slow and you usually need the operation only once. It√Ę‚ā¨‚ĄĘs also a good idea to read the Javscript article, it might help you. Look for .length in Javascript, .length seems innocent, but it might just give you the performance boost you need.
It√Ę‚ā¨‚ĄĘs code-wise also better to assign the second parameter to a local variable, it makes your code more readable and why make unnecessary method calls?
I know this article wan√Ę‚ā¨‚ĄĘt rocket science, but a lot of people forget the impact of a method call in a for-loop.

Source

IEBlog : IE + JavaScript Performance Recommendations – Part 1

Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

The post Do you really know how for-loops work? How to speed up your for loops appeared first on AMIS Oracle and Java Blog.

]]>
https://technology.amis.nl/2007/07/15/do-you-really-know-how-for-loops-work-how-to-speed-up-your-for-loops/feed/ 10
Getting started with Eclipse 3.3 WTP 2.0 and JSF √Ę‚ā¨‚Äú will this JSF editor beat JDeveloper? https://technology.amis.nl/2007/07/01/getting-started-with-eclipse-33-wtp-20-and-jsf-will-this-jsf-editor-beat-jdeveloper/ https://technology.amis.nl/2007/07/01/getting-started-with-eclipse-33-wtp-20-and-jsf-will-this-jsf-editor-beat-jdeveloper/#comments Sun, 01 Jul 2007 20:27:53 +0000 http://technology.amis.nl/blog/?p=2230 Share this on .. A few days ago a brand new Eclipse release popped up in my RSS reader. Eclipse 3.3 with WTP 2.0. After browsing through the new features I was very surprised that it included a brand new JSF editor. I thought this sub-project died very slow and painful. What I will try [...]

The post Getting started with Eclipse 3.3 WTP 2.0 and JSF √Ę‚ā¨‚Äú will this JSF editor beat JDeveloper? appeared first on AMIS Oracle and Java Blog.

]]>
Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

A few days ago a brand new Eclipse release popped up in my RSS reader. Eclipse 3.3 with WTP 2.0. After browsing through the new features I was very surprised that it included a brand new JSF editor. I thought this sub-project died very slow and painful.

What I will try is get an existing Maven2 JSF project and open it with WTP2.0 and just see what happens and what is possible.

....

I grabbed an old JSF project of mine (with a Maven2 infrastructure) and tried to open it in Eclipse. Well that didn’t work, I’ve become too lazy I guess. So I opened the manual and read it (who does that nowadays anyway).
The first important step is including the JSF libraries in your Eclipse (not your project, Eclipse!)
Go to Window, preferences, WEB and XML, JavaServer Faces Tools, Libraries and click new.

Include the impl and api library of you JSF implementation. I picked an old MyFaces implementation because that one was bundled with my project. Don’t forget to check the ‘Is JSF Implementation’ (you can also attach other libraries to JSF, that’s why the checkbox is added)

After this you have to include a JSTL library. Finally you should have a screen like this:

Because I’m working on an existing project I had a problem. I couldn’t add a JSF facet to my project manually. Unfortunately I got a strange error saying that I needed a web.xml version 2.5 for a JSF project. The Maven2 eclipse:eclipse command only allows to create a WTP 1.0 project and what I want is a 2.0 project.

After comparing some Eclipse project files I found a (partial) solution. The solution is editing the org.eclipse.wst.common.project.facet.core.xml file in the .settings directory of your project. Just add the following element:

&lt;installed facet=&quot;jst.jsf&quot; version=&quot;1.1&quot;/&gt;

Don’t forget to restart Eclipse and now you can benefit from the new JSF features.

Let’s create a new JSP file and add some components on it.
I recently followed an ADF training at AMIS so I think it’s a good idea to recreate those pages with plain JSF (instead of ADF Faces).
When you created the JSP file you have to open it with the web page editor (right click file, open with, Web Page Editor). This also can be done automatically, consult the Eclipse help file for this, it’s explained pretty well in there.

I expected a JSF editor like JDeveloper, but this one was a little bit different (and I do not mean that it’s bad, it’s just different). There’s a Design and Preview mode. I think the Design mode is added to have a better overview of what you’re building.
When you edit your web page in the Web Page Editor 4 new icons appear on the toolbar:

You can have a split view (with code and design/preview) when you click the first two icons. Isn’t that great? It reminds me of the good old days of HTML-editing in Dreamweaver and when Java was just an island.

The first assignment of the ADF training was to create a search page to find books for a library. It consists of some outputText and inputText elements inside a panelGrid. With the Eclipse JSF editor you can just drag and drop the elements onto the page. A little thing I miss is dragging the element inside the JSP-code, but you’re usually using your keyboard when you’re in JSP-mode (and then you have auto-completion of course)

In the upper-left corner is the wysiwig editor with a panelgrid and some outputText and inputText elements on it. The lower half of that screen is the JSP code. On the right we have a Palette with all JSF components on it and at the bottom is the properties view.

So far so good. But now the thing where it goes ‘wrong’. The next item of the search form is a list with topics. This list is bound to a managed bean. I wanted to pick the managed bean in the binding property of the selectManyListbox element. Wel that just doesn’t work, that’s a shame, that makes the wysiwig interface less useful because we have to look up the beans manually. One of the reasons JSF was developed is to provide the developers with good tooling (where the guys at Oracle did a great job with JDeveloper).
In the JSP view though the auto-completion works ok with the binding attribute. Just enter #{} move the cursor in between the curly braces and hit ctrl-space.

The editor for Faces-config is also pretty cool it has many features. You can pretty much see all the configuration options in a nice interface. They looked good at how they did it with Jdeveloper. The nicest thing is the navigation tab:

Unfortunately I couldn’t get the Faces Config editor working with my Maven2 project, so this is a test with a brand new project.

Conclusion

I really like the editor but it’s only a good start. In my opinion the JSF features of Eclipse are only useful when you’re experienced with JSF. Experienced developers can build JSF manually and check the results in the wysiwig editors. But when you’re new to JSF it just isn’t good enough and maybe even frustrating because you don’t really know what you’re doing.
The fact that I can’t open the faces-config.xml and have to ‘hack’ Eclipse project files isn’t very nice either. But don’t throw Eclipse out of your window yet, this is the first final version of Eclipse that supports JSF and I’m sure the guys at Eclipse are improving the editor as we speak.
For now just stick to JDeveloper, it’s a proven tool and is also free. Or another option is to learn JSF so you can use Eclipse ūüėČ
With Netbeans it’s also possible to edit JSF, you have to include the Visual Web Pack for this. I only saw some screenshots and dragged some JSF-elements onto a page and that all seemed to work pretty good. When you’re deciding which editor to pick it’s a tough one. If all your developers have experience with JSF the Eclipse editor is a good option. Jdeveloper and NetBeans are both safe choices.

Sources

Eclipse 3.3 new and noteworthy
NetBeans Visual Web Pack
Eclipse 3.3 WTP 2.0 download (pick the all in one if you don’t have Eclipse 3.3 yet)

Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

The post Getting started with Eclipse 3.3 WTP 2.0 and JSF √Ę‚ā¨‚Äú will this JSF editor beat JDeveloper? appeared first on AMIS Oracle and Java Blog.

]]>
https://technology.amis.nl/2007/07/01/getting-started-with-eclipse-33-wtp-20-and-jsf-will-this-jsf-editor-beat-jdeveloper/feed/ 14
Using the javax.xml.bind annotations to convert Java objects to XML and XSD https://technology.amis.nl/2007/05/30/using-the-javaxxmlbind-annotations-to-convert-java-objects-to-xml-and-xsd/ https://technology.amis.nl/2007/05/30/using-the-javaxxmlbind-annotations-to-convert-java-objects-to-xml-and-xsd/#comments Wed, 30 May 2007 10:52:41 +0000 http://technology.amis.nl/blog/?p=2046 Share this on .. Did you know that when you put the @XmlRootElement annotation on any class you can have an XML representation of that class? When I first saw Java 6 I didn’t get very excited by it, but I have found out some nice things (scripting and Derby for example). This article will [...]

The post Using the javax.xml.bind annotations to convert Java objects to XML and XSD appeared first on AMIS Oracle and Java Blog.

]]>
Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

Did you know that when you put the @XmlRootElement annotation on any class you can have an XML representation of that class?

When I first saw Java 6 I didn’t get very excited by it, but I have found out some nice things (scripting and Derby for example). This article will also describe a new feature of Java 6. I believe it was also possible with JWSDP, but I don’t like to search external libraries (or at least not standard in a Maven 2 repository ūüėČ )

I wanted to put an get an XML document in and from a database. With the new JDBC 4.0 you can save and load the XmlType data type from your database. But this article is not about JDBC, it started as an article about it, but then I discovered some pretty cool featues with XML only. The JDBC 4.0 has to wait a little longer.

Creating the XML document

When I was looking how to create an XmlType object I found out it was possible to marshal (the conversion from Object to XML representation) an object to an XML document. Let’s start with a simple class called Movie:

<code><span style="color: #7f0055;"><strong>public class </strong></span><span style="color: #000000;">Movie </span><span style="color: #000000;">{</span>

<span style="color: #ffffff;">  </span><span style="color: #7f0055;"><strong>private </strong></span><span style="color: #000000;">String title;</span>

<span style="color: #ffffff;">  </span><span style="color: #7f0055;"><strong>private </strong></span><span style="color: #000000;">String genre;</span>

<span style="color: #ffffff;">  </span><span style="color: #7f0055;"><strong>private </strong></span><span style="color: #000000;">Integer year;</span>

<span style="color: #000000;">}</span></code>

Now create the getters and setters for these fields. Note that without getters and setters the marshalling doens’t work as expected! An empty constructor is also needed when you override the default constructor.

The final step is putting an @XmlRootElement annotation on your class.

<code><span style="color: #646464;">@XmlRootElement</span>

<span style="color: #7f0055;"><strong>public class </strong></span><span style="color: #000000;">Movie </span><span style="color: #000000;">{</span>

<span style="color: #ffffff;">  </span><span style="color: #000000;">...</span>

<span style="color: #000000;">}</span></code>

I created a simple unit test to print an XML document to the System.out.

 

<code><span style="color: #7f0055;"><strong>public class </strong></span><span style="color: #000000;">XmlTest </span><span style="color: #7f0055;"><strong>extends </strong></span><span style="color: #000000;">TestCase </span><span style="color: #000000;">{</span>
<span style="color: #ffffff;">  </span><span style="color: #7f0055;"><strong>public </strong></span><span style="color: #7f0055;"><strong>void </strong></span><span style="color: #000000;">testXml</span><span style="color: #000000;">() </span><span style="color: #7f0055;"><strong>throws </strong></span><span style="color: #000000;">Exception </span><span style="color: #000000;">{</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">Movie movie = </span><span style="color: #7f0055;"><strong>new </strong></span><span style="color: #000000;">Movie</span><span style="color: #000000;">(</span><span style="color: #2a00ff;">"Pulp Fiction"</span><span style="color: #000000;">, </span><span style="color: #2a00ff;">"Action"</span><span style="color: #000000;">, </span><span style="color: #990000;">1994</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>

<span style="color: #ffffff;">    </span><span style="color: #000000;">JAXBContext context = JAXBContext.newInstance</span><span style="color: #000000;">(</span><span style="color: #000000;">Movie.</span><span style="color: #7f0055;"><strong>class</strong></span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">Marshaller marshaller = context.createMarshaller</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">marshaller.setProperty</span><span style="color: #000000;">(</span><span style="color: #000000;">Marshaller.JAXB_FORMATTED_OUTPUT, </span><span style="color: #7f0055;"><strong>true</strong></span><span style="color: #000000;">)</span><span style="color: #000000;">; </span><span style="color: #3f7f5f;">//pretty print XML</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">marshaller.marshal</span><span style="color: #000000;">(</span><span style="color: #000000;">movie, System.out</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">  </span><span style="color: #000000;">}</span>
<span style="color: #000000;">}</span></code>

I created a constructor for my Movie object, so I didn’t have to set 3 fields. The next line creates a JAXBContext, this is the entry point of all your JAXB operations. You can give an array of classes (or just use the Java 5 varargs as parameters) or a list of packages. For now it is enough to pass the Movie class. With our context we can create a Marshaller, the marshaller will perform the actual conversion to XML.

The property jaxb.formatted.output is used for debugging purposes only, normally all XML tags will be on one line.

Finally we invoke the marshal method and you’ll see the following document appear on the console:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<movie>
<genre>Action</genre>
<title>Pulp Fiction</title>
<year>1994</year>
</movie>

You can also route the output to other streams or objects. The javadocs of the Marshaller explain this pretty well.

To get a String create a StringWriter object and ivoke the getBuffer() get a StringBuffer, which can be toString()-ed to get a String.

 

Creating the schema

Whilst browsing the API I found a method called generateSchema. That sounds cool and easy. The easy part appeared to be a little more difficult, but it works.

The generateSchema method on JAXBContext takes a SchemaOutputResolver as parameter and changes that object (which is quite evil in my opinion). So let’s find an implementation of the SchemaOutputResolver. When I opened the Javadoc I saw this interesting line of comment : “This is a class, not an interface so as to allow future versions to evolve without breaking the compatibility” I don’t get this, an interface breaks compatibility? I looked up the source of SchemaOutputResolver and found no non-abstract methods, so that’s an interface to me, but you can’t extend from another class and extending from another class doesn’t break compatibility or does it?

But enough of that, I couldn’t find an implementation of the class. Fortunately google code search helped me out. In the source of Xfire I found an implementation of the clas:

<code><span style="color: #7f0055;"><strong>final </strong></span><span style="color: #000000;">List&lt;DOMResult&gt; results = </span><span style="color: #7f0055;"><strong>new </strong></span><span style="color: #000000;">ArrayList&lt;DOMResult&gt;</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">  </span><span style="color: #000000;">context.generateSchema</span><span style="color: #000000;">(</span>
<span style="color: #ffffff;">    </span><span style="color: #7f0055;"><strong>new </strong></span><span style="color: #000000;">SchemaOutputResolver</span><span style="color: #000000;">() {</span>
<span style="color: #ffffff;">      </span><span style="color: #646464;">@Override</span>
<span style="color: #ffffff;">      </span><span style="color: #7f0055;"><strong>public </strong></span><span style="color: #000000;">Result createOutput</span><span style="color: #000000;">(</span><span style="color: #000000;">String ns, String file</span><span style="color: #000000;">)</span>
<span style="color: #ffffff;">            </span><span style="color: #7f0055;"><strong>throws </strong></span><span style="color: #000000;">IOException </span><span style="color: #000000;">{</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">DOMResult result = </span><span style="color: #7f0055;"><strong>new </strong></span><span style="color: #000000;">DOMResult</span><span style="color: #000000;">()</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">result.setSystemId</span><span style="color: #000000;">(</span><span style="color: #000000;">file</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">        </span><span style="color: #000000;">results.add</span><span style="color: #000000;">(</span><span style="color: #000000;">result</span><span style="color: #000000;">)</span><span style="color: #000000;">;</span>
<span style="color: #ffffff;">        </span><span style="color: #7f0055;"><strong>return </strong></span><span style="color: #000000;">result;</span>
<span style="color: #ffffff;">      </span><span style="color: #000000;">}</span>
<span style="color: #ffffff;">  </span><span style="color: #000000;">})</span><span style="color: #000000;">;</span></code>

I won’t get into the details of this code, it isn’t important right now, we just want a schema. The context object is the JAXBContext object we created earlier.

The final step is writing the schema to System.out. This is a little bit more work than the XML file:


DOMResult domResult = results.get(0);
Document doc = (Document) domResult.getNode();
OutputFormat format = new OutputFormat(doc);
format.setIndenting(true);
XMLSerializer serializer = new XMLSerializer(System.out, format);
serializer.serialize(doc);

We have to cast node from the result to a Document to let the serializer understand it. The setIndenting(true) not only indents, but also puts every tag on a new line.

The result:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="movie" type="movie"/>
  <xs:complexType name="movie">
    <xs:sequence>
      <xs:element minOccurs="0" name="genre" type="xs:string"/>
      <xs:element minOccurs="0" name="title" type="xs:string"/>
      <xs:element minOccurs="0" name="year" type="xs:int"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

Advanced

This schema isn’t right I hear you think. A movie needs at least a title, so minOccurs should not appear.

 

<code><span style="color: #646464;">@XmlElement</span><span style="color: #000000;">(</span><span style="color: #000000;">required = </span><span style="color: #7f0055;"><strong>true</strong></span><span style="color: #000000;">)</span>
<span style="color: #7f0055;"><strong>public </strong></span><span style="color: #000000;">String getTitle</span><span style="color: #000000;">() {</span>
<span style="color: #ffffff;">  </span><span style="color: #7f0055;"><strong>return </strong></span><span style="color: #000000;">title;</span>
<span style="color: #000000;">}</span></code>

Remember to put the annotation on the getter and not on the field, otherwise you’ll get the following error:

com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions

Class has two properties of the same name “title”

When you run your test again you’ll notice the minOccurs=0 has dissapeared. The order of the elements has also changed, this is not wat we want. The title must be the first element and today I think year as the second element is nice.

We have to use the @XmlType annotation for this:

<code><span style="color: #646464;">@XmlRootElement</span>
<span style="color: #646464;">@XmlType</span><span style="color: #000000;">(</span><span style="color: #000000;">propOrder = </span><span style="color: #000000;">{</span><span style="color: #2a00ff;">"title"</span><span style="color: #000000;">, </span><span style="color: #2a00ff;">"year"</span><span style="color: #000000;">, </span><span style="color: #2a00ff;">"genre"</span><span style="color: #000000;">})</span>
<span style="color: #7f0055;"><strong>public class </strong></span><span style="color: #000000;">Movie </span><span style="color: #000000;">{ </span><span style="color: #000000;">... </span><span style="color: #000000;">}</span></code>

Quite straightforward, only a pity that we have to ‘hardcode’ the element names. It would’ve been nice if the schema generator took the order as we put it in the class (but of course there is no order in the class, it’s just what we see). The good thing however is that you’ll get an error on the JAXBContext.newInstance(Movie.class); when you do something wrong with the propOrder.

 

Multiple genres

Pulp Fiction is an action movie, but it’s also crime and drama. What we usually do in Java is create a Set of genres. Unfortunately it doen’st work when you replace the String genre with Set genres, you need to put an annotation on a getter and you can’t just change the Set interface. So I created a GenreSet class:

public class GenreSet {
  private Set<String> genre;
  
  public GenreSet() {
    genre = new HashSet<String>();
  }

  public void add(String s) {
    genre.add(s);
  }

¬†¬†@XmlElement(name¬†=¬†“genre”)
  public Set<String> getGenre() {
    return genre;
  }
}

I replaced the String genre in the Movie class with GenreSet genres and when we run the test again we’ll get a set of genres:

<code><span style="color: #000000;">&lt;?xml version=</span><span style="color: #2a00ff;">"1.0" </span><span style="color: #000000;">encoding=</span><span style="color: #2a00ff;">"UTF-8" </span><span style="color: #000000;">standalone=</span><span style="color: #2a00ff;">"yes"</span><span style="color: #000000;">?&gt;</span>
<span style="color: #000000;">&lt;movie&gt;</span>
<span style="color: #ffffff;">  </span><span style="color: #000000;">&lt;title&gt;Pulp Fiction&lt;/title&gt;</span>
<span style="color: #ffffff;">  </span><span style="color: #000000;">&lt;year&gt;</span><span style="color: #990000;">1994</span><span style="color: #000000;">&lt;/year&gt;</span>
<span style="color: #ffffff;">  </span><span style="color: #000000;">&lt;genres&gt;</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">&lt;genre&gt;Drama&lt;/genre&gt;</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">&lt;genre&gt;Crime&lt;/genre&gt;</span>
<span style="color: #ffffff;">    </span><span style="color: #000000;">&lt;genre&gt;Action&lt;/genre&gt;</span>
<span style="color: #ffffff;">  </span><span style="color: #000000;">&lt;/genres&gt;</span>
<span style="color: #000000;">&lt;/movie&gt;</span></code>

Omit the year

Suppose we don’t want to show the year in XML, but we do want it to be in the Java object. We can use the @XmlTransient annotation to get this behaviour.

 

Year as attribute

It’s also possible to use a field as an attribute, use the @XmlAttribute for this.

 

Conclusion

What started out as an article to show the XmlType in JDBC turned out to be an article about XML only. After the @XmlAttribute I thought it was time to stop. Every time I started exploring a new feature I found 2 new other cool features. The java.xml.bind package is quite extensive with many possibilities.

A good thing is that everything is in the JDK, when you had a library problem in the past it probably was due to an XML libary.

 

Sources

JAXBContext javadoc

Marshaller javadoc

http://forum.java.sun.com/thread.jspa?threadID=633093&messageID=3666378

Xfire source for SchemaOutputResolver

unofficial JAXB Guide

 

Share this on .. Tweet about this on TwitterShare on LinkedInShare on FacebookShare on Google+Email this to someoneShare on TumblrBuffer this page

The post Using the javax.xml.bind annotations to convert Java objects to XML and XSD appeared first on AMIS Oracle and Java Blog.

]]>
https://technology.amis.nl/2007/05/30/using-the-javaxxmlbind-annotations-to-convert-java-objects-to-xml-and-xsd/feed/ 4