Friday, August 31, 2012

Realigning Java EE 7 - A promise is a cloud; fulfillment is rain.


The news came out yesterday. Java EE 7 is going to be realigned and the PaaS enablement and multi-tenancy support will be moved to Java EE 8. While the email to the EG and the linked Aquarium post are only proposals the first EG members (including me) already responded positively. I am kind of relieved now and happy to share some of the reasons I see behind it.

re·a·lign  (/ˌrēəˈlīn/)
tr.v. re·a·lignedre·a·lign·ingre·a·ligns
1. To put back into proper order or alignment.
2. To make new groupings of or working arrangements between.

What happened? You can roughly split this up into two parts.

Emerging needs in the community
The significant enhancements in simplification, usability, and functionality in updated versions of major JSRs which came with Java EE 6 are still far from perfect. We have seen a lot of requests regarding ongoing efforts to complete what has been started with EE 6. To name but a few the integration of JSON-P, the simplified JMS 2.0 APIs, further Managed Bean alignment, including transactional interceptors, a JAX-RS 2.0 client API, support for method-level validation, a much more comprehensive expression language and many many more. We are in need of a version I like to call Java EE 6.5. A comprehensive and complete version of what we have as of today.

Slow progress on the cloud side of our agend
The second part is the fact that we didn't see enough progress with the PaaS or cloud parts of EE 7 so far. As Red Hat's Pete Muir said:
We've long advocated that we, the Java EE community are not ready to standardise cloud yet, and feel this is proven by OpenShift, our Java EE cloud offering, which is working well with Java EE 6. (Source: EG Mailinglist)
And this is pretty much to the point. Even if I am an advocate of innovation with standardization this might simply be too early and as I personally see this today, the EG is missing some significant members of the Java cloud market (e.g. Jelastic). Even if Oracle is working with them to optimize their GlassFish offerings and I believe that there are first best-practices around this simply isn't enough for starting to standardize it today.
The Arabian Proverb from the title does fit this very well. At the moment all we can do is to promise stuff but we have never actually seen enough of the rain to start extracting the essentials that need to make it into the platform.

Given those two parts it is a brave and honest decision of the EG to realign Java EE 7 to the community needs and make a second try on Cloud and PaaS with the Java EE 8 Platform release scheduled for the spring of 2015.

I am nominated for the 10th JCP Annual Awards - JCP Member of the Year


What a surprise! I am nominated for the 10th JCP Annual Awards. It is especially true since I am following the JCP for a long time now and finally managed to actually contribute by officially joining it. On the one side as a German iJUG representative but also as an individual contributing to Java EE 7 as part of the Expert Group.

The JCP is the mechanism for developing standard technical specifications for Java technology. Anyone can register for the site and participate in reviewing and providing feedback for the Java Specification Requests (JSRs), and anyone can sign up to become a JCP Member and then participate on the Expert Group of a JSR or even submit their own JSR Proposals. With no member fee for personal contributors this is an outstanding chance to help shape the future of Java and bring your personal experiences into the standards backing Java.

JCP Member/Participant Of The Year - This award recognizes the corporate or individual member (either Member or Participant) who has made the most significant positive impact on the community in the past year. Leadership, investment in the community, and innovation are some of the qualities that EC Members look for in voting for this award.

I don't know if I truly have a chance of winning this category. There is great competition:
Stephen Colebourne - (for his work with JSR 310, Times-Ten)
Google - (helping to keep the Java platform open by defending the right to create independent implementations of its API specifications.)
JUG Chennai - (for being the first - and is still the only - JUG from India.)
Werner Keil - (for his work towards a new version of the JCP, also known as JCP 2.8)
London Java Community and SouJava - (for The Adopt a JSR program)
Antoine Sabot-Durand - (because of his excellent response to the rejected EC ballot for JSR 357)

Congratulations to all the nominees! Looking forward meeting you Tuesday evening, October 2, at the Annual JCP Community Party held in San Francisco.

Tuesday, August 28, 2012

Java Champions at JavaOne 2012


Everybody is doing some kind of preparation for JavaOne and Oracle OpenWorld these days already. Only a few more weeks to go and you should have your accommodation ready by now. Next on my schedule for conference preparation is to look for good content. Why not start with the talks from the most exclusive group of passionate Java technology lovers?

The Java Champions are an exclusive group of passionate Java technology and community leaders who are community-nominated and selected under a project sponsored by Oracle. Java Champions get the opportunity to provide feedback, ideas, and direction that will help Oracle grow the Java Platform. This interchange may be in the form of technical discussions and/or community-building activities with Oracle's Java Development and Developer Program teams. According to their bio page, there are 127 active JCs (plus one posthumous and four alumni).


Andres Almiray
CON5102 - Walk Through Groovy's AST Transformations
CON5100 - The Groovy Ecosystem
CON4853 - JavaFX for Business: Monitoring a Container Terminal
CON5106 - Griffon, Up Close and Personal
CON8222 - RIA Technologies and Frameworks Panel

Adam Bien
TUT3907 - Java EE 6/7: The Lean Parts
CON3906 - Stress-Testing Java EE 6 Applications Without Stress
CON3896 - Interactive Onstage Java EE Overengineering
CON3908 - Building Serious JavaFX 2 Applications

Stephen Colebourne
CON4350 - From Instants to Eras, the Future of Time in Java

Bert Ertmann
TUT5064 - Real-World Java EE 6 Tutorial
TUT5061 - Tutorial: A Practical Guide to Mixing OSGi and Java EE
CON5066 - Migrating Spring to Java EE
CON6430 - Java EE and Spring Framework Panel Discussion

Frank Greco
CON7365 - Extending Application Protocols and Java APIs over the Web with HTML5 WebSocket

Stephan Janssen
CON6439 - Progress at Parleys.com, a Java-Based E-Learning Platform
UGF10359 - GlassFish Community: The Foundation for Opportunity
BOF11369 - 2012 Duke’s Choice Award: Meet the Winners and Learn More About Why They Won

Heinz Kabutz
HOL6500 - Finding and Solving Java Deadlocks

Mattias Karlsson
BOF6540 - Java Champions and JUG Leaders Meet Oracle Executives
UGF10468 - Gooey and Sticky Bits: Everything You Ever Wanted to Know About Java

Fabiane Bizinella Nardon
UGF10462 - Autoscaling Web Java Applications: Handle Peak Traffic with Zero Downtime and Minimized Cost

Kevin Nilson
CON3363 - HTML5 Testing in All Browsers with Java
CON3362 - Moving to the Client: JavaFX and HTML5
CON8222 - RIA Technologies and Frameworks Panel

Kirk Pepperdine
CON5405 - Are Your Garbage Collection Logs Speaking to You?
BOF6540 - Java Champions and JUG Leaders Meet Oracle Executives
HOL6500 - Finding and Solving Java Deadlocks

Paul Perrone
TUT10154 - Programming Real Robots in Real Time
CON6335 - Rapid Robot Programming

Peter Pilgrim
CON4643 - Contemporary User Interface Design Patterns in JavaFX 2.2
CON4648 - Scala, JavaFX, Java EE 7, and Enterprise Integration
TUT5466 - JavaFX 2: A Java Developer’s Guide

