You're viewing all posts tagged with java

cooler javaFX kreations

Oracle recently released JavaFX 2, which is a rich client API that ditches the JavaFX language from JavaFX 1.x in favor of a pure Java library.  And man, is it slick.  It makes it very easy to implement rich, graphical applications or applets.

Inspired by @visualrinse’s Cooler Kreator, I created my own (greatly simplified)  version of it, which I called “Cooler Kreations FX”.  To use it, simply launch it, give it permission to run, type in a tag, and the program will consult Kuler for a random color scheme with the specified tag.  Assuming, of course, that the Kuler API is working at the time (which, lately, hasn’t been very often…).

To create an application is as simple as extending the Application class.

public class CoolerKreations extends Application {

    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage stage) {
        stage.setScene(createScene());
    }
 
    private Scene createScene() {
        ....
    }
}

You can use FXML to create your scenes declaratively, or write pure Java code to create your scenes programatically, or mix and match the two.

// declaratively, via FXML
Group root = FXMLLoader.load(getClass().getResource("my.fxml"));
Scene scene = new Scene(root, Color.BLACK);

// the FXML:
<VBox fx:controller="com.metatrope.controller.Controller" alignment="center" xmlns:fx="http://javafx.com/fxml" style="-fx-spacing: 5;">
   <children>
        <HBox alignment="center">
           <children>
                <Label text="Cooler Kreations" style="-fx-font: 42 Tahoma;" textFill="white" fx:id="title"/>
                <Label text="FX" style="-fx-font-weight: bold; -fx-font-size: 42; -fx-font-style: italic;" textFill="white" fx:id="titlefx"/>
           </children>
        </HBox>
   </children>
</VBox>

// programatically
Group root = new Group();
Text text = new Text();
text.setText("hi");
root.getChildren().add(text);
Scene scene = new Scene(root, Color.BLACK);

There are a lot of controls available. Visually, you can style your controls with CSS and there are plenty of effects you can use, such as drop shadows, reflections, blurs, and more. You can even chain them:

Bloom bloom = new Bloom();
bloom.setThreshold(2.0);

BoxBlur blur = new BoxBlur(4 + randomInt(0, 5), 4 + randomInt(0, 5), 4 + randomInt(0, 6));
blur.setInput(bloom);
 // the output of bloom will be the input for this effect

DropShadow ds = new DropShadow();
ds.setOffsetY(4.0f);
ds.setOffsetX(4.0f);
ds.setColor(Color.CORAL);
ds.setInput(blur);
 // the output of blur will be the input for this effect

// apply bloom AND blur AND a drop shadow to this text
text.setEffect(ds);

JavaFX also makes it dead simple to animate controls. Simply bind a property and identify key points in the timeline, and the system will interpolate all the values in between. For example, here I tell JavaFX to rotate one of my nodes repeatedly:

// loop my node from 0 degrees to 360 degrees, completing one rotation every 15 seconds.
// repeat ad infinitum.
Timeline animation = new Timeline();
animation.getKeyFrames().addAll(
  new KeyFrame(Duration.ZERO, new KeyValue(node.rotateProperty(), 0d)),
  new KeyFrame(Duration.seconds(15.0), new KeyValue(node.rotateProperty(), 360d)));
);
animation.setCycleCount(Animation.INDEFINITE);
animation.play();

This is a huge step forward for rich client development in the Java space and a wonderful replacement for Swing.  On modern JVMs, it even loads quickly in the browser; this wasn’t historically the case with JavaFX 1.x, or for applets in general, but nowadays Java applets start up almost as fast as Flash (and this will improve even more when Java becomes modularized in future versions.) 

The source code can be viewed on my github account.  You can test it out online as well (though only if you use Windows, unfortunately.)  The result could look something like this:

force create hibernate envers audit events

Recently, I had decided to adopt Hibernate Envers to audit changes to several tables on my database.  I decided to attempt to force create the insert events that would have been generated had I been using Envers from the start.  Unfortunately, there wasn’t an obvious way to do this, short of writing my own SQL scripts.  That approach is fine, but I had several tables to migrate, and I prefer to avoid bypassing Hibernate when I can.

