vendredi 7 novembre 2014

How to deploy wisdom application to AWS Beanstalk using Docker


Today I'd like to demonstrate how to deploy a wisdom application on AWS BeanStalk using Docker. The goal is to be able to update your current deployed app in one maven command. Maybe you want first to check some points 

Create your Wisdom app

In order to create a new app just do :
mvn org.wisdom-framework:wisdom-maven-plugin:0.6.5:create \
-DgroupId=YOUR_GROUPID \
 -DartifactId=YOUR_ARTIFACTID \
 -Dversion=1.0-SNAPSHOT
congratulation you have now a cool app ! You can try it :
mvn wisdom:run
To package your application run :
mvn clean package
It packages your app inside a zip into target/yourApp-version.zip, this is the zip to deploy in the server.

Add a Dockerfile

If you want to use Docker, there is no magic trick, create a Dockerfile at the root directory of your app (next to your pom.xml).
FROM dockerfile/java:oracle-java8

# Add the wisdom distribution
ADD . /root/wisdom

# Expose the port 9000
EXPOSE 9000

# Volumes
VOLUME /root/wisdom/logs
VOLUME /root/wisdom/application

# Change workdir.
WORKDIR /root/wisdom

RUN touch /root/wisdom.log

# For easier handling, we dump the log, so `docker logs containerId` displays
# the log.
CMD chmod +x chameleon.sh; ./chameleon.sh stop;./chameleon.sh start; tail -F logs/wisdom.log
To include the Dockerfile inside the .zip of your packaged app you have to add the following resources tag inside your pom.xml between the build tag :
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>${project.basedir}</directory>
            <includes>
                <include>Dockerfile</include>
            </includes>
            <targetPath>${project.build.directory}/wisdom</targetPath>
        </resource>
    </resources>
    ...
</build>
run again
mvn clean package
If you open the zip file the Dockerfile is now present.

Create a cool Beanstalk application

From here I suppose you already have a AWS access and you are able to create a BeanStalk app.
  • From AWS console go to Elastic Beanstalk
  • Create a new application and fill the name and click next
  • Environment type
    • Environment tier > Web server
    • Predefined configuration > Docker
    • Environment type > single instance
  • Application version > Upload your own > select the zip file of your packaged app
  • Environment information > put what you want
  • Additional resources > just click next (or configure following your requierments)
  • Configuration details > just click next (or configure following your requierments)
  • Environment tags > just click next (or configure following your requierments)
  • And LAUNCH
That it ! Wait a moment while beanstalk creates your application. Once it's done just check your app and you should see the wisdom sample page ! If not... Sorry you probably missed something

BUT WAIT !! I DON'T WANT TO UPLOAD MY ZIP BY HAND EACH TIME !!!

I know ! As I promised, it's time to reduce the heavy uploading step by a single maven command. Take a look at Beanstalker maven plugin it does all the boring part for you.
First, follow the Setting Up Credential part to configue your access and secret key.
next add the following profile to your pom.xml
<profiles>
    <profile>
        <id>deploy</id>
        <properties>
            <beanstalker-serverId>aws.amazon.com</beanstalker-serverId>
            <beanstalker.region>eu-west-1</beanstalker.region>
            <maven.install.skip>true</maven.install.skip>
            <maven.deploy.skip>true</maven.deploy.skip>
            <beanstalk.applicationName>test</beanstalk.applicationName>
            <beanstalk.cnamePrefix>test-env</beanstalk.cnamePrefix>    //This is the first part of your env url  test-env.elasticbeanstalk.com
            <beanstalk.environmentName>Test-env</beanstalk.environmentName>
            <maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
            <beanstalk.s3Bucket>application-version</beanstalk.s3Bucket>  // The name of your S3 bucket which will contain every version uploaded
            <beanstalk.s3Key>${project.build.finalName}.zip</beanstalk.s3Key>  //The name of the zip to upload
            <beanstalk.multipartUpload>false</beanstalk.multipartUpload>
            <beanstalk.useLatestVersion>false</beanstalk.useLatestVersion>
        </properties>
        <build>
            <defaultGoal>deploy</defaultGoal>
            <finalName>${project.name}-${project.version}</finalName>
            <plugins>
                <plugin>
                    <groupId>br.com.ingenieux</groupId>
                    <artifactId>beanstalk-maven-plugin</artifactId>
                    <version>1.3.5</version>
                    <executions>
                        <execution>
                            <id>default-deploy</id>
                            <phase>deploy</phase>
                            <goals>
                                <goal>upload-source-bundle</goal>
                                <goal>delete-application-version</goal>  //delete the application version on beanstalk if it already exist (useful for snapshot)
                                <goal>create-application-version</goal>
                                <goal>update-environment</goal>
                            </goals>
                            <configuration>
                                <artifactFile>${project.build.directory}/${project.name}-${project.version}.zip
                                </artifactFile>
                                <skipExisting>false</skipExisting>
                                <environmentRef>cloudtest-env.elasticbeanstalk.com</environmentRef>
                                <optionSettings>                           //This part does nothing but I get NulPointer if I don't put anything here
                                    <setting>
                                        <namespace>aws:elasticbeanstalk:application</namespace>
                                        <optionName>Application Healthcheck URL</optionName>
                                        <value>/ping</value>
                                    </setting>
                                </optionSettings>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>