Chris Richardson
CON4775 - Developing Polyglot Persistence Applications
CON4779 - Developing Applications with Cloud Services

Michael Santos
CON7780 - Designing Java EE Applications in the Age of CDI

Bruno Souza
UGF10468 - Gooey and Sticky Bits: Everything You Ever Wanted to Know About Java
BOF6283 - 101 Ways to Improve Java: Why Developer Participation Matters

Regina ten Bruggencate
BOF5303 - Women in Java: An Unconference
BOF11369 - 2012 Duke’s Choice Award: Meet the Winners and Learn More About Why They Won

Dalibor Topic (Alumni, now Oracle)
CON6803 - JDK 7 Updates in OpenJDK
CON3705 - OpenJDK Governance and Development Process Overview

Jim Weaver (Alumni, now Oracle)
HOL11265 - Playing to the Strengths of JavaFX and HTML5
HOL3058 - Custom JavaFX Controls

Stephen Chin (Alumni, now Oracle)
BOF5455 - Cleaner APIs, Cleaner UIs with Visage
BOF6275 - Developing Rich UI Applications with JavaFX 2: A Community Experience Exchange
BOF5503 - JFXtras Super Happy Dev BOF
CON3362 - Moving to the Client: JavaFX and HTML5
CON5486 - Grezi and GroovyFX
CON5329 - JavaFX and Scala, Like Milk and Cookies
CON8222 - RIA Technologies and Frameworks Panel
TUT5466 - JavaFX 2: A Java Developer’s Guide

Brian Goetz (Alumni, now Oracle)
CON6080 - Lambda: A Peek Under the Hood
CON4862 - The Road to Lambda

Sunday, August 26, 2012

JSF Component Libraries - Quality is more than zero bugs.


It has been a while since I last looked at the quality of the three major JSF component libraries. In December 2009 I started a comparison of the overall software quality of RichFaces, Primefaces and ICEfaces. Things have changed since than and I wanted to re-evaluate and update this since some time now. The tools I used back in 2009 are still valid but the tool-suite was a bit tricky to setup and I was simply missing the time for doing this. Thanks to the recent needs for a FAMIX 2.1 exporter I was looking again at inFusion.  It did the trick for GlassFish City posts (First, Second). But beside this it is far more. It's a tool to help with assessment of quality for your systems. It focuses on architecture and design quality and allows for quality assurance of multi-million LOC systems.
Before I give you an idea about what inFusion can do for you (implicitly by analyzing the candidates, I don't do advertising :-D) I have to thank Dr. Radu Marinescu and Dr. Adrian Trifu for providing a full functional test and evaluation license of their product to me. Without this I would not be able to show you the great software cities or blog about quality of open source projects in general like today! Please look at the resources underneath this post for further links about inFusion and the principles behind it. If you would like me to do a complete product post, let me know in the comments!

Focus of this Article
PrimeFaces, RichFaces and ICEfaces are the three mostly used JSF component libraries. Looking at the communities using it I always get the feeling that there is kind of a competition for the one and only. This is absolutely driven by the PrimeFaces lead. You can think about what he is doing and like it or not. With this post I am not trying to blame anybody about political correct behavior but trying to bring this back to some more objective views on the different projects by looking at the delivered quality.

Introduction
Before we get to the results I need to introduce you to some basics. If you feel you have seen enough of this before and everything down below is simple, feel free to proceed to the single results.
InFusion assesses software quality in a way that is build around but not centered on metrics. So it is introducing a special kind of quality model (QM) which expresses the quality of a software system in terms of some of its measurable characteristics. Quality itself can mean a couple of different things (External, Process, Internal quality). inFusion defines the notion of quality as “internal quality”, in other words the quality of the system’s architecture and design. The inFusion QM defines two decompositional layers: a layer of "quality attributes", and a layer of "design properties". The higher level overview contains a set of five "design properties" which is build up on a couple of well known "design principles" (e.g. DRY Principle and the Law of Demeter). With these principles in mind, inFusion measures deviations from most of these principles and design rules. By taking into account also the "bad smells" these deviations are quantified. All this together with the right mapping (which could be looked up in inFusion itself or the publications mentioned below) a "Quality Deficit Index" (QDI) is computed. The QDI is a positive, upwards unbound value, which is a measure of "badness" of the analyzed system's design quality respecting the overall size of the system.
Beside those high-level measures, inFusion also presents visualizations like coupling, encapsulation and design flaws on different levels (package, inheritance, class and modules).
I also like the metrics pyramid. It somehow answers the question "How does my project compare to others?".It generates a pyramid, showing key metrics for your project along with comparisons to industry-standard ranges for those numbers.It is separated into three different categories (inheritance, size and communication).
Overview Pyramid
The numbers indicate the ratios; the colors indicate where the ratios fit into the industry-standard ranges (derived from numerous open source projects). Each ratio
is either green (close to average range), blue (close to low range), or red (close to high range). The generated numbers serve a couple of purposes. First, they allow you to compare your code base to others along several dimensions. Second, these numbers indicate places where you might want to expend effort to improve code hygiene and design. However, you must understand these numbers in context.

PrimeFaces (QDI: 30,8)
Design Flaws on PrimeFaces
Founded in 2009 and having a growing user base. Head of development is Çağatay Çivici. The following analysis was run on the latest development trunk.

The total number of lines of code in the system is 44.123 (includings comments and whitespace). The Quality Deficit Index for primefaces is 30,8.
InFusion detected 12 different Design Flaws. Most impacting ones are the 24 Data Classes and the 23 Refused Parent Bequest classes. Followed by three God classes. There are quite a few duplication flaws but no cyclomatic dependencies.

Class hierarchies tend to be tall and wide (i.e. inheritance trees tend to have many depth-levels and base-classes with many directly derived sub-classes)
Classes tend to contain an average number of methods; be organized in rather fine-grained packages (i.e. few classes per package)
Methods tend to be rather long and having an average logical complexity ; call many methods (high coupling intensity) from few other classes (low coupling dispersion);

Metrics Pyramid for PrimeFaces
Given the fact, that this is a component library the NDD (Number of direct descendants) and HIT (Height of inheritance tree) might be acceptable. Complex inheritance is something that make understanding and predicting behavior more complex. Deeper trees constitute greater design complexity, since more methods and classes are involved, but enhance the potential reuse of inherited methods. NOM refers to the number of methods. This is a simple metric showing the complexity of a class in terms of responsibilities but not in terms of size of the methods.

RichFaces (QDI: 9.1)
Design Flaws on RichFaces
RichFaces originated from Ajax4jsf in late 2005. It is the widely used component library on JBoss.
The analysis was using the latest development trunk and only includes the core and the components parts.

The total number of lines of code in the system is 134.037 (includings comments and whitespace).
The Quality Deficit Index for RichFaces is 9.1.


Class hierarchies tend to be tall and of  average width  (i.e. inheritance trees tend to have many depth-levels and base-classes with several directly derived sub-classes)
Classes tend to contain an average number of methods; and are organized in rather fine-grained packages  (i.e. few classes per package);
Methods tend to: be average  in length and having an average logical complexity; call  many methods  (high coupling intensity)  from  few other classes  (low coupling dispersion);

Metrics Pyramid for RichFaces
RichFaces is doing a better job with hierarchies in general. Only the inheritance tree height is close to high range. The NOM for communication classes also is close to high. The rest is within the defined ranges which actually leads to this good QDI.

ICEfaces (QDI: 16.6)
Design Flaws on ICEfaces
ICEfaces is there since ... and 
The analysis was done against the 3.1.0-tag and includes the core, push and the components. 

The total number of lines of code in the system is 153.843 (includings comments and whitespace).
The Quality Deficit Index for ICEfaces is 16.6.
InFusion detected 16 different design flaws with 35 Data Classes, 13 God Classes, 20 SAP Breakers followed by 21 Refused Parent Bequest classes and 35 Cyclic Dependencies.We have a fair amount duplication in there, too.

Class hierarchies tend to be tall and of average width i.e. inheritance trees tend to have many depth-levels and base-classes with several directly derived sub-classes)