This is what I came up with:

Envers works by using Ejb3 listeners to find out when an entity is inserted, updated, deleted, etc. So, the obvious solution was to trigger this listener. The listener is an instance of org.hibernate.ejb.event.EJB3PostInsertEventListener and expects to receive PostInsertEvents.

PostInsertEvent pie = new PostInsertEvent(entity, entity.getId(), state, persister, source);
eventListener.onPostInsert(pie);

Entity is simply the entity that you saved to the database, so of course we already have that. We just need to figure out what Envers expects for the source, state, and the persister

The source is simple.  This turns out to be the Hibernate session itself, which you can obtain from the JPA EntityManager:

EventSource source = (SessionImpl)jpaEntityManager.getDelegate();

The persister is an instance of an EntityPersister, which just captures the mapping and persistence logic for the given entity.  Every entity has one, and this can be obtained from the EventSource.

The state is an object array containing the values of each property that we are persisting.  It can be obtained from the EntityPersister.

Object[] state = persister.getPropertyValuesToInsert( entity, null, source ); 

So, basically, all of that information could be obtained with just the entity and the session.  I’m not sure why they make us pass in all these additional fields when you can get them all from just the EventSource and the entity itself, but whatever.  Once we have all that information, we assemble the PostInsertEvent and pass it to an instance of the AuditEventListener that will do the work.  We don’t even need to hook into the one that Hibernate creates (from your configuration files), we can just create it “by hand”.

The complete code is this:

// instantiate the event listener
AuditEventListener eventListener = new AuditEventListener();
eventListener.initialize(HibConversation.getHibernateConfiguration());
EventSource source = (SessionImpl)jpaEntityManager.getDelegate(); EntityPersister persister = source.getEntityPersister( null, entity );

// create an insertion event for each entity you want to audit
Object[] state = persister.getPropertyValuesToInsert( entity, null, source ); PostInsertEvent pie = new PostInsertEvent(entity, shippingRate.getId(), state, persister, source);
eventListener.onPostInsert(pie);

i stuck my cucumber in it

We’re building out an application to support this high profile effort that involves something like 10 different teams.  My team’s application has over a million lines of code, 8000 classes, and Needs To Work(tm).  Or heads will roll.  And mine doesn’t like to do that, because it might get all scruffed up.  So naturally we decided to get down with the BDD and use the Cucumber.  But since we’re enterprise Java developers, things get a little more complicated.  Because that’s how we roll.

We use JRuby so our Ruby code can talk to our Java code and it’s totally awesome and all that.  But when it comes to deploying, right now we have a simple process that involves a script (using a proprietary internal tool that is kind of like SCP except it leaves me wishing it actually was) that bundles up all my deliverables and sticks it on the target server.  The application servers and Java platforms and so on are already there, usually maintained by other teams.

I wanted to build the application on a build server where the features will be run whenever code changes (using hudson to trigger the scripts).  I know what versions of Java will be available on the target servers, since there are architectural standards within the enterprise that I can count on.  And, among those standards, I can count on not having any variety of Ruby anywhere unless I put it there myself.  But that complicates our process, because I really shouldn’t be adding things to the server (which my team doesn’t own or control).  And even if I did, then the server would have an additional component that existed nowhere else which would need to be maintained and loved and cared for, and I’m not at all into that sort of thing.

So I says to myself: how do I simplify this process?  And myself says back: stick your cucumber in it.

So I did.  But what does that mean, you say?  Well, besides being what the cool Java kids are calling it these days, what I mean is that I stuck Cucumber and its dependent gems inside the JRuby jar which meant that all I needed to do was bundle a single extra jar in with the application that we build.  This makes deploying the exact same version of Ruby with the exact same gems to any machine or environment really easy: you just copy one file around the network.  Even a caveman could do it.  But TCP/Smoke Signal was notoriously slow and error prone so they usually didn’t.