Now you just have to run :
mvn -Pdeploy
Wait and... Voila !

vendredi 3 octobre 2014

JavaFX persistence made easy with JCROMfx

Persisting model classes with JavaFX properties using hibernate is not impossible but requires some efforts. You can either use the "property access" (as described here) or map and bind all JavaFX fields to good old java fields. Both approaches have major drawbacks. Persisting JavaFX collections is almost impossible with the first approach and the second approach involve writing a lot a boiler code and to register tons of listeners to maintain the state between the JavaFX fields and their corresponding Java fields.

We recently decided to test a new persistence solution: Java Content Repository and especially the ModeShape implementation. Java Content Repository are designed to store content and metadata about this content. It looks like they are a good solution to persist application data, especially if you are manipulating lot of files and binary data.

The tree structure of a Java Content Repository allow a pretty simple mapping of graphs of Java objects. Mapping can be done either manually or using an object mapping framework. It looks like that one of the most used JCR mapping framework is JCROM. JCROM is described as a lightweight framework for mapping Java objects to/from a Java Content Repository (JCR). 

JCROM was initially designed to handle most basic Java types but it was in 2008 when JavaFX did not exist! So we forked this excellent project and tried to extend it to support JavaFX properties...and it turned out to be pretty easy, even for JavaFX collections.

So we are pleased to announce that you can use JCROMfx to map your Java objects with JavaFX properties directly to/from a JCR repository! Just annotate your JavaFX properties and you are ready to persist them. This include all basic JavaFX properties (StringProperty, IntegerProperty,...), collections (ListProperty, MapProperty) and object properties of enum or of other objects (using @JcrChildNode)

Just to give you an overview of how a bean looks like with JCROM annotation & JavaFX properties : 

Feedback is welcome :)

mardi 23 septembre 2014

FXForm2 sampler

We are pleased to announce that we provide now some FXForm2 samples using the FXSampler.

These samples were designed to help you using FXForm2 and to discover all of its features. FXForm2 can be highly customized to generate most of the forms you need; this sampler should help you to understand which features you need and how to configure your form.

We have covered some frequent cases we use here at dooApp, but feel free to ask for more examples!

How to test it?

  • Clone the FXForm2 repo
  • Run mvn exec:java in the samples directory
  • Enjoy
There is some capture




jeudi 24 juillet 2014

Wisdom framework with apache shiro

Today, we'll see how to use Wisdom framework with apache shiro to manage users authentication.

First, what is Wisdom ?

Wisdom is a young but promising Java web framework, to develope quickcly modular and dynamic web applications. You can check Wisdom website for more informations.

Unfortunaly it does not include yet users management. That's why I decided to try to embed apache shiro inside my project.

The goal is to manage multiple users with different roles and to be able to authenticate them and display different template according to their roles.

In this example I create some users during shiro initialisation, but in the next article I'll use a real database.