Classes tend to contain an average number of methods; be organized in rather fine-grained packages (i.e. few classes per package).

Methods tend to be rather long and having an average logical complexity; call many methods (high coupling intensity) from few other classes (low coupling dispersion).

Metrics Pyramid for ICEfaces
As expected, we also find a close to high inheritance tree height. Beside that only the number of methods is something to worry about.

Interpretation
This analysis is different from the one I did a few years back. I skipped looking at all the obvious stuff (e.g. checkstyle, findbugs) because everybody is running a different approach here and to me this simply isn't a comparable base for system quality in general.
Before we draw the conclusion here, let me first express that the results are no indication about weather you should use any of the candidates or not. The system design quality doesn't influence the quality of the code you produce using them. Also it shouldn't be any indicator about if the candidates are stable or bug-free. It simply focuses on the issues the developers building the products might face. On a long range this also might have an impact on you as a user. Because design problems are expensive, frequent and unavoidable. So having a lot of quality defects in a code base could influence the number of new features a team is able to deliver over time or the time for fixing bugs raises significantly. At the end, in combination with a small team this might lead to the end of a product.

All three candidates share the same problems in terms of inheritance. The reason for that is, that they are all frameworks which provide a good set of features to their clients. In combination with the size of the candidates, PrimeFaces seems to have the biggest design flaws at the moment doing the analysis. RichFaces is the leader in terms of quality far in front of any of the other two. This is what I expected to see from a RedHat community driven project. Another indicator, that working software communities are vital, skilled and kicking! ICEfaces is the only project with cyclic dependencies and an unusual amount of duplicated code. So they might end up having to fix the same error a couple of times.

I don't have a price to give away here but like to send my congratulations to the RichFaces team for a high quality product! Keep up the good work!

Here is your RichFaces-City (core & components). The green area is the old org.ajax4jsf.* bungalow :)
RichFaces-City
Resources:
inFusion Product Page
Object-Oriented Metrics in Practice (Springer, 2006)
iPlasma: An Integrated Platform for Quality Assessment of Object-Oriented Design (PDF)
Pragmatic Design Quality Assessment (Slideshare presentation)

Friday, August 24, 2012

New Article in German Java Aktuell: Java EE 7


For your reading pleasure. I mean, as long as you can read and understand German. A new article of mine was published in the mouthpiece of the German Java User Groups, Java Aktuell. This is kind of an early announcement:

The No4 (winter edition) will be available on the 5th of September and contains a lot more interesting articles. Translation of the introduction for my English speaking readers:

Java EE 7: Development for the clouds

Java EE 7 casts its shadows. Initial ideas and goals were presented at last year's JavaOne already. Meanwhile many of the contained Java Specification Requests have started and making good progress. The articles gives an overview on the objectives, the schedule and the current status of specifications and explained novelties.

You can download my article as a reprint PDF edition.

Wednesday, August 22, 2012

Rewrite to the edge - getting the most out of it! On GlassFish!


A great topic for modern application development is rewriting. Since the introduction of Java Server Faces and the new lightweight programming model in Java EE 6 you are struggling with pretty and simple, bookmarkable URLs. PrettyFaces was out there since some time and even if it could be called mature at the 3.3.3 version I wasn't convinced.

Mainly because of the fact that I had to configure it in xml. If you ever did a JSF project you know that this is something you do on top later on. Or never. With the last option being the one I have seen a lot. Rewrite is going to change that. Programmatic, easy to use and highly customizable. Exactly what I was looking for.

Getting Started
Nothing is easy as getting started with stuff coming from one of the RedHat guys. Fire up NetBeans, create a new Maven based Webapp, add JSF and Primefaces to the mix and run it on GlassFish.
First step for adding rewriting magic to your application is to add the rewrite dependencies to your project.

        <dependency>
            <groupId>org.ocpsoft.rewrite</groupId>
            <artifactId>rewrite-servlet</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
That isn't enough since I am going to use it together with JSF, you also need the jsf-integration.

  <dependency>
            <groupId>org.ocpsoft.rewrite</groupId>
            <artifactId>rewrite-integration-faces</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
Next implement your own ConfigurationProvider. This is the central piece where most of the magic happens.Let's call it TricksProvider for now and we also extend the abstract HttpConfigurationProvider. A simple first version looks like this:
public class TricksProvider  extends HttpConfigurationProvider
{
   @Override
   public int priority()
   {
     return 10;
   }

   @Override
   public Configuration getConfiguration(final ServletContext context)
   {
     return ConfigurationBuilder.begin()
        .addRule(Join.path("/").to("/welcomePrimefaces.xhtml"));
    }
}
Now you have to register your ConfigurationProvider. You do this by adding a simple textfile named org.ocpsoft.rewrite.config.ConfigurationProvider to your applications /META-INF/services/ folder. Add the fully qualified name of your ConfigurationProvider implementation to it and you are done. If you fire up your application.

The Rewriting Basics
While copying the above provider you implicitly added your first rewriting rule. By requesting http://host:8080/yourapp/ you get directly forwarded to the Primefaces welcome page generated by NetBeans. All rules are based on the same principle. Every single rule consists of a condition and an operation. Something like "If X happens, do Y". Rewrite knows two different kinds of Rules. Some preconfigured ones (Join) starting with "addRule()" and a fluent interface starting with defineRule(). This is a bit confusing because the next major release will deprecate the defineRule() and rename it to addRule(). So most the examples you find (especially the test cases in the latest trunk) are not working with the 1.1.0.Final.
Rewrite knows about two different Directions. Inbound and Outbound. Inbound is most likely working like every rewriting engine you know (e.g. mod_rewrite). A request arrives and is forwarded or redirected to the resources defined in your rules. The Outbound direction is little less. It basically has a hook in the encodeURL() method of the HttpServletRequest and rewrites the links you have in your pages (if they get rendered with the help of encodeURL at all). JSF is doing this out of the box. If you are thinking to use it with JSPs you have to make sure to call it yourself.

