lunes, abril 21, 2014

JPA Tip: Inject EntityManager instead of using PersistenceContext


Almost all projects you develop with Java EE will contain a persistence layer and probably you will use JPA for dealing with SQL systems. One way to get an EntityManager is using @PersistenceContext. In this post we are going to explore the advantages of injecting EntityManager instead of using PersistenceContext annotation.

I have written the example and the explanation on github using Docstract.  You can read on https://github.com/tomitribe/community/tree/master/injecting-entitymanager.

We keep reading,
Alex
Pistol shots ring out in the bar-room night, Enter Patty Valentine from the upper hall, She sees a bartender in a pool of blood, Cries out, "My God, they killed them all" (Hurricane - Bob Dylan)

Music: https://www.youtube.com/watch?v=hr8Wn1Mwwwk

lunes, abril 14, 2014

Docstract-0.2.0 Released.


Docstract is an small java project which reads a java source file, extracts the comments between /** and */ sequentially from all over the file and stores them inside an output AsciiDoc file. The idea is not new in fact it is from https://github.com/javaee-samples/javaee7-samples/ developed by Aslak Knutsen but instead of using Ruby and inside Awestruct, this project is written in java and it is run from CLI.

Let me show you an example to understand what this application does:

This is a class which contains some comments to be processed.

And the output document looks like:

Note that in comments we are also using include macro for inserting files inside. The rules for inclusion are the next ones:

  • if include contains a java file, like first example, the whole class is read and inserted within AsciiDoc source code blocks.
  • if include contains a java file but with # symbol, like second one, the right part of # will be used as method name of given class. So for example Project#setId(String, String) will include a method of Project's class called setId and receiving two string parameters.
  • if include contains an xml file, the file is inserted "as is" within AsciiDoc source code block.
  • if include contains an xml file and between brackets there is an xpath expression, the result of that expression will be inserted.
  • any other include is left "as is", so it will be processed by AsciiDoc(tor) processor.

Also note that the include files will be resolved relative from place where the CLI is being run, typically from the root of the project.

You can use callouts inside java and xml code and the processor will render it in the proper way.

In java you can write a callout as a single line comment with callout number between <, > at start.

In xml you can write callouts between +xml+ comments and the callout number being the first word.

You can grab a runnable jar from https://bintray.com/lordofthejars/generic/Docstract/0.2.0/view/files

To render previous class we can call as:

java -jar docstract-<version>.jar --input=src/test/java/com/lordofthejars/asciidoctorfy/MM.java --output=README.adoc


And an AsciiDoc file will be generated from comments blocks.

There is one optional parameter called --baseDir. This parameter is used to set the baseDir in include macros. So for example if you set baseDir to /home/lotj/project, the include macro will be resolved to include::/home/lotj/project/src/test/java/....


New features will be added when they are required but of course feel free to clone and improve it.


We Keep Learning,
Alex.
Weiß mit dem Locken umzugehn, Und mich auf's Pfeifen zu verstehn. Drum kann ich froh und lustig sein, Denn alle Vögel sind ja mein. (Die Zauberflöte - Wolfgang Amadeus Mozart)
Music: https://www.youtube.com/watch?v=PRtvVQ1fq8s

miércoles, marzo 26, 2014

Apache TomEE + NoSQL (writing your own resources)



@Resource annotation appeared for the first time in Java EE 5 specification.  When you annotate an attribute with @Resource, it will be the container responsible of injecting the requested resource. The typical example is used with DataSource class.

That's great and you can use it with JMS as well, but what's happening to NoSQL databases, would not it be perfect to do something similar for them?

With Apache TomEE you can do it by providing your own @Resource provider class. In this post we are going to see how you write your own provider for MongoDB so you can use @Resource for MongoDB too.

The first thing to do is create the provider class, which is a simple POJO:

It is a simple POJO with a method which returns a MongoClient class (the base class for Java MongoDB driver), and setters with required parameters.

Next step is creating a file called resources.xml in WEB-INF directory. In this file we configure TomEE so he knows about the provider/class.

Notice that in this file you set the provider class and how the attributes are set. In fact you set them more or less like a properties file. So when you are are writing address 127.0.0.1, TomEE under the cover will call provider.setAddress("127.0.0.1")

The last thing to do is start using @Resource annotation with MongoDB.

So in this case we are creating a MongoClient provider because TomEE requires a no parameters constructor, but MongoClient has parameters so we need to create a provider class with a method which returns the MongoClient instance to be used.

And what really is awesome about TomEE is that you can even override your @Resource definitions from system properties, so you can do something like:

-Dmongo.address=localhost

where mongo is the id of the resources file and address the name of the field.

So you can change each of the value in an easy way depending on the environment you are pushing. And that's an awesome thing.

So now there is no excuses to not start treating NoSQL databases like SQL databases from the point of view of Java EE.

[Update] Romain notice me that with latest version of Apache TomEE you don't need a default constructor, parameters are bound directly properties as constructor params

We keep learning,

Alex.

Et j’ai sa main!, Jour prospère!, Me voici, Militaire et mari! (Ah mes amis - Gaetano Donizetti)

Music: https://www.youtube.com/watch?v=3aS6M8j3pvQ

martes, febrero 18, 2014

Learn CDI with Apache TomEE [Video tutorials]



In this post I have grouped a collection of videos I recorded some time ago to learn the basic concepts of CDI (Context and Dependency Injection) using Apache TomEE. I suggest clicking the YouTube icon to watch them directly from YouTube site and configure them in HD.

Servlets




CDI (Inject)


CDI (Scopes)


CDI (Name Qualifiers)


CDI (Qualifiers)




CDI (Alternatives)




CDI (Postconstruct)



CDI (Producer)




CDI (Events)




CDI (Interceptors)



CDI (Decorators)




We Keep Learning,
Alex.

Que vas a hacer sin mí, Cuando tú te enteres que you estoy pegao, Con el que sabe no se juega, Y si se juega con cuidado (El Cuchi Cuchi - Mayimbe)

lunes, febrero 17, 2014

Aliens have invaded Undertow

What is Undertow?

Undertow is a flexible performant web server written in java, providing both blocking and non-blocking API’s based on NIO.

Undertow has a composition based architecture that allows you to build a web server by combining small single purpose handlers. The gives you the flexibility to choose between a full Java EE servlet 3.1 container, or a low level non-blocking handler, to anything in between.

Undertow is sponsored by JBoss and is the default web server in the Wildfly Application Server.

Writing tests for Undertow

Arquillian-Container-Undertow as every Arquillian Container Extension  it take cares of you of starting, stopping and deploying the application. Also provides an Shrinkwrap resolver for creating the Undertow deployment file.

To simplify the development of tests on Undertow we have created two Shrinkwrap resolvers:
  • Embedded Servlet Deployment
  • Non-blocking handler

Maven Artifacts


Embedded Servlet Deployment


When you want to deploy a servlet/s inside Undertow, you must create a DeploymentInfo class and provide all the required information. 

For this reason Arquillian-Container-Undertow provides a Shrinkwrap resolver named UndertowWebArchive.


And then we can write our test:

Non-blocking handler


But with Undertow you can also write non-blocking handlers. For creating a non-blocking handler in Undertow you simply must create a class that implements HttpHandler interface and register it. For this reason Arquillian-Container-Undertow provides a Shrinkwrap resolver named UndertowHttpHandlerArchive.


And then we can write our test:

Configuration



You can configure the bind address and port of Undertow. By default Undertow is opened at localhost:8080.

But you can also set the bind address and the listening port.

<1> If port is set to -1, a random port between 1024 and 49151 is used.

So now you can write tests for Undertow container within the context of Arquillian.

We keep learning,
Alex.

Oh django! After the showers is the sun. Will be shining... (Django - Luis Bacalov & Rocky Roberts)

Music: https://www.youtube.com/watch?v=UX3h22aABIc

lunes, enero 27, 2014

DRY with examples on documentation. Include Java Extension for Asciidoctor.


One of the great features that Asciidoctor offers us as a writers of manuals, tutorials and documentation in general is that allows us to follow the DRY pattern. If for example you are writing a tutorial, probably you will have one part of the tutorial which will be the documentation, and another part which will be source code with examples. Asciidoctor allows us to write the documentation and include the examples directly from source code project to document.

For example:


As you can see you can include directly from source code the example and Asciidoctor will render it inside the document. Moreover if you set the language, Asciidoctor will highlight the code too.

But as you can see there is one problem with this approach, you are including the whole file, with imports, javadoc, comments, ... and maybe you only want to show a method of that class. Now with Asciidoctor you have two options:

Using lines attribute:

Which have the problem that modifying original source code also modifies the code embedded inside tutorial.

Using tags:

Which is an invasive method that requires you modify the original source code:


But now we have got another option in case your language is Java. And it is using java-semantic-asciidoctorj extension. This extension allows us to embed parts of the code by its components. That is you can set which method to add, which class, if you want to add imports or not, ... The extension only works with asciidoctorj-1.5.0.preview1 and beyond, and uses the new SPI for extensions, so you only have to add the jar extension on classpath, and the extension is automatically registered.