The sample project is available here

Now let's take a look at the code.

First the ShiroActivator class used to initialize shiro

This is just basic stuff here, it create 2 roles and 2 users. Just with this, you're done ! you can use shiro now.

Then when you submit your form login this route will be called.

As you can see it's really simple, in 3 lines of codes you're authenticated. The exceptions here will display a flash message on the view in case of error like wrong password.

Once you're logged you'll be redirected to the protected page which displays different content whether you are admin or not.

But how is the route protected if you're not logged ?
Here I do a combination of wisdom and shiro features. This is my protected route :

As you can see there is an annotation @Authenticated. It comes from wisdom. You have to specify the name of your authenticator implementation. This is mine

So in the getUsername() method, I simply use shiro to retrieve the current user, if it returns null, so you're not logged and the onUnauthorized method will be called. Otherwise the controller route will be executed correctly.

Once you're logged, you'll have a different message if you're admin or guest. To achieve this I add some if statements in my template.

As you can see on the ProtectedController, on method return we have a new UserHelper in our parameters. that mean you will be able to call methods of this class on our template to check the role of the current user.
So your template will know which statement to use depending of the user role.
This is everything you need. I let you check by yourself on the sample project the logout method cause it's not really complicated.

Have fun with this great framework !

jeudi 28 novembre 2013

FXForm: two releases and a lot of new features

We have added a bunch of cool features to FXForm, let's have a look!

Get ready for JavaFX 8

FXForm is now ready for JavaFX 8. We have adopted the following versioning conventions:

  • FXForm 2.2.x for JavaFX 2.2 (latest version: 2.2.4)
  • FXForm 8.0.x for JavaFX 8.0 (latest version: 8.0.1)
The version 8.0 of FXForm comes with the support of new types: LocalDate and Color using the new DatePicker and ColorPicker controls.


Improved data validation

We have improved the data validation layer of FXForm by adding the support of class level constraint and a finer granularity in constraint handling.

Class level constraint validation

FXForm now support class level constraints. This can be used to specify cross-field constraints.
The class level constraint violations are reported in the form. See below an example with the validation of a repeat password field:


In this case, our bean was simply annotated with the @PasswordMatch annotation which is a custom constraint validating that both password fields are equals. See Creating custom constraints for more informations about this.

Strict constraint versus warning constraint


Sometimes you want a constraint to be strict, sometimes you want it to be just a warning. FXForms allows you to specify this in your constraint declaration by using the group attribute of the constraint. By default a constraint is considered as strict. If you want your constraint to be a warning, use the Warning group provided by FXForm: 


In this case the @Max constraint will be treated as a warning. The main difference between a warning and a strict constraint is that with a warning, the model value will be updated even if the user input violates the constraint, which is not the case for as strict constraint.
Elements in the form that violates a constraint get a different style class for strict constraints and warning, so that the user feedback can be different in both cases.


In this example, the element editor is red and its label is bold when a strict constraint is violated and the element editor is orange when a warning is violated.

Multiple bean source

You can now edit multiple beans in the same form using the MultipleSourceBean


All features work as for a simple bean, including filters (reorder, exclude,...) and custom factories.

@Adapter

A custom adapter can now be specified directly on a field using the @Adapter annotation. If specified, FXForm will use the adapter provided by the annotation to bind the field property with the view property. See customizing bindings in FXForm2 for more informations about adapters.

Better handling of bound and read-only properties

FXForm introduces a notion of "editable" on the Node (see FXFormNode) which indicates whether a Node manipulated by FXForm allows the user to provide input.

FXForm now automatically disables editable nodes when bound to a property that is already bound or that is read-only. If the node is not editable (for example a Label), then it remains enabled.

New NodeSkin

FXForm now provides a NodeSkin. This NodeSkin can be used if you want to be responsible for creating the view of your form. You can then give your Node to the NodeSkin and FXForm will lookup for the required nodes and bind them to your bean. The lookup is based on the node ids. See wiki to understand how FXForm does the mapping between bean fields and nodes.

If your view is implemented in FXML, you can still use the FXMLSkin.

ListProperty support