Forwarding .html to .xhtml with some magic
Let's look at some stuff you could do with rewrite. First we add the following to the TricksProvider:
.defineRule()
.when(Direction.isInbound()
.and(Path.matches("{name}.html").where("name").matches("[a-zA-Z/]+")))
.perform(Forward.to("{name}.xhtml"));
This is a rule which is looking at inbound requests and checks for all Patch matches {name}.html which confirm to the regular expression pattern [a-zA-Z/]+ and Forwards those to {name}.xhtml files.
If this rule is in place all requests to http://host:8080/yourapp/something.html will end up being forwarded to something.xhtml. Now your users will no longer know that you are using fancy JSF stuff underneath and believe you are working with html :) If a url which isn't matching the regular expression is requested, for example something like http://host:8080/yourapp/something123.html this simply isn't forwarded and if the something123.html isn't present in your application you will end up receiving a 404 error.

Rewriting Outbound Links
The other way round you could also add the following rule:
.defineRule()
.when(Path.matches("test.xhtml")
.and(Direction.isOutbound()))
.perform(Substitute.with("test.html"))
You imagine what this is doing, right? If you have a facelet which contains something like this:
   <h:outputLink value="test.xhtml">Normal Test</h:outputLink>
The link that is rendered to the user will be rewritten to test.html. This is the most basic action for outbound links you will ever need. Most of the magic happens with inbound links. Not a big surprise looking at the very limited reach of the encodeURL() hook.

The OutputBuffer
The most astonishing stuff in rewrite is called OutputBuffer. At least until the release we are working with at the moment. It is going to be renamed in 2.0 but for now let's simply look at what you could do. The OutputBuffer is your hook to the response. Whatever you would like to do with the response before it actually arrives at your client's browser could be done here. Thinking about transforming the markup? Converting css? Or even GZIP compression? Great, that is exactly what you could do. Let's implement a simple ZipOutputBuffer
public class ZipOutputBuffer implements OutputBuffer {

    private final static Logger LOGGER = Logger.getLogger(ZipOutputBuffer.class.getName());

    @Override
    public InputStream execute(InputStream input) {
        String contents = Streams.toString(input);
        LOGGER.log(Level.FINER, "Content {0} Length {1}", new Object[]{contents, contents.getBytes().length});
        byte[] compressed = compress(contents);
        LOGGER.log(Level.FINER, "Length: {0}", compressed.length);
        return new ByteArrayInputStream(compressed);
    }

    public static byte[] compress(String string) {
        ByteArrayOutputStream os = new ByteArrayOutputStream(string.length());
        byte[] compressed = null;
        try {
            try (GZIPOutputStream gos = new GZIPOutputStream(os)) {
                gos.write(string.getBytes());
            } 
            compressed = os.toByteArray();
            os.close();
        } catch (IOException iox) {
            LOGGER.log(Level.SEVERE, "Compression Failed: ", iox);
        }
        return compressed;
    }
}
As you can see, I am messing around with some streams and use the java.util.zip.GZIPOutputStream to shrink the stream received in this method. Next we have to add the relevant rule to the TricksProvider:
.defineRule()
.when(Path.matches("/gziptest").and(Direction.isInbound()))
.perform(Forward.to("test.xhtml")
.and(Response.withOutputBufferedBy(new ZipOutputBuffer())
.and(Response.addHeader("Content-Encoding", "gzip"))
.and(Response.addHeader("Content-Type", "text/html"))))
An inbound rule (we are not willing to rewrite links in pages here .. so it has to be inbound) which adds the ZipOutputBuffer to the Response. Also take care for the additional response header (both) unless you want to see your browser complaining about the content I have mixed up :) That is it. The request http://host:8080/yourapp/gziptest now delivers the test.xhtml with GZIP compression. That is 2,6KB vs. 1,23 KB!! Less than half of the size !! It's not very convenient to work with streams and byte[]. And I am not sure if this will work with larger page sizes in terms of memory fragmentation, but it is an easy way out if you don't have a compression filter in place or only need to compress single parts of your application.

Enhance Security with Rewrite
But that is not all you could do: You could also enhance the security with rewrite. Lincoln has a great post up about securing your application with rewrite. There are plenty of possible examples around how to use this. I Came up with a single use-case where didn't want to use the welcome-file features and prefer to dispatch  users individually. While doing this I would also inspect their paths and check if the stuff they are entering is malicious or not. You could either do it with the .matches() condition or with a custom constraint. Add the following to the TricksProvider:
Constraint<String> selectedCharacters = new Constraint<String>() {
        @Override
        public boolean isSatisfiedBy(Rewrite event,
                EvaluationContext context, String value) {
            return value.matches("[a-zA-Z/]+");
        }
    };

And define the following rule:
.defineRule()
.when(Direction.isInbound()
.and(Path.matches("{path}").where("path").matches("^(.+)/$")
.and(Path.captureIn("checkChar").where("checkChar").constrainedBy(selectedCharacters))))
.perform(Redirect.permanent(context.getContextPath() + "{path}index.html"))
Another inbound modification. Checking the path if it is has a folder pattern and capturing it in a variable which is checked against the custom constraints. Great! Now you have a save and easy forwarding mechanism in place. All http://host:8080/yourapp/folder/ request are now rewritten to http://host:8080/yourapp/index.html. If you look at the other rules from above you see, that the .html is forwarded to .xhtml ... and you are done!

Bottom Line
I like working with rewrite a lot. It feels easier than configuring the xml files of prettyfaces and I truly enjoyed the support of Lincoln and Christian during my first steps with it. I am curious to see what the 2.0 is coming up with and I hope that I get some more debug output for the rules configuration just to see what is happening. The default is nothing and it could be very tricky to find the right combination of conditions to have a working rule.
Looking for the complete sources? Find them on github. Happy to read about your experiences.

Where is the GlassFish Part?
Oh, yeah. I mentioned it in the headline, right? That should be more like a default. I was running everything with latest GlassFish 3.1.2.2 so you can be sure that this is working. And NetBeans is at 7.2 at the moment and you should give it a try if you haven't. I didn't came across a single issue related to GlassFish and I am very pleased to stress this here. Great work! One last remark: Before you are going to implement the OutputBuffer like crazy take a look at what your favorite appserver has in stock already. GlassFish knows about GZIP compression already and it simply can be switched on! Might be a good idea to think twice before implementing here.

Monday, August 20, 2012

Resource Bundle Tricks and Best Practices


Today is resource bundle day. This is the most well known mechanism for internationalization (i18n) in Java in general. Working with it should be a breeze. But there are many little questions that come up while getting your hands dirty with it. If you are feeling the same, this post is for you.

Basics
The java.util.ResourceBundle defines a standardized way for accessing translations in java. They contain locale-specific resources. Resource bundles belong to families whose members share a common base name, but whose names also have additional components that identify
 their locales. Each resource bundle in a family contains the same items, but the items have been translated for the locale represented by that resource bundle. Those are key/value pairs. The keys uniquely identify a locale-specific object in the bundle.

The most basic example uses the following familiy:
Messages.properties
Messages_de.properties
Messages_en.properties