The process is super easy to do.  First of all, you need to download the source code.  You can get it from github (http://github.com/jruby/jruby) or just download the source jar: http://jruby.org/download

What we want to do is build the jar-complete version of the distributable, which is a completely standalone JRuby environment encapsulated as a single jar.  If you inspect the ant build script (which is like a make file in the Java world), you’ll see the target “jar-complete” invokes a command to install additional gems defined in the “complete.jar.gems” property.  This will by default be found in the “default.build.properties” file.  I just edited it directly, and added a reference to a new property “cucumber.gems” to the end:

complete.jar.gems=${rspec.gem} ${rake.gem} {$ruby.debug.gem} ${ruby.debug.base.gem} ${columnize.gem} ${cucumber.gems}

Then we need to define the cucumber gems we want.  To ensure the build is predictable, I specify each gem and dependency along with its version:

cucumber.gems=${build.lib.dir}/cucumber-0.9.2.gem ${build.lib.dir}/builder-2.1.2.gem ${build.lib.dir}/diff-lcs-1.1.2.gem ${build.lib.dir}/gherkin-2.2.9-java.gem ${build.lib.dir}/json-1.4.6-java.gem ${build.lib.dir}/term-ansicolor-1.0.5.gem

Now you need to get the gem files and put them in the jruby_src/build_lib folder.  When you run the build, it will download the actual gem sources.  I just copied the gem files from an existing JRuby installation’s gem cache (jruby/lib/ruby/gems/1.8/cache), but you can do it any way you want.

Now run “ant dist-jar-complete” and you’ll be presented with a lovely, customized version of jruby-complete-1.x.y.jar in your jruby_src/dist folder ready for the cukes or whatever else you want.

You could then invoke it by calling:

java -jar jruby-complete-1.5.3.jar -S cucumber features

jstl tags not working in jsf 2

I was migrating a JSF application to JSF 2 and noticed that none of the JSTL tags worked anymore.  And Googling for a reason for that hasn’t been very helpful as 99% of the posts regarding “JSTL and JSF” just say “don’t”. 

The prevailing wisdom used to be that you shouldn’t mix JSTL and JSF, and once upon a time that was very true.  But JSF and JSTL has worked pretty well together since at least 1.2, and while in general you should avoid JSTL when there’s an equivalent purely JSF-based solution, there are times when it just makes more sense to use JSTL.  So I was disappointed at first to see that this didn’t appear to be working anymore.

Well, it turns out, JSF 2’s Facelets specification requires support for JSTL and both major implementations includes the taglib.xml so we’re good.  There’s no reason to rewrite all those .xhtml files just yet.

It turns out the problem was simply that the taglib namespace had changed from

      xmlns:c=”http://java.sun.com/jstl/core”

to

      xmlns:c=”http://java.sun.com/jsp/jstl/core”

I couldn’t find documentation anywhere about that, so here you go, Googlers.  Hopefully I saved a few of you a couple of headscratching minutes.

getting a generic List from a JAXB-RS Web service

If you consume a JAXB-RS web service using Jersey, you might encounter an issue when attempting to construct a generic List returned by the service.  To get a simple object, you would simply call this code:

Client client = Client.create();
Foo foo = client.resource(url).type(mimeType).get(Foo.class);

But because of type erasure, this isn’t as straightforward for returning a generic collection. As with most APIs that require type-information at runtime for generics, you have to pass in a type token. With Jersey, you can do that by passing in a concrete instance of com.sun.jersey.api.client.GenericType.

Client client = Client.create();
List listOfFoos = client.resource(url).type(mimeType).get(new GenericType<List<Foo>>() {});

This works because when you create a construct a subclass for a generic type, the class can, via reflection, obtain its own parameterized type.

Type superclass = getClass().getGenericSuperclass();
Type myTypeArguments = ((ParameterizedType)superclass).getActualTypeArguments()[0];

This is why GenericType is abstract and you are forced to instantiate a subclass with the type information you want Jersey to know about.

Not exactly an ideal solution (reified generics would be better), but it gets the job done.

generating ddl with hibernate, envers, and spring

So I have this Spring app that uses Hibernate and I’ve defined my model.  And I want to generate the DDL that I need to run to get the database in sync with my model.  I also want to get the DDL for tables needed for use with the Envers auditing framework. Here’s how you get all that:

@Autowired
LocalContainerEntityManagerFactoryBean lcemfb;

public void printUpdateScripts() {
Ejb3Configuration ejb3 = new Ejb3Configuration();
ejb3.configure(lcemfb.getPersistenceUnitInfo(),
lcemfb.getJpaPropertyMap());
Configuration config = ejb3.getHibernateConfiguration();
config.buildMappings();
AuditConfiguration.getFor(config); // include audit tables
Dialect dialect = Dialect.getDialect(config.getProperties());
DatabaseMetadata metadata;
Connection conn = null;
try {
EntityManager em = lcemfb.getObject().createEntityManager();
conn = ((HibernateEntityManager) em).getSession().connection();
metadata = new DatabaseMetadata(conn, dialect);
String[] scripts = config.generateSchemaUpdateScript(dialect,
metadata);
// String[] scripts = config.generateSchemaCreationScript(dialect);
// String[] scripts = config.generateDropSchemaScript(dialect);
for (String script : scripts) {
System.out.println(script);
}
} catch (Throwable t) {
t.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}

And LocalContainerEntityManagerFactoryBean is just your standard Spring FactoryBean for creating EntityManagerFactory instances.

<bean id="lcemfb" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="..." />
<property name="dataSource" ref="..." />
<property name="jpaVendorAdapter" ref="..." />
</bean>

JSF Action Methods Not Invoking

I decided to upgrade one of the systems I support to JSF 2.  As if that wasn’t a large enough task, I decided while I’m at it, I would switch from MyFaces to Mojarra and dump Tomahawk while I’m at it.

After removing a lot of the Tomahawk components and the ExtensionsFilter servlet filter, I started to notice that many of my forms did not work anymore.  Clicking on the commandButtons or commandLinks within those forms would simply refresh the page but would not invoke the associated action.  Unfortunately for me, I had made a few dozen other changes besides removing Tomahawk, so the relationship between the two wasn’t that obvious at the time.

I had several forms that were declared like this:

<h:form enctype="multipart/form-data" id="sidebarForm">
...
</h:form>

There was no error message: upon submitting the form from a commandLink or commandButton, the page simply refreshed.  The request never invoked the action methods.  

The fix turned out to be rather simple.  Removing enctype=”multipart/form-data” fixed the problem.

Why was that there to begin with?  Well, because I used to use the Tomahawk inputFileUpload component to allow my clients to upload files.  The Tomahawk ExtensionsFilter allowed JSF to handle multipart form submissions before.

So this might not be likely to happen to anyone else, but if you ever decide to dump Tomahawk like I did, and suddenly notice your forms aren’t working, this might be why. 

new play! module — paginate

One of the things I miss from JSF programming is the ability to use easily pluggable controls.  Play! isn’t really a component oriented framework, so it doesn’t provide that ability out of the box.  But because it’s so extensible it’s easy enough to fill in this gap.

I just uploaded a new module for the Play! framework to github.  It’s called Play—Paginate and does exactly what it sounds like it does: it gives you the ability to easily create paginating tables with minimal impact on your code.

Simply render the paginator from your controller.  You can instruct it to load the values from the database, or wrap a List you already loaded.

    public static void index() {
        Paginator entities = new ModelPaginator(TestModel.class,
"field=?", "whatever").setPageSize(4);
        render(entities);
    }

Simply render the paginator in your view by adding this stylesheet:

<link rel="stylesheet" type="text/css" media="screen" 
href="@{'/public/stylesheets/play-pagination.css'}">

And use the tags #{paginate.list}, which is a drop-in replacement for #{list}, and #{paginate.controls}, to display the pagination controls:

#{paginate.list items:entities, as:'ref'/}
#{paginate.controls items:entities /}

Then you’ll get something like this:

Play--Paginate control

Easy peasy.

dev derby 2010

This weekend, on September 11, 2010, I took part in the Dev Derby 2010.  This was a contest where teams were split up by programming language, and challenged to create as usable and fully functional a program as possible in only six hours.  Sadly, some teams, such as Justin Ko’s Team Ruby, were shorthanded.  However, the PHP and C# teams put up a good fight.

The challenge was to design a software system that could be used to match non-profit organizations with volunteer groups that offer services that match their needs.  There were a number of criteria that we had to meet, such as implementing some external API (most people chose some form of Single Sign On) and implementing all of the required features for the application.

I’m happy to announce that my team, Team Java, won the challenge.  More so, our system was the only one that worked end to end. 

Some might wonder how we did it: well, I started out doing what I do with everything else - I first identified the best tools for the job. And sometimes those tools aren’t the ones we normally use.

At work, as an enterprise Java developer on Wall Street, I normally use a particular stack of frameworks: Spring, JSF, Hibernate.  I think they are the right tools for that job.  The usual development cycle involves coding - compiling - deploying the updated code - restarting the server/process/container - relogging in and whatever else to get back to wherever you were - and then, finally, retesting.  (Of course, we employ automated test suites as well.)

For the contest, we were building a webapp, and competing against languages like Ruby, Python, and PHP that do not have the compile and deploy stages: it’s simply code - hit refresh and test.  Over the long term, for a large project, that’s not a huge advantage, but in a contest that lasts only six hours, that would have killed us.

So our secret weapon was the Play! framework.  This is a very easy to use to framework.  How easy was it? Well, none of the other six team members had even heard of Play! before the contest.  I sent out a document only a week before the challenge describing how to use it and only two people really read it.  The rest learned as we coded. 

Play! is a very agile framework that is completely stateless and recompiles changes to your codebase transparently - so it erases the advantage that dynamic languages have by not needing a compilation step.  In the meantime, we still benefit from the advantages of static typing that Java gives us, protecting us from a large number of time-wasting bugs.  Certainly, there are certain types of problem domains that are easier or only possible in dynamic languages (that’s why there are no pure static typed languages: they all offer some way to subvert the type system such as reflection or casting), but for a webapp those problems aren’t applicable.

We were allowed to use libraries that would help us in meeting the coding challenge.  Play! has a lot of plugins available for it: we used Search to implement full text search in our filters, and Scaffold to rapidly generate prototype screens.

While not a Play! plugin, we also used the java-facebook-api which was incredibly easy to use when adding Facebook Connect access to the system.

I’m very pleased with how well our use of the Play! framework turned out (even if I’m not entirely pleased with how our CODE turned out: hey, in only six hours, you have to make a few allowances… :) ).  It was a fun challenge, and I hope to try again next year.  Hopefully the Ruby team will have better luck assembling their team so I can show all the cool kids how you should truly achieve web scale webapps.  At least the Zend-spinning PHP geeks got the message.  (Luckily for C#, Microsoft was on hand with paid counselors to help them cope with the loss with promises of improvements in Visual Studio 2011 that would make them more competitive… well, not really, but they should have been!)

Playing with Play!

I’ve been playing around with the Play! framework for some time.  It’s a really great framework for the Java language that makes web programming fun again.  Well, fun for those of us who didn’t jump on the Ruby bandwagon several years ago.  They’ve already been having fun.  But now we can too, and not have to give up the things we love about Java like static typing and enterpriseyness and NullPointerExceptions.  Well, maybe not the last one…

I think Play! shows how most of the problems that people have with the Java language are mostly self-imposed and cultural.  Don’t like the code-compile-deploy test cycle?  Who doesn’t?  With Play! that isn’t a problem anymore.  Play! uses a custom classloader which compiles the classes on the fly, meaning we get the same rapid coding that Ruby on Rails and PHP developers are accustomed to: edit your source file, hit save, hit refresh on the browser, and go.

So I’ve had some fun with Play! for a while and decided to give back to the Play! community.  Today, I’ve released a module for use by the Play! community called scaffold.  It basically works like the Ruby on Rails scaffolding generators, creating some simple controllers and CRUD views based on your models.  Unlike the CRUD module that comes with Play!, this is done via static generation instead of dynamic, runtime introspection.  So, once you’ve customized your views and controllers, you can remove the module and continue without any further dependency.

Hopefully someone finds it useful.