Certainly one of the most funny (and useful!) feature of the latest release. FXForm now creates a TableView for ListProperty fields. Columns are populated automatically by analyzing the generic type of the ListProperty and extracting fields. When you click on a row, a popup shows, with -guess what- an FXForm :) This popup allows the edition of the selected item.



This feature is pretty powerful, since you can now edit pretty much your whole tree of model objects using just an FXForm. We might also add a default support for SetProperty and MapProperty in the future.

You can find the full release notes here. Thanks to usander, peterbecker and pjean for their appreciated feedback on the project.

Have fun with FXForm :)

mercredi 17 juillet 2013

Natural language search in FXML

I'm pleased to introduce "Natural Language Code Search", an IDE plugin straight out of our R&D lab that might be useful for you too!

Traceability


This plugin is the result of a collaboration between dooApp and the INRIA (French public science and technology institution). We investigated a new way to automatically recover traceability links between specifications and code elements. Establishing traceability links is very important for many reasons:

  • program comprehension,
  • maintenance,
  • requirement tracing,
  • impact analysis,... 
If you are not familiar with software traceability, have a look at this introduction on Wikipedia and at this excellent paper.

Classical approach


Most classical approaches to retrieve links between specifications (in natural language) and code involves analyzing code symbols (e.g. class names). It raises two issues:
  • the developers might not always use the exact and precise domain terminology
  • the code and the specification (e.g. a regulation) might be in different languages

Our approach


In our work, we introduced a new approach based on the analyze of the UI labels. Our idea is that the specifications lead most of the time to texts displayed to the user in the user interface and that these texts will use a precise domain terminology. Then it's possible to retrieve the UI label usage in the code, to identify the pieces of code you are looking for !

Process


We designed a three-step process:
  • Index resource bundles using Apache Lucene
  • Query the indexed bundles in natural language and retrieve the best matching labels and associated keys
  • Retrieve code elements by analyzing key usages (either statically by analyzing code or dynamically by registering stacktraces of calls to ResourceBundle.get())

IntelliJ plugin


We have tested and evaluated our approach; the promising results of the evaluation lead us to develop an IntelliJ plugin wrapping the whole process. Check it out directly from the IntelliJ repository if you want to give a try !

And what about JavaFX?


At this point, you might wonder why we published this article under the JavaFX category? 
Actually, when you are developing a JavaFX application, your bundle keys are not used directly in the code but rather in FXML files. So, our plugin also lookup for key usage in the FXML file.

So, we realized that our plugin can also be used to easily retrieve FXML files associated to user interface labels, even if the query is approximate !
Don't lose time anymore trying to identify which FXML file to open when you want to modify the user interface ! Type in what you are looking for (e.g. some words that you see in the user interface) and let the plugin find it for you!
This is really handy for developers starting working on an existing project or for maintenance.

Try it yourself


The best way to understand how this plugin can help you is to try it on your own codebase:
  • Install the plugin from IntelliJ
  • Type "Ctrl+Shit+S" to open the input dialog
  • Type your query in natural language
  • Explore the results !




jeudi 27 juin 2013

FXBinding, the binding you need

JavaFX 2 brings the Properties and Bindings concepts. If you don't know what I am talking about, I suggest you to have a look here : binding

I have an List ObservableList<XYChart.Data<Number, Number>>. I want to compute the average value of XValueProprerty for all Data contained into the list :


Without FXBinding :

See full code here

As you can see, it doesn't work :/

The binding is invalid only when the list changes, so when the XValue of a Data changes, nothing append.

I have to register every XValueProperty() into the bind() method :

See full code here

Now it works for all Data that was into the list at the beginning, but not for all added (or removed) Data after the init of the Binding

Let's make it work :

See full code here

While the complexity of your model is growing, you will have to register many listeners and the code is going to be less readable, less maintainable and less bug proof.


With FXBinding

Now let's replace our DoubleBinding by a magical FXDoubleBinding, it's 4 time step :

  • Replace new DoubleBinding() by new FXDoubleBinding()
  • Change the method name from computeValue() to compute()
  • Remove {bind(...)} and replace it by the configure() method
  • In the configure() method call addObservable() instead of bind()