If you need to query a bundle in your application you simple call the
ResourceBundle bundle = ResourceBundle.getBundle("Messages");
method and query the returned bundle:
bundle.getString("welcome.message");
If you are wondering which Locale is going to be used here, you are right. The String constructor implicitly uses Locale.getDefault() to resolve the language. That might not be what you want. So you should ResourceBundle bundle =
ResourceBundle.getBundle("Messages", locale);
You cannot set the locale after you have retrieved the bundle. Every ResourceBundle has one defined locale.

Naming stuff
Some thoughts about naming. Name the bundle properties after their contents. You can go a more general way by simply naming them "Messages" and "Errors" etc. but it also is possible to have a bundle per subsystem or component. Whatever fit's your needs. Maintaining the contents isn't easy with lots of entries. So any kind of contextual split makes developers happy. The bundle properties files are equivalent to classes; Name them accordingly. And further on you should find a common system for naming your keys. Depending on the split you have chosen for the property files you might also introduce some kind of subsystem or component namespace with your keys. Page prefixes are also possible. Think about this wisely and play around with it. You are aiming to have least possible dublicates in your keys.

Encapsulating
As you have seen, you use the string representation of the bundles a lot. The fact that those are actually file-names (or better class-names) you would be better of with a simple enum which encapsulates everything for you:
public enum ResourceBundles {
    MESSAGES("Messages"),
    ERRORS("Errors");
    private String bundleName;  

    ResourceBundles(String bundleName) {
        this.bundleName = bundleName;
    }

    public String getBundleName() {
        return bundleName;
    }

    @Override
    public String toString() {
        return bundleName;
    }
}

Having this you simply can write
ResourceBundle bundle = ResourceBundle.getBundle(MESSAGES.getBundleName());

Java Server Faces and ResourceBundles
To use resource bundles in your jsf based application you simple have to define them in your faces-config.xml and use the shortcuts in your xhtml files.

<resource-bundle>
<base-name>Messages</base-name>
<var>msgs</var>

 <h:outputLabel value="#{msgs['welcome.general']}" />

JSF takes care of the rest. What about parameter substitution? Think about a key-value pair like the following:
welcome.name=Hi {0}! How are you?
You can pass the parameter via the f:param tag:
 <h:outputFormat value="#{msgs['welcome.name']}">
         <f:param value="Markus" />
 </h:outputFormat>
To change the language you have to set a specific locale for your current FacesContext instance. It's best to do this via a value change listener:

    public void countryLocaleCodeChanged(ValueChangeEvent e) {
        String newLocaleValue = e.getNewValue().toString();
        //loop country map to compare the locale code
        for (Map.Entry<String, Object> entry : countries.entrySet()) {
            if (entry.getValue().toString().equals(newLocaleValue)) {
                FacesContext.getCurrentInstance()
                        .getViewRoot().setLocale((Locale) entry.getValue());
            }
        }
    }

Resource Bundles in EJBs
JSF obviously is very easily integrated. What about using those bundles in EJBs? It is basically the same. You have the same mechanisms in place to get hand on the bundle and use it. There is one thing that you should keep in mind. You probably don't want to always use the default locale. So you have to find a way to pass the locale down from the UI. If you are thinking about @Injecting the MessageBundle via a @Produces annotation you have to think more than one time. Especially if you are working with @Stateless EJBs. Those instances get pooled and you have to pass the Locale to any business method that needs to know about the current Locale. You typically would do this with a parameter object or some kind of user session profile. Don't add the Locale as method signature all over.

Resource Bundles from the DB
In most of the cases I see you need to pull the keys from a DB. Given the inner workings of the ResourceBundle (one "class" per locale) you end up having to implement the logic in your own ResourceBundle implementation. Most of the examples you find on the web do this by overriding the handleGetObject(String key) method. I don't like this approach, especially since we have a far better way using the ResourceBundle.Control mechanism. Now you can override the newBundle() method and return your own ResourceBundle implementation. All you have to do is to set your own Control as a parent with your DatabaseResourceBundle:

public DatabaseResourceBundle() {
        setParent(ResourceBundle.getBundle(BUNDLE_NAME,
        FacesContext.getCurrentInstance().getViewRoot().getLocale(), new DBControl()));
    }
The DBControl returns MyResourceBundle which is a ListResourceBundle:

protected class DBControl extends Control {

        @Override
        public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
                throws IllegalAccessException, InstantiationException, IOException {
            return new MyResources(locale);
        }

        /**
         * A simple ListResourceBundle
         */
        protected class MyResources extends ListResourceBundle {

            private Locale locale;

            /**
             * ResourceBundle constructor with locale
             *
             * @param locale
             */
            public MyResources(Locale locale) {
                this.locale = locale;
            }

            @Override
            protected Object[][] getContents() {
                TypedQuery<ResourceEntity> query = _entityManager.createNamedQuery("ResourceEntity.findForLocale", ResourceEntity.class);
                query.setParameter("locale", locale);

                List<ResourceEntity> resources = query.getResultList();
                Object[][] all = new Object[resources.size()][2];
                int i = 0;
  for (Iterator<ResourceEntity> it = resources.iterator(); it.hasNext();) {
  ResourceEntity resource = it.next();
  all[i] = new Object[]{resource.getKey(), resource.getValue()};
  values.put(resource.getKey(), resource.getValue());
   i++;
  }
                return all;
            }
        }
    }
As you can see, this is backed by an entitymanager and a simple ResourceEntity which has all the fields and NamedQueries necessary for building up the different bundles.
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column(name = "i18n_key")
    private String key;
    @Column(name = "i18n_value")
    private String value;
    @Column(name = "i18n_locale")
    private Locale locale;
By putting the bundles in a private Map<String, String> values = new HashMap<String, String>(); you also have a good way of caching the results after the bundles have been build up for the first time.
This still isn't the best solution as ResourceBundles have a way of caching. But I might dig into this in more detail later. Until now, this bundle is cached forever (or at least until the next redeployment).

Rewrite as Language Switch
On last thing to mention is that you also could have some fancy add-ons here. If you already have the JSF language switch magic in place it is simple to add ocpsoft's rewrite to your application. This is a simple way to encode the language in the URLs like this http://yourhost.com/Bundle-Provider-Tricks/en/index.html
All you have to do is to add rewrite to the game by adding two simple dependencies:
<dependency>
            <groupId>org.ocpsoft.rewrite</groupId>
            <artifactId>rewrite-servlet</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.ocpsoft.rewrite</groupId>
            <artifactId>rewrite-integration-faces</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
Rewrite needs you to add your own ConfigurationProvider which is the central place to hold your rewriting rules. Implement the following:
public class BundleTricksProvider extends HttpConfigurationProvider {

    @Override
    public Configuration getConfiguration(ServletContext context) {
        return ConfigurationBuilder.begin()
                // Locale Switch
                .addRule(Join.path("/{locale}/{page}.html").to("/{page}.xhtml")
                .where("page").matches(".*")
                .where("locale").bindsTo(PhaseBinding.to(El.property("#{languageSwitch.localeCode}")).after(PhaseId.RESTORE_VIEW)));
    }

    @Override
    public int priority() {
        return 10;
    }
}
Next is to add a file named "org.ocpsoft.rewrite.config.ConfigurationProvider" to your META-INF/services folder and put the fully qualified name of your ConfigurationProvider implementation there. One last thing to tweak is the logic in the LanguageSwitch bean. Rewrite isn't able to trigger a ValueChangeEvent (as far as I know :)) so you have to add some magic to change the Locale while the setter is called. That's it .. very easy!

