Joine Music

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Tuesday, 17 October 2006

JAXB, JIBX and Reverse Engineering XSD from my Java Object Model

Posted on 10:27 by Unknown
I've got the requirement to output the contents of my object model in a readable fashion. What could be more readable than XML which led me to JAXB. The onyl problem is, with JAXB you start with the schema and go in the other direction. Step up to the mark JiXB. This allows you to go the other way and was very simple to get up and running.
  1. First step was download the bits and "install" (i.e. unzip) them (the "bits" I used were the core libs plus the utils. In my case "jibx_1_1.zip" and "jibxtools-beta2.zip"
  2. Copy the jibx-genbinding.jar and jibx-genschema.jar files from the tools zip file to the ./lib directory of your main JiBX "install"
  3. Open a command line and change directory to where your compiled classes are (NOTE: not the java source files as jibx uses introspection with the class files to do it's work. If they are in a package structure, make sure you are at the root of the package structure so that the cp declaration in the following command works. Otherwise you'll get a JiBXException about classes not being found)
  4. Auto-generate the binding file ("binding.xml") for your classes by running the following command:
    • java -cp . -jar /home/myexampleuser/jibx/lib/jibx-genbinding.jar com.myexample.ClassA com.myexample.ClassB
  5. I had warnings at this stage about references to interfaces or abstract classes:
    • Warning: reference to interface or abstract class java.util.Set requires mapped implementation
  6. I'd gone outwith the standard example on the website. Time to hit google... It turns out that out-of-the-box JiBX can handle some java.util.Collections fine like ArrayLists which my model also used but java.util.Sets (I'd used HashSet) were a little more troublesome. I needed to edit the newly created binding.xml file each time a Set-based relationship was found as follows:
    • Original: <structure field="mySetOfAObjects" usage="optional">
      </structure>
    • Updated: <collection field="mySetOfAObjects" factory="com.myexample.ObjectB.hashSetFactory">
      <structure type="com.myexample.ObjectB" usage="optional"/>
      </collection>
  7. You'll have noticed that I seem to be calling a method "hashSetFactory()" on ClassB. This is the case, and it won't be there already. You need to add a static method to this class as follows:
    • private static Set hashSetFactory() { return new HashSet();}
  8. You'll now be able to run the second command which will generate your xsd schema for you based on your new mapping binding.xml file:
    • java -cp . -jar /home/myexampleuser/jibx/lib/jibx-genschema.jar binding.xml
  9. This will then generate you the xsd schema file you have been looking for all along.
Read More
Posted in | No comments

Monday, 21 August 2006

Imagining Using the Portlet 2.0 (JSR 286) Early Draft 1 Spec Release

Posted on 07:41 by Unknown
I've done some projects which have used JSR 168 Portlets in the past. When I saw that the first public released draft of the new spec was out I thought I'd take a look. Here's my imaginings of how things would have been if we'd used this spec instead...