See full code here

Every time the binding is becoming invalid, we will reconfigure it, so it's always a cool binding.

We will never have to add a listener even in a very complex model

An other example :

See full code here

Get FXBinding here

jeudi 20 juin 2013

ListProperty vs ObjectProperty



In the world of JavaFX, when you need to use an ObservableList with the Property pattern, you write the following :

ObjectProperty<ObservableList<T>>

To be notified when the list content is modified, you can register a ListChangeListener on the ObservableList referenced by the ObjectProperty using the getter.
You can also register a ChangeListener on the ObjectProperty to be notified when the instance of ObservableList referenced by the ObjectProperty is modified.

You will end up with something like that :




  • If you add an element or more, your ListChangeListener will be notified.
  • If you change your ObservableList instance, your ChangeListener will be called.
But if the ObservableList instance referenced by the ObjectProperty has changed, and you try to add some elements to the new list instance, you won't be notified. This is because your ListChangeListener  is still registered on the previous ObservableList instance. So in your ChangeListener you have to unregister your ListChangeListener from the old ObservableList instance and register it to the new one. It's a little bit boring to do each time...



A major issue we discovered, is that if you replace an empty ObservableList by an other empty ObservableList, the ChangeListener is not notified, as we can see on this unit test, so that you can't correctly re-register the ListChangeListener on the new instance:



Why ? cause the equals method implementation return true between the two ObservableList.

So as you see... using an ObservableList with the Property pattern, is not really cool.

This is a problem, isn't it ??



Oh Legolas wants to help us. So listen what he says:

Replace our ObjectProperty<ObservableList<T> by a ListProperty<T>. ListProperty implements both Property<ObservableList> and ObservableList and makes the whole wrapping really transparent for the developer, taking care of the previous ListChangeListener manipulation automatically !
With that, if you want to be notified when the content of the List is modified, you just need to register the ListChangeListener once.

Like that :






When you do this, adding an element will notify the listener, and changing the ObservableList instance will call the listener to. And if you add an element after changing the list instance, no problem! the listener will also be notified of the change in the new list instance. No need to register a new Listener on the new List, the ListProperty manages it for you !

This unit test show us the ListChangeListener is called 5 times, once on each change.



Now you are ready to replace your ObjectProperty<ObservableList> by ListProperty ! Have fun


lundi 1 avril 2013

FXML + FXForm2 = Developing forms has never been so easy!

We just released a major version of FXForm2 (0.2.0) that includes FXML support.


This new version introduces the brand new FXMLSkin:
  • write your model bean
  • design your form in FXML
  • FXForm2 do the rest!
How does it work? The FXMLSkin lookups all required nodes in the FXML file using their id and bind them automatically to the model bean. This skin offers a new flexible way to create complex forms without the pain of writing all the controllers logic. See wiki to know how to construct node ids.
How do I use it? form.setSkin(new FXMLSkin(form, my_file.fxml));
What about the original skins? Don’t worry, the original Default and Inline skins are still here and will still build the whole form for you! They are still very useful if you don’t need to customize your form too much and allow you to get quickly a functional form.
Feel free to give us feedback about this new feature!
Note: This release implied some architectural refactorings in FXForm2 and the form API has been slightly modified. If you have developed custom skins or custom node factories for a previous FXForm2 version, you will need to migrate them. An article will be published soon to help you do this very easily.

mardi 19 juin 2012

Logarithmic scale strikes back in JavaFX 2.0

JavaFX provides an impressive chart API that allows to draw a wide range of charts. Unfortunately the only available scale for XY charts is a linear implementation.
As we did it two years ago for javafx 1, we defined the logarithmic axis for javafx 2.
We received some requests of developpers who need to use a logarithmic axis but thay are confronted to the understanding of how axis works in javafx 2 and the impossibility to extend the NumberAxis, since it’s final in the API. So the only way to have a logarithmic axis is to extend directly the ValueAxis abstract class. Below, we’ll see how to implement all required methods to make it works. At the end you’ll be able to have this kind of chart :
So let’s create our LogarithmicAxis class that extends ValueAxis and define two properties that will represent the log lower and upper bounds of our axis. 