This is all for today. Find the code on github.com. Happy to read about your thoughts.

Saturday, August 18, 2012

JBoss Community Leader: Documentation category


Thought I share this one with you :) During my visit to JUDCon we recorded an interview about Arquillian and my engagement with the project. Thanks again for the great time there! It was a pleasure!

Friday, August 17, 2012

The Heroes of Java: Sacha Labourey


The "Heroes of Java" series has a run these days. Sacha took some of his precious time and joint as no. 19. Most of you know him from his JBoss time.

Sacha Labourey
founded the European headquarters for JBoss and, as GM for Europe, led the strategy and partnerships. In 2005, he was appointed CTO of JBoss, Inc. and as such, oversaw all of the JBoss engineering activities. After JBoss was acquired by RedHat in 2007, Sacha became co-General Manager of Red Hat's middleware division. He ultimately left Red Hat in April 2009 and he formed CloudBees, Inc. in April 2010.

General
Who are you?
My name is Sacha Labourey, I live in Switzerland and I was born 12 years ago when I joined the JBoss project to contribute its first clustering implementation. I immediately felt in love with middleware, open source and Java. I have now decided to work on the future of middleware and make Java developers cool again, and that happens in the cloud.

(Oh, and don't worry, JBoss' clustering implementation has been totally rewritten at least twice since then, so you are now at no risk of using JBoss AS. )

Your offical job title at your company?
CEO

Do you care about it?
You bet, I'd better! This is really a great passion and I am very lucky to work with some of the brightest guys in that industry, so this is very stimulating.

Do you speak foreign languages? Which ones?
Well, English would be a true foreign language since my mother tongue is French. I also studied German for 8 years but haven't practiced much so it would need a refresh. I also try to learn Rumantsch (Surmiran) to understand my wife when I'm on vacation in the Alps (http://en.wikipedia.org/wiki/Romansh_language) but I am struggling.

How long is your daily "bootstrap" process? (Coffee, news, email)
The first thing I do in the morning when I am barely awake is to read my emails on my phone, followed by various RSS feeds (IT, general news, etc.). That way, I start thinking about things in a calm way while getting ready and having breakfast.

Twitter
You have a twitter handle? Why?
Yes, @SachaLabourey. Only because everybody obviously care about what I think about all things, right? ;) I actually think this is a great way to get a drum beat of what happens in our business.

Whom are you following in general?
There are no hard rules but from a business standpoint, I typically follow partners, competitors and rain makers. From a personal standpoint, I follow some of the leading News channels and a bunch of crazy and/or funny people.

Do you have a personal "policy" for twitter?
"If you are unsure whether you should send a tweet, don't send it."

Does your company restricts or encourages you with your twitter ussage? CloudBees encourages usage of social media, whatever they are. We currently don't have a policy simply because I trust people common's sense by default and I don't like to "design by exception".

Work
What's your daily development setup? (OS/IDE/VC/other Tools)
Mac or Windows, Office and Google Docs and Chrome ;) As a CEO, I don't have the opportunity to code anymore (outside of the demos I do). But that's probably a good thing for our customers...

Which is the tool providing most productivity to your work?
"The Cloud"! All of the tools I am using are SaaS tools, Google, Evernote, Dropbox, etc. I can take a brand new laptop with just a browser and be ready to work in 2 minutes, anywhere, anytime.

Your prefered way of interacting with co-workers?
Face-to-Face obviously, but since we are a very distributed company (our team is spread in 7 countries!), we rely extensively on Skype and GoToMeeting. From time-to-time, I also like to use Skype Videos - except when my correspondant in California (9h behind me) still wears his pyjama obviously.

What's your favorite way of managing your todo's?
It keeps changing :) the only stable process I've been using is to consider e-mails in my Google Mail's Inbox to be TODOs until they are archived. For non-email related todo's, I've been using plenty of tools, and I have to admit nothing beats a small piece of paper on my desk.

If you could make a wish for a job at your favorite company: What would that be?
I have absolutely no idea, I really like what I am currently doing at CloudBees.

Java
You're programming in Java. Why?
Because it was hip and fun back at the end of the 90's and a lot of the projects at my school had to be done in Java. So I guess I was just part of the Java wave to start with. But I decided to stick to it because I think the innovation that has been put in the JVM makes it the strongest most complete runtime platform ever built. Also, from a business standpoint, SUN has been able to create one of the most successful IT ecosystem that ever existed, with not just partners, but also with competitors aiming at improving the overal quality of the Java ecosystem - and this is truly unique.

What's least fun with Java?
The weight it took over time and its startup overhead. Yet, now that the JVM is über-efficient, I think a lot of the innovation is taking place in specific frameworks and new languages, and not so much in Java-as-a-language per se, and that's fine I guess, but it would be great to see more of that innovation come back into this shared DNA that the Java language is. For this, Oracle has to find a way to get all people around the table to actively collaborate again.

If you could change one thing with Java, what would that be?
The lack of a proper CLR in Java early on has slowed down the creation of new languages, hence new innovation, some which could have been retrofitted in Java.

What's your personal favorite in dynamic languages?
I know that if I wanted to look smart I should tell you all about the sophisticated and fancy dynamic languages out there, but I actually think that the HTML5 environment, with JavaScript, CSS, DOM, JSON is amazingly powerful - we are truly moving away from server-side generated pages for the most part.

Which programming technique has moved you forwards most and why?
To me, developing in the cloud has been the most impressive experience. In just a few click from a laptop, you can start a new project, store your code, perform continuous development, continuous deployment, static code analysis, web UI testing, etc. without ever installing anything, without ever having to configure anything. When people initially read about PaaS, they don't necessarily see what's the big deal about it. Until they try it! Once you've tried it, it is hard to look back, it is like asking a Samsung S3 or iPhone 4S owner to go back and use a fancy 2005 Nokia - it hurts.

What was the biggest project you've ever worked on?
JBoss AS was probably the biggest one. In the 2.x to 4.x series, I really knew a lot about it. As such, I really enjoyed doing technical support when JBoss was still a tiny company. Trying to understand what was going wrong for a customer was like a mini-adventure.

Which was the worst programming mistake you did?
I don't remember, I am probably still in denial about it...

Thursday, August 16, 2012

GlassFish City Revisited


More than a year ago I looked at GlassFish from a very high level point of view and did a 3D analysis of the source code. Today I feel like updating the model and re-running the analysis.

The way we are looking at Code
On a day to day basis we are looking at source code. Classess, Packages, Deployment Units. And for what you usually do, this is far than enough. But there are rare cases where you have to get hand on very big code-bases. Need to navigate stuff or find a way to identify problems very quickly. In these cases alternate views onto your problem might help. CodeCity is one of those tools. Developed back in 2009 you can still use it if you are able to generate a FAMIX 2.1 format which is the input for CodeCity. CodeCity is an integrated environment for software analysis, in which software systems are visualized as interactive, navigable 3D cities. The classes are represented as buildings in the city, while the packages are depicted as the districts in which the buildings reside. But let's start with some basics.