Lets describe my imaginary app. (The standard kind of portler app I've worked on.) The setup is simple. There are three portlets. A “search” portlet and two content portlets: “films” and “actors”. You can use the search portlets single search field, coupled with a radio button selection of the search type (c.f. google) to search for either actors or films. The results of your search are displayed in the same portlet as a clickable list.

Once a result in this list is clicked, wiring passes the actor or film id to the relevant portlet, which retrieves and displays the relevant content. If the other content portlet currently displays content, then a “reset” wire from the search portlet tells it to clear its contents.

Finally, content displayed in the actor portlet includes a list of films which they have appeared in. Clicking this link passes the film id to the films portlet which again retrieves and displays the relevant content. On this occasion there is no need to reset any other portlets. This functionality is also present from the films portlet to the actors portlet.

Clearly this is not at all possible using JSR 168 portlets alone. We were deploying to Websphere Portal Server 6.0 which gave us the ability to "wire" portlets together which were on the same page (inter page wiring has been added since then). This wiring was pretty darn complex (i've blogged about it before now) but once we got it going, we were able to get the kind of behaviour described above. In our case, even though we had all our portlets in a single war app, we passed all our parameters (such as film and actor ids) as request parameters and the wiring allowed an action in one portlet to call the processAction() method in another before all the following doView(). We only used the sessions for portlets to store their individual state, not to share it.

So how would things change if we now wanted to change to Portlet 2.0? Well the first point I'm happy to make is that we still have binary backwards compatability with 1.0 portlets. This means all our portlet code would still work. However, as the wiring was all proprietary, we would have to do something new to regain this functionality.

This is where the new "Portlet Co ordination" model comes in. The new spec (as I understand it) has added the concept of events which can be "thrown" (my terminology - almost in the same way as exceptions or events which are listened for in Swing apps is the impression that I get). These are then handled in an additional phase in the request action handling - rendering cycle which occurs after the relevant processAction() method is called, but before all the doView(), doEdit() etc. calls are made to generate the page fragments. As with wires, you can set attributes in the event (as standard types or even XML which is marshalled with JAXB - nice and flexible) which can then be picked up by those portlets which have elected (declaratively in the portlet.xml - again, nice and flexible) to react to specific
goings on which have happened (not only as a result of user interaction, but also emitted from the portal framework itself (c.f. pp. 75) The spec indicates that portlets can send what are termed "dynamic" events which are not declared in portlet.xml or, more usually static "declared" events. Finally I should note that a portlet can throw more than one event per processAction() call. Something which made things even more complicated with Websphere wires.

Clearly this is brilliant. How do we do it? Well, there's a new lifecycle interface for our portlet classes: javax.portlet.EventPortletInterface. This provides a new method which we must implement: processEvent(). To reinstate our old wired portlets, we need to take the Portlet classes we'd written, add the implementation of the interface, do some fairly hefty refactoring to move a lot of the code in many of the portlets processAction() methods to the new processEvent() method, declare our sending and receiving of events in the portlet.xml file and then deploy. Hooray! The complex WSDL for the exports and imports of data which WebSphere used for wiring is no longer required.

The final beauty of this new model is that the portal will now be happy to dynamically propagate any events as requested during operations. No more intervention is required after a successful deployment. (This is a vast improvement on WebSphere wiring jungle which would be remembered after subsequent deployments, but if you wanted to change a wire, you had to undeploy the entire portlet application and remove your portal pages again, then redeploy, put the pages back and then re wire using the admin GUI. If things still didn't work, then you'd have to undeploy, destroy and then repeat again. This wasted a lot of time.)

You should have guessed that I'm very happy that this has been added to the 2.0 spec. But while I do admit that it does seem a vast improvement on the way I have described above, I fear a few tricks have been missed in keeping this simple. Firstly, one of the few things I did like about the wiring method was that the wire effectively allowed you to call processAction() on one portlet, set a request parameter which would tell the wire to then call the processAction() on another portlet. It made sense to me and did not mean I had to understand (and debug) an increasingly complex class flow. Indeed, there could be multiple calls (as I outlined above where a click in a search result would get one portlet to display some detail and the other to reset itself) and each would follow the same route, initiated by the same original interaction from the user. The point I'm trying to make is that I'm not entirely convinced that there is a requirement for another portlet method, and its associated interface to implement. What is so vastly different between "actions" and "events" which means that they have to be handled separately?

Portlet development, even in the simplest sense is more complicated that it is with servlets - and rightly so, due to the slightly more complicated request - (action - render) - response cycle. But the aim should be to keep a sensible level of simplicity, otherwise potential developers will be driven away and the spec under used. Something JEE is only just recovering from. Consequently, it seems to me, that were the two new concepts of Portlet Co ordination and Shared Render Parameters (see below) to be linked and allow the proposed mechanism to call the processAction() methods rather than the additional processEvent() methods. The associated benefits of bookmarkable URLs (see below) could be leveraged and the present processing mechanism would be maintained. Code which was written for 1.0 could be simply updated (or in my case, little new would have to be done, we could just replace the wires with the new entries in portlet.xml to let on about who did the sending and who the receiving. Sorted.

Which brings me onto my second and final (and far shorter) area of feedback. I've already discussed what a nightmare getting the WebSphere wiring to work could be. It certainly seems vastly simpler with the "auto wiring" in the 2.0 spec, and the necessary xml configurations in portlet.xml are vastly simpler than the previous WSDL nightmare. But are the configurations necessary at all? Why do we still have to hack XML? - EJB3 showed us that annotations and sensible defaults can get us a great deal. I would also like to see the same sort of support in Portlet 2.0. Perhaps this is a way of implementing the (possibly necessary complexity) which led to the additional processEvent() step. As with EJB's, the Home, RemoteHome, and other interfaces are still there, it's just that the developer never needs to think about them, unless they choose to.

Before I close, I'd like to mention a few more quickies. Firstly, support for Java 5 - excellent - but why no support for JEE 1.5 rather than 1.4? Surely this would be an ideal to piggy back on what looks to be a storming, remarkably simplified and vastly more usable spec. The fact that the JPA can now be used outside an EJB container is a vast improvement. If portlets could then simply use this for the "M" in their MVC (we just used Hibernate and POJOs when we did our development) then everything done would be far more futureproof and allow portal implementations to run on Web Container only platforms.

Secondly, it is also very welcome to see the ability to share session state and render parameters. The possibililty of bookmarkable portlet URLs is an attractive one and will greatly increase usability and greatly simplify trying to handle the ever present threat of a user pressing the dreaded "back" button. The ability to share parameters outside the current portlet application is also a great improvement on a previously frustrating and seemingly arbitrary restriction.

All in all, I think this is a very promising looking 2.0 spec. I for one look forward to doing more portlet development in the future and coming up with even wilder ways to try and push the limits of what it can do.

NOTE: I haven't commented on the proposed AJAX or WSRP support. Both would be most welcome however and help the spec to be relevant to an even wider audience.
Read More
Posted in | No comments

Wednesday, 26 July 2006

My Current Firefox Extensions

Posted on 09:56 by Unknown

Here's a snap of my current firefox extensions. Not too few, not too many, but just enough...


Read More
Posted in | No comments

Tuesday, 11 July 2006

EJB 3.0: One Model Inside and Out (Pt. 2) - The POJO Model Itself – Annotations and Relationships

Posted on 03:26 by Unknown
Please note, this blog entry is based heavily on many other things out there on the web at the moment, most particularly this tutorial on netbeans.org. I've taken this liberty, as I thought I needed to provide a firm bedrock upon which to build my later entries in this series where I do go into uncharted territory. If I have infringed any copyright, please do tell me and I will take appropriate action.

I hate databases. We don't get on. They don't respect me, and as a result I don't respect them. Therefore I always like to start my OO apps. by encapsulating the domain model in a class model. For the Loads-A-Movies project mine was very simple:

If it looks simple, it's supposed to. Lets create the classes.

Creating the Movie Entity Class

This will represent the table “MOVIE” in the database. We first need to generate a simple, serializable java POJO class with the attributes shown above encapsulated as appropriate (you can do this automatically with your chosen GUI). This now needs to be annotated to let the compiler know how to treat it. (Note: This requires JDK annotation support which you'll get if you use Java 5)

 ...
public class Movie implents Serializable {
private Long id;
private String title;
private int runningTime;

public Long getId() {
return id;
}

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

First up we need to let on this is an Entity Class. We do this simply by using the “@Entity” annotation before the “public class Movie implements Serializable” line. The compiler is now clever enough to know that, unless told otherwise, the attributes on this class will be represented as columns in our table. That's how EJB 3.0 works. It assumes the default, unless you tell it different. Very handy.

 ...
import javax.persistence.Entity;
...
@Entity
public class Movie implents Serializable {
...

The observant amongst you will realise that we most likely need a primary key. Correct, each entity class must have a primary key. When you create the entity class, we must add an @Id annotation to the “id” attribute to declare we plan to use it as the primary key. We also add the @Generated... annotation to specify the key generation strategy for the primary Id. In our case:

 ...
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
...
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
...

Finally for Movie, there is the interesting case of the relationship with the Actor Entity class. Firstly we need to add the collection attribute, “Collection actors;” and encapsulate it (again you can do this automatically with your GUI if you so desire). Now you need to provide some information about the relationship. Add the following annotation above the actors collection to specify a One-to-Many relationship for the entity:

  import javax.persistence.OneToMany;
...
@OneToMany(mappedBy="movie")
private Collection actors;
...

And that's the Movie Entity class coded. We now need to do the same for the Actors. As before, create a POJO class (ensuring you “implement Serializable”) with the required attributes encapsulated. This will represent the "ACTOR" table in the database. Again define it as an Entity with the @Entity annotation and mark the “id” attribute as the primary key and set it to
be auto generated with the @Id and @Generated tags.

Again we need to add the new attribute. in this case it's the Actior nowing about the film he has appeared in:

 private Movie movie;

Again, encapsulate this attribute. Finally we need to add the annotation to let on that this is the reverse direction of the previous relationship. We do this by putting the following annotation above the new movie declaration:

  import javax.persistence.ManyToOne;
...
@ManyToOne

private Movie movie;

Note: You'll have noticed that you require imports for these annotations. These are contained in the “javaee.jar” package which I needed to declare as a dependency in my maven project.xml file. I found the one I used in my GlassFish server's /lib directory. If you're doing it differently maybe your IDE has suggested one for you.


That's all for this entry. There is far more information on the possibilities of EJB 3.0 persistence which I haven't gone into. The best sources for more information I have found are as follows:
  • Java Persistence in the Java EE Platform - tutorial at netbeans.org
  • Standardizing Java Persistence with the EJB3 Java Persistence API - Article at OnJava.com
  • The Java Persistence API - A Simpler Programming Model for Entity Persistence - Article at java.sun.com
Read More
Posted in | No comments

EJB 3.0 - One Model Inside and Outside the Container (Pt. 1)

Posted on 02:44 by Unknown
I'm writing a suite of (i.e. two) applications which share an object model. I'm a trained J2EE architect and consequently I love the idea of maximum code reuse. I'm also lazy. In the following series of blog entries I'm going to explain how I managed to achieve this using Java 5, EJB 3.0 (including persistence) and Maven.

First up, lets have a quick overview of what I'm trying to achieve. The plan is to create a website to store information about my film collection. I want to be able to do all kinds of fancy things but really it's an excuse to fiddle around with Java 5, generics, annotations, JSF, EJB 3.0 and Maven. I have a cunning plan however. I love the idea of the Flickr uploader but I want to take it further. What if I could have a local, thick Swing app. which I could keep in sync. with my web app. and use to upload and maintain info on my public website? It could use the same model code... That would be cool. It would also let me fiddle with the Matisse GUI builder, Derby and most importantly the Napkin look and feel...

So how am I going to approach this? Well, the plan is to have three separate maven projects, with all the common stuff factored out into a code-less master project (I won't go into this any further, that's a separate blog entry). The first is to be the model project; “loadsamovies-model” which we will discuss in the next blog, the second the web presentation layer; “loadsamovies-presentation” which I don't plan to go into as the techs and methods is covered in great detail elsewhere. The last is the uploader Swing app; “loadsamovies-thickclient”

See the next entry for how I coded up the model.
Read More
Posted in | No comments

Sunday, 9 July 2006

Booting Apache Derby ("JavaDB") with your Java App's Startup

Posted on 09:58 by Unknown
If you're embedding the Derby RDBMS with your java desktop application and want it to start when you start your app, you need to make the following call somewhere in your code (i.e. in main() or an init() method):
        // Start the Derby Database
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver")
.newInstance();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}

// Set the connection to the database
Connection conn = null;
try {
conn = DriverManager
.getConnection("jdbc:derby:sample;create=true");
} catch (SQLException ex) {
ex.printStackTrace();
}

It's important to notice (as I didn't to begin with) that you need the local version of the URL as you are doing this using the embedded driver. If you use the URL version you'll get a "java.sql.SQLException: No suitable driver" error.


You'll also notice that this creates the database with the name provided in a directory with the name provided, (e.g. "sample"). This directory will be in the same place as the main class you are running.

One final thing, this is dead easy to use with EJB 3.0 too. All you need to do is set up your persistence manager to run outside a container and as soon as you have started your embedded database, you can connect to it with something like TopLink. Beautiful....
Read More
Posted in | No comments

Saturday, 8 July 2006

Ubuntu Superusers

Posted on 03:31 by Unknown
I came to Ubuntu (Dapper Drake) from Solaris. I thought I'd be able to log in as the root user or su from the command line to my heart's content. It's not that simple. By default you can't log in or su to the root user as I expected. To perform admin tasks as a non root user you need to use the sudo command (this was in fact running for me withjout my knowledge as I ran the various admin tasks to set things up after install. For info on the sudo command, look at the Dapper documentation wiki.
Read More
Posted in | No comments
Newer Posts Older Posts Home
Subscribe to: Posts (Atom)

Popular Posts

Categories

  • 0
  • 2008
  • ant maven pimp build javaone 2008
  • apple ipod touch
  • asm
  • blog new ruby
  • blogtag list
  • bond casinoroyale mashup mi6 film movie
  • build
  • bytecode
  • CI
  • cobertura
  • communityone 2008 nutter jvm scala jruby groovy davinci
  • communityone 2008 opensocial socialsite
  • communityone javaone keynote oreilly
  • configuration
  • cowley
  • css div layout column ie firefox safari example
  • custom
  • darkstar mpk20 wonderland java3d commaboration SL
  • dashboard rss communication news development
  • db2 database SQL max min howto tip
  • db2 database ibm lessons tips
  • db2 database load batch howto example
  • db2 import upload data howto command
  • debt technical java annotation
  • debugging tips javaone 2008
  • development web2.0
  • findbugs JavaOne 2008 pugh
  • findbugs JavaOne BOF notes
  • gafter closures java javaone notes
  • google trouble patriarchal patriarchy
  • groovy metaprogramming javaone 2008
  • grubby oss data generation project announce
  • guice javaone 2008
  • gwt maven howto example simple
  • howto
  • hudson
  • hudson CI javaone 2008
  • ibm
  • invokeDynamic jvm dynamic ruby javaone
  • itinerant web2.0 portable desktop
  • jacl was websphere wsadmin trace logging
  • james gosling sun java open source tech days second life SL
  • jar java manifest properties config howto tip
  • java
  • java applet javaone 2008 reloaded jnlp
  • java javafxscript javaone 2008 fxscript
  • java javaone 2007 07
  • java javaone 2008 bytecode cobertura asm singleton testability
  • javaone
  • javaone keynote gage schwarz javafx
  • javaone semantic web bof notes web3
  • jazz
  • jruby rails javaone charlesnutter thomasenebo
  • jruby ruby netbeans development
  • kill dead laptop computer rebuild restore
  • lessonslearned
  • mac osx java gui shellscript classpath problem solution
  • maven plugin unittest test packager
  • mylin mylar javaone eclipse 2008
  • netbeans development ide
  • netbeans development ide RC
  • netbeans maven2 profiling
  • netbeans ruby sun tech days visual web pack roman strobl
  • ola bini java javaone 2008 thoughtworks ruby jruby
  • openjdk java javaone javafx wonderland
  • overheard
  • pojo ejb3.0 jpa orm java example howto
  • rant
  • rest restful jsr311 java web2.0 javaone ts-6411
  • rome rss feed blog rss atom propono java javaone
  • rsa uml profile plugin howto
  • ruby inheritance example
  • ruby jruby rss xml hpricot
  • ruby unless example
  • scm
  • setup
  • subversion svn xp windows cleanup
  • sun java soa web2.0 netbeans opensource javacaps
  • sun tech days java derby database rdbms london
  • sun tech days london impressions
  • terracotta java javaone 2008 android gwt
  • tip
  • tips
  • vwp netbeans JPA howto
  • was jython scripting nfr ibm pmi jvm
  • was tpv jython scripting nfr ibm pmi
  • webrick ruby jruby actadiurna investigation code howto
  • workitem

Blog Archive

  • ▼  2012 (1)
    • ▼  October (1)
      • Writing Unit Tests to Ensure Your "@Transactional ...
  • ►  2010 (8)
    • ►  November (1)
    • ►  October (3)
    • ►  June (1)
    • ►  May (1)
    • ►  February (1)
    • ►  January (1)
  • ►  2009 (9)
    • ►  December (1)
    • ►  November (5)
    • ►  March (2)
    • ►  February (1)
  • ►  2008 (22)
    • ►  December (1)
    • ►  November (3)
    • ►  May (15)
    • ►  March (1)
    • ►  January (2)
  • ►  2007 (53)
    • ►  December (1)
    • ►  November (3)
    • ►  September (3)
    • ►  August (2)
    • ►  July (3)
    • ►  June (1)
    • ►  May (12)
    • ►  April (5)
    • ►  March (13)
    • ►  February (7)
    • ►  January (3)
  • ►  2006 (35)
    • ►  December (8)
    • ►  October (1)
    • ►  August (1)
    • ►  July (5)
    • ►  June (8)
    • ►  May (3)
    • ►  April (7)
    • ►  March (2)
Powered by Blogger.

About Me

Unknown
View my complete profile