Then we bind our properties with the default bounds of the value axis. But before, we should verify the given range according to the mathematic logarithmic interval definition.


Now we have to implement all abstract methods of the ValueAxis class.
The first one, calculateMinorTickMarks is used to get the list of minor tick marks position that you want to display on the axis. You could find my definition below. It’s based on the number of minor tick and the logarithmic formula.


Then, the calculateTickValues method is used to calculate a list of all the data values for each tick mark in range, represented by the second parameter. The formula is the same than previously but here we want to display one tick each power of 10.


The getRange provides the current range of the axis. A basic implementation is to return an array of the lowerBound and upperBound properties defined into the ValueAxis class.


The getTickMarkLabel is only used to convert the number value to a string that will be displayed under the tickMark. Here I choose to use a number formatter.


The method setRange is used to update the range when data are added into the chart. There is two possibilities, the axis is animated or not. The simplest case is to set the lower and upper bound properties directly with the new values.


In order to have an animated axis, we should declare two timelines that will set progressively the range and use them if the animate parameter is true.



We are almost done but we forgot to override 3 important methods that are used to perform auto-ranging and the matching between data and the axis (and the reverse).


Well it’s done! I hope that this article will help you to define your own logarithmic axis and don’t hesitate to give me your feedback on this implementation.
Full code is available here :


JavaFX 2.0, Forms and Bean Validation: FXForm2 is here!


...and we are back on our technical blog!
We started last year a project called FXForm providing automatic form generation in JavaFX 1.3. We have been using this library intensively in some of our applications. JavaFX 2.0 is now a public beta. It did not took too much time until we decided to migrate FXForm to this exciting new version of the JavaFX technology. Actually, it was not really relevant to convert the old code to JavaFX 2.0 code. Most FXForm code was about binding and this part of the API has be heavily modified in JavaFX 2.0 to fit the constraints of the Java langage. So we decided to write it again from scratch — and you know what? This was quicker than expected to achieve! The new JavaFX 2.0 API is intuitive and clear. By the way, some features of the Java ecosystem where much more easier to integrate such as the JSR 303 Bean Validation support. So we are proud to announce FXForm2. Check our Get Started page to create your first form! Many features and default controls are still coming, but any help is welcome! Feel free to contact us.

Netbeans JavaFX Composer: Designing a CustomNode

The JavaFX composer is a powerful tool to design interfaces but at first it’s not really obvious how to split a complex interface into several pieces and how to handle custom nodes. In this article I’ll present the approach that turned out to be the most efficient from my own experience after some months of work with this composer.
  • Create a new desktop design file called Main.fx that contains the common design parts of your application.

  • Now let’s say we have the following model object and its manager:


  • Next step is to design the node responsible for rendering a Doo instance in the interface. Select New File > JavaFX Fragment Design File to create a DooNode.fx design file. This will create a design fragment that you can edit visually with the JavaFX composer. Let’s switch to the “Source” view and add a field to this class that will contain the Doo instance edited/rendered in our node.

  • We can now design this node and bind it to the rendered object.

  • Now the question is how to use this design file in the main interface? The composer generates a method called getDesignRootNodes() that gives you access to the parent nodes of the design file. Using this method to handle this node is not really handy since it’s not defined in any interface and it won’t be easy to switch from a renderer to another one. JavaFX define the concept of custom node through the CustomNode class. Why not using this class as parent class for our design file? Switch back to the source view and let DooNode extends CustomNode. Now just define the postinit method and insert the root nodes into the children of the custom node. Your class should look like this now:

  • Our DesignNode class is now a classical CustomNode and can be manipulated in a transparent way in the main design file. Let’s insert a flow layout into the Main design class and bind it’s content to a sequence of DooNode associated to the doo’s defined in the manager:

And that’s it! If you run the application you should see something like this:


This approach provides a handy way to split the interface into several small pieces in a transparent way and to take advantage of the composer features.
Note: the Netbeans project is available in the CustomNodeDesign file attached to this post