My first post about this kind of visualization featured a tool called inFusion. This was available for free or at least as a trial to generate the needed models for CodeCity. As of today it is only available as a demo version and a licensed versions. The first one isn't able to export the mse models. Thanks to the team at intooitus I was granted a license to be able to bring you the GlassFish city update. But please don't think that inFusion is only good for that. It's an eclipse based tool which provides intuitive insights, semantics-rich interpretations and matching refactoring recommendations, which identify and address inadequate underlying design decisions. So I will feature some more details about it later on this blog.

GlassFish
For now lets get back to the post. May I introduce GlassFish. More precisely the com.sun.*, org.glassfish.* and javax.* classes and packages that are contained in GlassFish 3.1.2-b15 which was shipped a few months back. On a high level overview (subsystems) this looks like this (thanks to Headwaysoftware for Structure101) :
The complete GlassFish is bigger and also contains work by apache, netbeans and others. Roughly 930K Lines of Code (No comment, no blank lines) and 10.824 Classes overall in 845 packages. The biggest classes are:
com.sun.ejb.containers.BaseContainer
org.apache.catalina.core.StandardContext
com.sun.jdo.spi.persistence.support.sqlstore.SQLStateManager
org.apache.catalina.connector.Request
com.sun.enterprise.deployment.EjbDescriptor

GlassFish Skyline
The skyline view is the most impressive one to me. I didn't publish it one year back but without any intention.
The biggest buildings represent the biggest classes from above. Starting right to left. To give you an impression, the StandardContext has 6341 lines of code (which is represented by it's dark blue color), it has a "height" of 390 methods and length and width are calculated based on the 114 attributes. The base container has a "height" of 198 methods but it's width and length are bigger based on 134 methods.

Overview Pictures
Now you know the basics about "city building". Time to look at the overview. The complete city from the front looks like this:
From the back:
And a view from the top which is probably the most commonly known one because many tools tend to use this kind of perspective:

Special Areas
Back in the days I started to look into some special areas. One was the Apache district. The Apache towers are more or less the same. You have some additional areas where you find Apache code. Those are highlighted in green and represent any occurrence of org::apache packages in the sources.


Another interesting area (at least to me) is the weld integration glue code (again, the little green in there). Remarkably less compared with the impact CDI has on the platform. I agree, that this simply is the "glue" and not the complete CDI implementation.

One last area of interest. The complete CMP container spreads over different packages. This is functionality which is going to be pruned with Java EE 7. Your last chance to take a look at it is here:

UPDATE 20.08.
Peter asked for tests! Here we go. Highlighted is everything that contains the word "tests". Have fun!

Monday, August 6, 2012

The Heroes of Java: Çağatay Çivici


Staying strong, the "Heroes of Java" series reaches the 18th edition. This time it is about Çağatay Çivici who is the inventor and lead developer of my favorite JSF component library Primefaces.

Çağatay Çivici
is a member of JavaServer Faces Expert Group, the founder and project lead of popular PrimeFaces Component Suite and PMC member of open source JSF implementation Apache MyFaces. He’s a recognized speaker in international conferences such as JavaOne, SpringOne, JAX, Jazoon, Confess, JSFSummit and many local events such as JUGs. Cagatay is also an author and technical reviewer of couple of books regarding web application development with Java and JSF. As an experienced trainer, he has trained over 300 developers on Java EE technologies mainly JSF, Spring, EJB 3.x and JPA. Cagatay is currently working as a consultant, mentor and instructor for Prime Teknoloji in Turkey.

General Part
Who are you?
I'm Çağatay Çivici, the founder and lead developer of PrimeFaces, expert group member of JSF 2.x Specification and PMC member of Apache MyFaces. I'm the co-founder of Prime Teknoloji, a company specialized in Java EE and Agile Mentoring. I'm a regular speaker in Java Conferences where I really enjoy meeting-reuniting people face to face on my social network all around the world at one place.

Your offical job title at your company?
I like having various titles that I can use for different cases such as co-founder on my office id card, principal consultant when I do consulting and CEO when I want it to sound cool.
My colleagues and PrimeFaces users call me Optimus Prime though.

Do you care about it?
Not really, as you can see from my previous post. I especially do not care about employee title hierarchy in big corporates.
Never spent time to understand those.

Do you speak foreign languages? Which ones?
I'm a native Turkish speaker and I also speak English fluently. I lived in London for 2 years which helped me to learn how to deal with various accents. Nowadays I'm self learning Spanish.

How long is your daily "bootstrap" process? (Coffee, news, email)
When I woke up with an idea, there is no bootstrap, I go straight to my laptop and start coding. For a regular day I start with a coffee with milk followed by tea afternoon.
I'm an NBA fan since my childhood and during season I start the day with watching NBA highlights.
After that I check my emails, do quick replies if applies and organize some to reply later.
I then check PrimeFaces forum, twitter, facebook group to see what community is up to before beginning to work.
To keep my focus, I shut down any kind of notification during working like mail, twitter and anything else that changes the state of my screen automatically.

Twitter
You have a twitter handle? Why?
Main reason is PR for work [@cagataycivici]. Most of my tweets are about PrimeFaces, well, @primefaces also has an official account but I tweet things that can be considered as "under the hood" activity.
I also use "PrimeFaces" search a lot to get the feedback from twitter users about PrimeFaces.

Whom are you following in general?
My friends and my colleagues mostly to see how they are doing. I'm not really a good follower, usually I just tweet things and just have a quick look (not read) at people I follow.

Do you have a personal "policy" for twitter?
We've asked our employees not to tweet about our clients, it is not professional for business.
I also follow the same policy, I believe twitter can have be dangerous if you don't know how to use it effectively. Reverting a bad tweet might not always work once it is out. I really think sometimes alter egos of people do the tweets.

Does your company restricts or encourages you with your twitter usage?
It is free will, almost everyone in our company has a twitter account for personal use.

Work
What's your daily development setup? (OS/IDE/VC/other Tools)
I use macbook pro for development and NetBeans as my IDE. I've been a NetBeans fan for a long time and have started good relations with NetBeans team after they bundled PrimeFaces in NetBeans. I use maven to build things and subversion/git for version control. I only start Windows as a VM for Internet Explorer testing. I also use development tools of browsers like firebug a lot as well.
Regarding servers I have glassfish, tomcat and jetty. For the past years, I lean towards being a front end developer so I don't use heavy duty server side stuff for some time. I can't really remember the last time I've written a code to persist an object to a datastore however I've written javascript-css half an hour ago.

Which is the tool providing most productivity to your work?
NetBeans for sure, it has all the features I want from an IDE. For Java EE development, it is just great and productive. To build things I use maven, I'm still on 2, well it works so why change it :) Firebug is also great as I can do the front end visuals with it and then move it back to PrimeFaces Core.

Your prefered way of interacting with co-workers?
Chat. Our main office is in Istanbul and majority of our team is based there so for meetings and discussions I use IM tools. Sometime emailing works as well.

What's your favorite way of managing your todo's?
For personal todo, I was writing things on a piece of paper for a long time, lately I got an ipad and using a couple of apps on that.
For business, we are using JIRA internally in our company. For PrimeFaces todos, we use google code issue tracker, it is not excellent but does the job, no complaints.

If you could make a wish for a job at your favorite company: What would that be?
My wish already came true already, my favorite company is Prime Teknoloji and I enjoy being self-employed.

Java
You're programming in Java. Why?
It was the first language I've learned in university and there were and still are many java developer jobs all around the world. So my choice is not technical but mainly due to popularity of Java.

What's least fun with Java?
Strongly typed nature, lack of modular programming and class reloading on runtime. Without using tools like jRebel and an effective development environment, working with java could be a pain.

If you could change one thing with Java, what would that be?
I'm a fan of javascript so would like to do things I can do in javascript such has passing any type of object to a method, adding removing properties easily. So basically any feature in Javascript that is not possible in Java.

What's your personal favorite in dynamic languages?
Javascript for sure, at my job, I code more javascript than java. With latest frameworks like jQuery, it is more fun than ever. I never had the chance/time to work with ruby, groovy or another language. Just played with them a bit but it is not enough to decide a favorite without going to real development.

Which programming technique has moved you forwards most and why?
I'd say DRY and KISS. I usually don't care about DRY part initially and focus on KISS part to keep things simple. I think being simple is one of the reasons why PrimeFaces is so popular. After implementing the requirement, I do a couple of refactoring phases to apply DRY.

What was the biggest project you've ever worked on?
When I was a junior developer, I worked for a giant government project. I quit after a year and not sure what happened to the project.

Which was the worst programming mistake you did?
Any bug in PrimeFaces is a big programming mistake for me and my team :)