An example of usage of this extension could be the next one. Let's imagine that we have a class with 5 methods and we want to include only a method called mymethod which receives an String as parameter and it has no return value. Also we want to add the imports, but nothing else.

We could do something like:

Note that now we are not invading our code with comment-tags, nor fixing the position with lines of the method inside our document.

The attributes you can set in include are:
  • imports: adds the imports.
  • fields: adds the fields of the main class.
  • class: adds all the content of the main class.
  • enum=<classname>: adds the enum with the given name. The enum should be defined inside the class we are adding.
  • annotation=<classname>: same as enum but for annotations.
  • class=<classname>: same as enum but for inner classes.
  • contructor=<constructorName>(<parameterType1>,<parameterType2>, ....): adds the defined constructor. In this case we must set the constructor name and the type of each parameter. For example: MyClass(String).
  • method=<returnType> <methodName>(<parameterType1>, <parameterType2>, ...): same as constructor but for methods, which implies adding the return type. Note that it is not required to add any modifier nor throws classes.

Now we can use our classes within our documentation and by adding the required block.

This version of plugin works with Java 1.7 and before, not with Java 1.8 but it could work in some cases.

The extension is published on bintray, so to install you simply have to add bintray repository and the required dependency:

The project is hosted at: https://github.com/lordofthejars/asciidoctorj-extensions

We keep learning,
Alex.
I feel shouting ya-hoo, And me still feeling hungry, Cowabunga!!, Cookie monster went and ate the new red two. Monster Went and Ate My Red 2 - Elvis Costello & Elmo
Music: https://www.youtube.com/watch?v=KxardpBReQc

viernes, enero 24, 2014

Reporting JBehave results in AsciiDoc format.


JBehave is a framework for Behaviour-Driven Development (BDD). BDD is an evolution of test-driven development (TDD) and acceptance-test driven design, and is intended to make these practices more accessible and intuitive to newcomers and experts alike. The core of JBehave from the point of view of end users are user story files, where we define stories that our product should meet to validate that we are aligned with what our client wants. These stories are run every time a change has done in the project, so we can still ensure that nothing has been broken and we are still delivering the right thing. To validate this, a report is generated by JBehave so we can inspect the result of all stories and be sure that all is ok and if there is something wrong, which stories and why they have failed. By default the formats supported by JBehave are TXT, HTML or XML

With the advent of markup languages for writing documentation, it has sense to be able to embed this reports inside our documentation system, because the result of a build should be considered as documentation too so everyone involved directly or indirectly on the project can review the real state of the project. One of the trending markup language nowadays is AsciiDoc (and Asciidoctor). It is for this reason that I have developed a JBehave report extension so reports are written in AsciiDoc format and consequently be embedded inside another AsciiDoc document.

Let's see an example of a report generated using AsciiDoc reporter, then the report of story is included inside a master AsciiDoc document and finally rendered using Asciidoctor to HTML.


The first part of the document we can see the story that is being executed (calculator_mult_stories.story). Just below we can see the result of the story in one sentence and with an icon. In this case there is one failure in one step (see below) so an ambulance icon is used. If there would be no errors then a green rocket is used, and if any pending or ignored steps then a yellow lorry is used. After that, description, meta-information and narrative data about story is printed. Then given stories of this story is printed with the result of all of them. In this case one given story has been executed and his scenario has just passed correctly.

Note that you can navigate to the result of a given story by simply clicking on the link provided in Given Stories information section.

And the document continues with:

After user stories the scenarios of current story are printed with their results. In this example as in previous one note that examples are used and are shown as a table. Finally all steps executed with its result are printed. Note that the final step have just failed and the cause of the error is shown.

So as you can see you can embed test result inside another AsciiDoc document and make them look clear for anyone who wants to review the state of the project.

But now let's see how to use AsciiDoc reporter inside JBehave.

Reporter is released on bintray, so the first thing is to add as repository maven bintray.

Then we can add the dependency on our project:

And now we can configure StoryReporterBuilder with adoc format.

And that's all, now when you run JBehave your reports will appear on output directory as HTML or TXT but also  as AsciiDoc.

We keep learning,
Alex.
He's the guy who's the talk of the town, with the restless gun, don't shoot broad out to fool him around (Lo chiamavano Trinità - Annibale E I Cantori Moderni)
Music: https://www.youtube.com/watch?v=w5HkxTLp5jA