Thursday, August 2, 2012

Oracle Public Cloud Java Service with NetBeans in Early Access


Who expected that to happen: Oracle is working on a public cloud offering and the signs of the approaching official launch are there. Nearly a year after the official announcement I was invited to join the so called "Early Access" program to test-drive the new service and give feedback. Thanks to Reza Shafii who is the product manager in charge I have the allowance to dish the dirt a bit. Even if I am not allowed to show you some screenshots from the UI there is plenty to talk about. And today I am willing to give you a first test-drive of the developer experience with NetBeans.

Preparations
As usual there are some preparations to do. Get yourself a copy of the latest NetBeans 7.2 RC1 Java EE edition. This is the publicly available IDE which has oracle cloud support. It was dropped from the 7.2 Final because ... yeah ... the OPC isn't public and nobody wanted to see unusable features in a final release. So the first secret seems to be lifted here. When OPC launches we will see a 7.3 release popping up (concluded from this test-specification). Another useful preparation is to download and install the corresponding WebLogic 10.3.6 for local development. And that is the second surprise so far. Oracle Public Cloud Java Service will be a Java EE 5 service. At least for the GA. And absolutely it doesn't make any sense to stay at this version. So it is really save to say that the WebLogic 12c which has Java EE 6 support will follow sometime next. All set. Fire up NetBeans.

Create your Java EE Application
All you have to do now is to create a new Java EE Web Application with NetBeans. Give it a name (I'm calling it MyCloud) and add a new local WebLogic 10 server in the "Add..." Server dialogue. Don't forget to chose Java EE 5 as EE version. Let's add JSF 2.0 and Primefaces 3.2 on the Framework tab. Click "Finish". If NetBeans is complaining about missing server libraries, let it deploy them. That's it for now. Right Click your app and Run it. This will fire up your local WebLogic domain and point your browser to http://localhost:7001/MyCloud/ or whatever your app is called. as you can see, the Primefaces components are also working. Not spectacular.

Add Cloud...
Next you have to add some cloud. Switch to the services tab, right click on the cloud node and select "Add Cloud...". Chose "Oracle Cloud" and click Next. You will have to fill in a couple of information here.
  • Identity Domain. The individual or group identity of your Oracle Cloud account. 
  • Java Service Name. The name of the Java Service.
  • Database Service Name. The name of the Database Service.
  • Administrator. Your identity as Oracle Cloud administrator.
  • Password. Your Oracle Cloud administrator password.
  • SDK. Path to your local copy of the Oracle Cloud SDK. Click Configure to browse for this file.       
Lucky you, you don't have to care about the details here. You get hand on the information after the successful account creation. And it is pretty straight forward to figure out what is meant here if you get a hand on the cloud finally. Some more words about the identity domain.When setting up Oracle Cloud services, a service name and an identity domain must be given to each service. An identity domain is a collection of users and roles that have been given specific privileges to use certain services or manage certain services in the domain. So it basically is kind of a secure storage.
Click "Finish" if everything is filled out correctly. NetBeans verifies your provided information against the OPC and you now have the Oracle Cloud in it. Additionally you find a new server "Oracle Cloud Remote" which is actually the server hook you have to specify in your projects run configuration. Go there. Switch it from local "Oracle WebLogic Server" to "Oracle Cloud Remote" and hit OK. Now you are all set for the cloud deployment.

Run in the Cloud...
Right click and "Run" your project. You see a lot of stuff happen. First of all NetBeans is doing the normal build and afterwards is starting the distribution. First of all this is uploading the bundle (MyCload.war) to the cloud. It get's scanned for viruses and needs to pass the Whitelist scan (more on this later). If both succeeds the deployment happens and your application is opened in your system's default browser:

That was a typical development round-trip with the Oracle Public Cloud Java Service. Develop and test locally deploy and run in the cloud.

Some more NetBeans goodies
But for what is the "Oracle Cloud" entry in the Cloud services good for? For now this is very simple. You can use it to access your deployment jobs and the according log-files.
Every deployment gets a unique number and you see the deployments status. Together with the log excerpts you are able to track that down further. Let's try some more. Add a servlet named "Test" and try to use some malicious code ;)
    System.exit(0);
First indication that something is wrong here is dashed code hint.
Completing it pops up a little yellow exclamation mark. Let's verify the project. Right click on it and select "Verify". That runs the White List Tool which outputs a detailed error report about the white-list validations.
ERROR    - Path:D:\MyCloud\dist\MyCloud.war (1 Error)
ERROR     - Class:net.eisele.opc.servlet.Test (1 Error)
ERROR      - 1:Method exit not allowed from java.lang.System.(Line No:41 
             Method Name:java.lang.System->exit(int))
ERROR    - D:\MyCloud\dist\MyCloud.war Failed with 1 error(s)
It is disappointing but there are limitations (aka White List) in place which prevent you from using every single Java functionality you know. For the very moment I am not going to drill this down further. All early access members had to say something about the restrictions and Oracle listened carefully. A lot of things are moving here and it simply is too early to make any statements about the final white list. A lot of 3rd party libraries (e.g. primefaces) are tested and run smoothly. Those aren't affected by the white list at all.

Bottom Line
That is all for today. I am not going to show you anything else of the OPC. And I know that you can't test-drive the service your own. You need to have the Javacloud SDK in place which isn't publicly available today. But it will be. And there will be a chance to test-drive the cloud for free. A trial. And I am looking forward showing you some more of the stuff that is possible. As soon as it becomes available. As of today you can register for access and get notified as the service is ready to sign you up!