Featured FREE Whitepapers

What's New Here?


JavaOne 2012 – 2400 hours to go! Some recommendations

As you might have seen the JavaOne 2012 Content Catalog is online. The Program Committee had some very intense weeks of sorting, reviewing, rating and discussing every single proposal and we finally managed to setup a (hopefully) interesting mix for you. With exactly 105 days or 2400 hours to go I thought it could be a good day to offer you a list of my favorites to come.I had the pleasure to work with two teams on the program tracks this year so you will get some recommendations for both the Java EE Web Profile and Platform Technologies and the Enterprise Service Architectures and the Cloud track. Let’s start with the first one.Java EE Web Profile and Platform Technologies   This track has 64 sessions, 31 BoFs and 6 tutorials overall. It’s hard to highlight the right ones here without being unfair to anybody. All the speakers did a great job in submitting their proposals and it was amazingly hard to pick the final ones. Even if I have my favorites I highly encourage you to look at all the content in this track to make your own decisions!Oracle 50 Tips in 50 Minutes ForGlassFish Fans Arun Gupta, Christopher Kasso ( CON4701) This fast-paced session presents 50 tips and tricks for using GlassFish Server technology. Presented by two GlassFish experts, the session offers tips to help novice users as well as seasoned developers get the most out of GlassFish.Apache TomEE, Java EE 6 Web Profile on Tomcat David Blevins IBM (CON7469) Making its Java EE 6 Web Profile certification debut at JavaOne 2011, Apache TomEE combines the simplicity of Tomcat with the power of Java EE. If you’re a Tomcat lover or a TomEE enthusiast, this is the session you don’t want to miss!Building HTML5 Web Applications with Avatar Bryan Atsatt and Santiago Pericasgeertsen – Oracle (CON7042) This session focuses on how to build HTML5, thin-server Web applications with the Avatar framework. It introduces the notion of thin-server architectures as well as the major features in the Avatar framework for building rich UI applications.Standardizing Web Flow Technology with JSF Faces Flows Edward Burns and David Schneider – Oracle (CON4627) With the introduction of Faces Flows, a flow technology based on Oracle Application Development Framework (Oracle ADF) task flows and Spring Web flows. This session provides an overview of the Faces Flows technology and how it can be used to increase application modularity and code reuse. Real-World Java EE 6 Tutorial Paul Bakker and BERT ERTMAN – Luminis Technologies (TUT5064) This tutorial demonstrates how to use the Java EE 6 APIs together to build a portable, full-stack enterprise application and solve real-world problems. It not only focuses on the APIs but also shows you how to set up a vanilla Maven build from scratch and do unit and integration testing—going into almost all parts of the Java EE 6 specs.GlassFish Community BOF Anil Gaur and Arun Gupta – Oracle (BOF4670) The GlassFish Community is large and vibrant and has had a tradition of getting together at JavaOne for the past few years. Attend this BOF to meet with the key members of the Oracle GlassFish team. They will share the roadmap for how Java EE 7 will provide a standards-based PaaS platform for running your enterprise Java applications in the cloud.Nashorn, Node, and Java Persistence Douglas Clarke and Akhil Arora – Oracle (BOF6661) With Project Nashorn, developers will have a full and modern JavaScript engine available on the JVM. In addition, they will have support for running Node applications with Node.jar. This unique combination of capabilities opens the door for best-of-breed applications combining Node with Java SE and Java EE.Meet the Java EE 7 Specification Leads Linda Demichiel, William Shannon – Oracle (BOF4213) This is your chance to meet face-to-face with the engineers who are developing the next version of the Java EE platform. In this session, the specification leads for the leading technologies that are part of the Java EE 7 platform discuss new and upcoming features and answer your questions. Come prepared with your questions, your feedback, and your suggestions for new features in Java EE 7 and beyond.The Arquillian Universe: A Tour Around the Astrophysics Lab Daniel Allen and Aslak Kntusen – Red Hat (CON6918) This presentation guides you through the Arquillian extensions by demonstrating how specific extensions solve common problematic testing scenarios faced by enterprise developers. You will get a overview of what is available and possible today as well as what is brewing in the community. Enterprise Service Architectures and the Cloud   This track has 61 sessions, 24 BoFs and 4 tutorials. The same as for the previous track applies here. That is far too many content to feature the one and only ones. So please see this as a good excuse to make your own decisions ;)GlassFish 4: From Clustering to the Cloud Fabien Leroy – SERLI (CON4930) Expected by the end of 2012, GlassFish 4 leverages the 3.1 clustering functionalities to enter into the cloud computing era. The session takes a look under the hood to show you what makes GlassFish 4 a PaaS solution able to dynamically allocate all the services needed by an application. See a live demo of GlassFish cloud features already running with a VMware virtual cluster.Making Apps Scale with CDI and Data Grids Manik Surtani – Red Hat (CON5875) This session walks through a live demo of building a Website with CDI, clustering it with Java EE clustering capabilities, and then introducing a data grid into the mix to dramatically boost performance and load-handling capacity.Utilize the Full Power of GlassFish Server and Java EE Security Masoud Kalali – Oracle (CON3964) In this session, learn how to utilize Java EE security and what GlassFish Server technology provides to address your security requirements. The presentation explains a two-phase authentication mechanism.Other News and Noteworthy Things   You might have heard that the Java Strategy, Partner, and Technical keynotes will be held on the Sunday of conference week, beginning at 4:00 p.m. at the historic Masonic Auditorium on Nob Hill. After the keynotes, attendees can go to the official JavaOne Open House at the Taylor Street Café @ the Zone. As in years past, Sunday will feature User Group meetings (at Moscone West) and Java University courses (Hilton San Francisco Union Square). On Thursday, the Java Community keynote will return. More information should flow out in the next couple of weeks. If you have not already done so, register.Planning to go? Have a look at my post 10 Ways to make the Best out of a Conference.Reference: JavaOne 2012 – 2400 hours to go! Some recommendations from our JCG partner Markus Eisele at the Enterprise Software Development with Java blog....

Moving Beyond Core Hamcrest in JUnit

In the post Improving On assertEquals with JUnit and Hamcrest I introduced use of Hamcrest with JUnit. I then looked at JUnit’s Built-in Hamcrest Core Matcher Support. In this post, I look at how to apply Hamcrest’s non-core matchers with JUnit. These non-core matchers are NOT included with JUnit by default, but are available by including a Hamcrest JAR in the classpath.Although JUnit‘s inclusion of Hamcrest core matchers makes them easier to use if one only wants to use the core matchers, this inclusion can make use of the non-core matchers more difficult and is a well-known issue.Because the non-core Hamcrest matchers are not included with JUnit, the Hamcrest JAR needs to be downloaded. For my examples in this post, I am using hamcrest-all-1.2.jar.The next screen snapshot indicates the problems with combining the hamcrest-all JAR with the normal JUnit library (JUnit 4.10 as provided by NetBeans 7.2 beta in my example). As the screen snapshot indicates, when the junit-4.10.jar is included in the NetBeans libraries BEFORE the hamcrest-all-1.2.jar, the previously working code (from my previous post) breaks. Both NetBeans and the command-line compiler show this breakage in this screen snapshot.Switching the order of the test libraries so that the Hamcrest library is listed first and the JUnit JAR listed after it, makes the compiler break on the test code go away. This is shown in the next screen snapshot.Although switching the order of the dependent libraries so that the Hamcrest JAR is included before the JUnit JAR does prevent the build problem, this is not typically a satisfactory approach. This approach is too fragile for long-term maintainability. Fortunately, there is a better approach that JUnit directly supports to deal with this issue.A special Hamcrest-less JUnit JAR can be downloaded. The next screen snapshot shows the one I use in this example: junit-dep-4.10.jar. The -dep in the JAR name is the clue that it’s Hamcrest-free. The notation next to the JAR on the download page (screen snapshot shown next) points this out as well (“Jar without hamcrest”).With the Hamcrest-free “dep” version of the JUnit JAR, I can include it in the test libraries at any point I like with relation to the Hamcrest JAR and will still be able to build the test code. This is a much more favorable approach than relying on a specific order of test libraries. The next image shows the screen snapshot of NetBeans and the command-line build being successful even with the JUnit JAR listed first.With the appropriate libraries in use (JUnit-dep JAR and the Hamcrest “all” JAR), all of Hamcrest’s matchers can be used with JUnit-based tests. Hamcrest provides numerous matchers beyond the core matches that are now bundled with JUnit. One way to get an idea of the additional matchers available is to look at the classes in the Hamcrest JAR. The following is output from running a jar tvf command against the Hamcrest JAR and removing many of the entries to leave some of the most interesting ones. The “core” matchers tend to be based on the classes in the “core” package and the non-core matchers tend to be based on the classes in all the other packages without “core” in their name. 4029 Thu May 21 23:21:20 MDT 2009 org/hamcrest/core/AllOf.java 3592 Thu May 21 23:21:20 MDT 2009 org/hamcrest/core/AnyOf.java 1774 Thu May 21 23:21:20 MDT 2009 org/hamcrest/core/CombinableMatcher.java 1754 Thu May 21 23:21:20 MDT 2009 org/hamcrest/core/DescribedAs.java 1104 Thu May 21 23:21:20 MDT 2009 org/hamcrest/core/Every.java 2088 Thu May 21 23:21:20 MDT 2009 org/hamcrest/core/Is.java 1094 Thu May 21 23:21:20 MDT 2009 org/hamcrest/core/IsAnything.java 2538 Thu May 21 23:21:20 MDT 2009 org/hamcrest/core/IsCollectionContaining.java 1862 Thu May 21 23:21:20 MDT 2009 org/hamcrest/core/IsEqual.java 2882 Thu May 21 23:21:20 MDT 2009 org/hamcrest/core/IsInstanceOf.java 1175 Thu May 21 23:21:20 MDT 2009 org/hamcrest/core/IsNot.java 1230 Thu May 21 23:21:20 MDT 2009 org/hamcrest/core/IsNull.java 960 Thu May 21 23:21:20 MDT 2009 org/hamcrest/core/IsSame.java 675 Thu May 21 23:21:20 MDT 2009 org/hamcrest/core/StringContains.java 667 Thu May 21 23:21:20 MDT 2009 org/hamcrest/core/StringEndsWith.java 678 Thu May 21 23:21:20 MDT 2009 org/hamcrest/core/StringStartsWith.java 2557 Thu May 21 23:21:20 MDT 2009 org/hamcrest/collection/IsArray.java 1805 Thu May 21 23:21:20 MDT 2009 org/hamcrest/collection/IsArrayContaining.java 1883 Thu May 21 23:21:20 MDT 2009 org/hamcrest/collection/IsArrayContainingInAnyOrder.java 1765 Thu May 21 23:21:20 MDT 2009 org/hamcrest/collection/IsArrayContainingInOrder.java 1388 Thu May 21 23:21:20 MDT 2009 org/hamcrest/collection/IsArrayWithSize.java 1296 Thu May 21 23:21:20 MDT 2009 org/hamcrest/collection/IsCollectionWithSize.java 812 Thu May 21 23:21:20 MDT 2009 org/hamcrest/collection/IsEmptyCollection.java 866 Thu May 21 23:21:20 MDT 2009 org/hamcrest/collection/IsEmptyIterable.java 1086 Thu May 21 23:21:20 MDT 2009 org/hamcrest/collection/IsIn.java 3426 Thu May 21 23:21:20 MDT 2009 org/hamcrest/collection/IsIterableContainingInAnyOrder.java 3479 Thu May 21 23:21:20 MDT 2009 org/hamcrest/collection/IsIterableContainingInOrder.java 993 Thu May 21 23:21:20 MDT 2009 org/hamcrest/collection/IsIterableWithSize.java 1899 Thu May 21 23:21:20 MDT 2009 org/hamcrest/collection/IsMapContaining.java 1493 Thu May 21 23:21:20 MDT 2009 org/hamcrest/collection/IsMapContainingKey.java 1421 Thu May 21 23:21:20 MDT 2009 org/hamcrest/collection/IsMapContainingValue.java1380 Thu May 21 23:21:20 MDT 2009 org/hamcrest/number/IsCloseTo.java 2878 Thu May 21 23:21:20 MDT 2009 org/hamcrest/number/OrderingComparison.java1082 Thu May 21 23:21:20 MDT 2009 org/hamcrest/object/HasToString.java 918 Thu May 21 23:21:20 MDT 2009 org/hamcrest/object/IsCompatibleType.java 2080 Thu May 21 23:21:20 MDT 2009 org/hamcrest/object/IsEventFrom.java1164 Thu May 21 23:21:20 MDT 2009 org/hamcrest/text/IsEmptyString.java 1389 Thu May 21 23:21:20 MDT 2009 org/hamcrest/text/IsEqualIgnoringCase.java 2058 Thu May 21 23:21:20 MDT 2009 org/hamcrest/text/IsEqualIgnoringWhiteSpace.java 1300 Thu May 21 23:21:20 MDT 2009 org/hamcrest/text/StringContainsInOrder.java4296 Thu May 21 23:21:20 MDT 2009 org/hamcrest/xml/HasXPath.javaJUnit’s providing of a JAR without Hamcrest automatically built in (the “dep” JAR) allows developers to more carefully building up their classpaths if Hamcrest matchers above and beyond the “core” matchers are desired for use with JUnit.Reference: Moving Beyond Core Hamcrest in JUnit from our JCG partner Dustin Marx at the Inspired by Actual Events blog....

JasperReports JSF Plugin Use Cases Series

This is the entry point of an article series in which I will try to cover some of the use cases of JasperReport JSF Plugin, a tool created to easily integrate business reports designed for JasperReports in JSF applications. All the examples described in this series are available from the JasperReports JSF Plugin web site, at the samples section and will be part of the same business application: An online book store. The series will go through the steps needed to build the previous mentioned web application. I will try to keep the articles as neat, self-contained and complete as possible but I will deliberately omit some parts not specifically related with none of the main technologies exposed here. This way each article will go straight to the point and will be less verbose enabling easier understanding of main actors and their roles. Before getting deep into the material in which I will explain the different scenarios for JasperReports JSF Plugin we need to setup the web application project that will be the starting point for the further use cases. The main tools used in this series to work on that project are as follows:JasperReports 4.5.1 : the reporting engine. iReport 4.5.1 : the visual report designer Java Server Faces 1.2 & Facelets 1.1.1 : the web framework for my application (notice that this can be easily migrated into JSF 2.x). JasperReports JSF Plugin 1.0 : the integration bridge between the reporting engine and the web framework. Apache Derby : database that will hold the information that we need. Apache Tomcat 6.0.35: the application server that I will use to deploy and test the application.The data to be shown by each specific report will come from a simple database with a few tables that will hold the information we need. The main entities that I will be using to compound the domain model are, basically: books, customers, orders and order lines. Contents1 Project Setup 2 Configuring iReport 3 The Domain Model 4 ConclusionProject Setup The approach I will follow is to create a new web-based project that will use that database model. I will use Maven to configure and manage the dependencies that I will use since I’m pretty used to it and it will avoid me to grab all the jar files independently and configure them in my code base by hand. Any other can use the tool of his/her preference (Ant, Gradle, IDE-based, etc.). A good example for doing this with Maven is the “simple-webapp” archetype sample from the Maven Book. I will post here the command line sentence I used to generate my project structure using that archetype: mvn archetype:create -DgroupId=net.sf.jasperreports.jsf.sample -DartifactId=jrjsf-usecases -Dpackage=net.sf.jasperreports.jsf.sample.usecases -Dversion=1.0-SNAPSHOT -DarchetypeArtifactId=maven-archetype-webapp -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeVersion=1.0 This will generate a Maven project in a folder with name jrjsf-usecases and with the following initial values:groupId: net.sf.jasperreports.jsf.sample artifactId: jrjsf-usecases version: 1.0-SNAPSHOT package: net.sf.jasperreports.jsf.sample.usecasesNow the pom.xml file needs to be modified a bit to hold the dependencies needed for our project. The main changes I will do will consist on adding support for Java 1.5 (and higher) and the dependencies to the items listed at the beginning of the article. To be able to use generics and other fancy features added to Java after the release of Java 5 we need to configure the maven-compiler-plugin so the Java compiler can recognise that we want support for those features: <project> ... <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <groupId>org.apache.maven.plugins</groupId> <configuration> <source>1.5</source> <target>1.5</target> </configuration> </plugin> </plugins> </build> </project> And now let’s add the dependencies we need to implement our application: <project> ... <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.4</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.el</groupId> <artifactId>el-api</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>javax.faces</groupId> <artifactId>jsf-api</artifactId> <version>1.2_14</version> </dependency> <dependency> <groupId>javax.faces</groupId> <artifactId>jsf-impl</artifactId> <version>1.2_14</version> </dependency> <dependency> <groupId>com.sun.facelets</groupId> <artifactId>jsf-facelets</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>net.sf.jasperreports</groupId> <artifactId>jasperreports</artifactId> <version>4.5.1</version> </dependency> <dependency> <groupId>net.sf.jasperreports.jsf</groupId> <artifactId>jasperreports-jsf</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>org.apache.derby</groupId> <artifactId>derbyclient</artifactId> <version></version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> <scope>test</scope> </dependency> </dependencies> </project> In this project we will be using a container-managed data source accessible through JNDI. This kind of configuration is dependant of the type of application server that we are using. Since I’m using Tomcat as my application server, I need to add a context.xml file to our project under the folder src/main/webapp/META-INF to tell it how to get access to that database and the type of resource I want: <Context path='/jrjsf-usecases' reloadable='true'><Resource name='jdbc/BookStoreDB' auth='Container' type='javax.sql.DataSource' maxActive='100' maxIdle='30' maxWait='10000' username='app' password='' driverClassName='org.apache.derby.jdbc.ClientDriver' url='jdbc:derby://localhost:1527/bookstoredb;create=true' /></Context>Configuring iReport We need to configure iReport to make it able to connect to our database so let’s launch the iReport design tool and configure it to have it ready for the design work. iReport doesn’t bring support to the Apache Derby database out-of-the-box, we need to add the libraries to its classpath and configure the Derby JDBC driver by hand. This exercise will teach us to configure the tool to support any other database by the way. First of all, download the Apache Derby database from its website and install it (decompress the zip file) in a folder of your choice in your local machine, if you haven’t done it yet. Then open iReport’s preferences/options window and select the classpath tab:I will add the Derby’s lib folder into the iReport classpath. To do so click on “Add Folder” button and browse your filesystem until you get to the lib folder inside the Apache Derby installation:Once done, click the OK button at preferences window and now the Apache Derby client classes should be available in iReport. At this moment we are ready to configure the Apache Derby datasource in iReport which is going to be used by our reports. To add a new datasource we can start from either the iReport welcome page and clicking on “Step 1: Create a database connection …” button or by clicking on the “Report datasources” button at the tool bar and then clicking on the “Add” button. Either way we will get to a window like the following:The Apache Derby datasource needs to be completely configured by hand in iReport so choose “Database JDBC connection” in the list from previous window, click on “Next >” and fill in the values for the JDBC driver in the next window:The values for the fields are as follows:Name: BookStoreDB JDBC Driver: org.apache.derby.jdbc.ClientDriver JDBC URL: jdbc:derby://localhost:1527/bookstoredb Username: app Password: <empty>Now, before continuing, make sure that your Apache Derby instance is running to allow connections against it and click on the “Test” button to check everything is fine. The Domain Model Let’s say that our project is configured and ready to start to work on it (we have a basic project folder structure and all the basic dependencies are in our classpath, and iReport is able to connect to our database) so let’s start with a bit of code. My first step in this area will be to create a SQL file (bookstore.create.sql) to initialize the domain model I’ve been talking about in the Introduction paragraph of this series. Copy the text below this paragraph and paste it into a file inside your project folder structure so you can use it later: create table book ( book_id int generated by default as identity primary key, title varchar(50) not null, author varchar(50) not null, published_year varchar(4) not null, genre varchar(20) not null, price numeric not null );create table customer ( customer_id int generated by default as identity primary key, name varchar(250) not null );create table purchase_order ( order_id int generated by default as identity primary key, customer_id int not null, created_date date not null,constraint customer_fk foreign key (customer_id) references customer(customer_id) );create table purchase_order_line ( order_line_id int generated by default as identity primary key, order_id int not null, book_id int not null, item_count int not null,constraint order_fk foreign key (order_id) references purchase_order(order_id), constraint book_fk foreign key (book_id) references book(book_id) ); This is just the backend part of my domain model, in my application I need to represent those entities as Java classes as well. So, to have this domain model complete my next step will be to write the Java classes that I need to represent the previous defined domain model inside my Java application. Now it’s time to take a look to previous model, we have 4 different entities so we will need 4 different classes inside our Java application to comply with that model: Book public class Book {private Long id;private String title;private String author;private String publishedYear;private String genre;private double price;public String getAuthor() { return author; }public void setAuthor(String author) { this.author = author; }public String getGenre() { return genre; }public void setGenre(String genre) { this.genre = genre; }public Long getId() { return id; }public void setId(Long id) { this.id = id; }public double getPrice() { return price; }public void setPrice(double price) { this.price = price; }public String getPublishedYear() { return publishedYear; }public void setPublishedYear(String publishedYear) { this.publishedYear = publishedYear; }public String getTitle() { return title; }public void setTitle(String title) { this.title = title; }} Customer public class Customer {private Long id;private String name;public Long getId() { return id; }public void setId(Long id) { this.id = id; }public String getName() { return name; }public void setName(String name) { this.name = name; }} Order public class Order {private Long id;private Customer customer;private Date createdDate;private List lines = new ArrayList();public Date getCreatedDate() { return createdDate; }public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; }public Customer getCustomer() { return customer; }public void setCustomer(Customer customer) { this.customer = customer; }public Long getId() { return id; }public void setId(Long id) { this.id = id; }public List getLines() { return lines; }public void setLines(List lines) { this.lines = lines; }} OrderLine public class OrderLine {private Long id;private Order order;private Book book;private int itemCount;public Book getBook() { return book; }public void setBook(Book book) { this.book = book; }public Long getId() { return id; }public void setId(Long id) { this.id = id; }public int getItemCount() { return itemCount; }public void setItemCount(int itemCount) { this.itemCount = itemCount; }public Order getOrder() { return order; }public void setOrder(Order order) { this.order = order; }} Now, use the tool of your choice to connect to your database and execute the bookstoredb.create.sql file to create the table structure. Conclusion I’m trying to keep the code as simple and clean as possible. The Java classes listed in the previous section can be mapped to our relational database using ORM tools such as Hibernate, iBATIS, Ebean, etc. I leave the choice of the Object Relational Mapping layer to the reader as there are many choices and none of them will affect the way we integrate our report with the web framework. Our web application should contain other classes to compose its architecture as DAO’s and business facades and view controllers. However, adding all of them in this article is completely out of scope for the same reason that I am not adding any ORM information that may help to link the model classes to the database tables. There are a lot of IoC containers out there nowadays (Spring Framework, Weld, Seam, etc) and what really matters in this series is to demonstrate the usage of the JasperReports JSF Plugin. (View controllers will be listed in its specific article as they are part of each specific use case). And this is all we need to start working in the different examples of this nifty tool. During the next weeks new articles will be published under the JasperReports JSF Plugin category giving detailed examples that demonstrate how implement the most common use cases. Hope you enjoy them, any comments are welcome. Reference: JasperReports JSF Plugin Use Cases Series from our JCG partner Alonso Dominguez at the Code Nibbles blog....

Full WebApplication JSF EJB JPA JAAS – Part 1

This post will be the biggest so far in my blog! We will see a full web application. It will be done will the newest technologies (until today), but I will give some hints to show how to adapt this post to older technologies. In the end of this post you will find the source code to download. You can use it as you wish. Just go to the last page and do the download. \o/ If you downloaded the code and did not understand something, in this post I will explain every detail found in the code. Just read the subject inside this post that you want. I will list bellow the technologies that I will use in this post:JSF 2.0 Mojarra – With ManagedBeans as RequestScope and SessionScope. Message Internationalization – File that will have all the messages of our system; it will be easier to translate you pages. Default CSS file that will be imported as a library. EJB 3 – Our DAOs and Façades will be @Stateless. Generic DAO – A generic DAO that will have the CRUD actions to make our life easier. JPA 2 – To map our classes in the DB JAAS – To control the login and the user access to the pages. MVC – I will use this pattern with small modifications. Postgres as database, but I will show how to set up your app to MySQL also.I will not use TDD – JUnit to test our View/Model/Classes, but in the following link you can see a technique to use the JUnit to test your ManagedBeans: JUnit with HSQLDB, JPA and Hibernate. Tools that we will use:Eclipse Indigo – http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/indigor I will use JBoss 7 (some readers of this blog asked me for it) – http://download.jboss.org/jbossas/7.0/jboss-as-7.0.2.Final/jboss-as-7.0.2.Final.zip the version is: JBoss 7 Everything (NOT Java EE6 Certified). Indigo JBoss Tools (milestone version) – https://www.jboss.org/tools/download/dev.html if you do not know how to install the JBoss Tools in this post I will show how to (User Login Validation with JAAS and JSF). Be aware that in the post I will show how to install to another eclipse version, but the difference is the URL; use this URL instead the URL used in the link above: http://download.jboss.org/jbosstools/updates/development/indigo/ I will use the Postgres database but you can use any database you want; you will need only to download the database and the JDBC driver. Here you can download the latest Postgres JDBC: http://jdbc.postgresql.org/download.html; the latest version so far is the 4: http://jdbc.postgresql.org/download/postgresql-9.1-901.jdbc4.jar.This post will have several pages; this first page is just to show the technical details of the post today. I will not code to interface my model/DAO, just to save space. Remember that you should always code to interfaces (Design Pattern – Strategy). Before you continue be sure that you installed the JBoss Tools and the JBoss 7 in this exactly order. Business – Model Let us create the EJB project that will hold our system business.Click in the “Finish” button. Let us create the User and Dog classes that will be inside the “com” package. It will have the code bellow: package com.model;import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.Table;@Entity @Table(name = 'USERS') @NamedQuery(name='User.findUserByEmail', query='select u from User u where u.email = :email') public class User {public static final String FIND_BY_EMAIL = 'User.findUserByEmail';@Id @GeneratedValue(strategy=GenerationType.AUTO) private int id;@Column(unique = true) private String email; private String password; private String name; private String role;public int getId() { return id; }public void setId(int id) { this.id = id; }public String getEmail() { return email; }public void setEmail(String email) { this.email = email; }public String getPassword() { return password; }public void setPassword(String password) { this.password = password; }public String getName() { return name; }public void setName(String name) { this.name = name; }public String getRole() { return role; }public void setRole(String role) { this.role = role; }@Override public int hashCode() { return getId(); }@Override public boolean equals(Object obj) { if(obj instanceof User){ User user = (User) obj; return user.getEmail().equals(getEmail()); }return false; } } package com.model;import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table;@Entity @Table(name = 'DOGS') public class Dog {@Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String name; private double weight;public int getId() { return id; }public void setId(int id) { this.id = id; }public String getName() { return name; }public void setName(String name) { this.name = name; }public double getWeight() { return weight; }public void setWeight(double weight) { this.weight = weight; }@Override public int hashCode() { return getId(); }@Override public boolean equals(Object obj) {if(obj instanceof Dog){ Dog dog = (Dog) obj; return dog.getId() == getId(); }return false; } } About the code above:The User class has a field named “role” that will store the role level of the user. I created as a single field and we will leave all data in the same table just to make easier to understand. If you want more details about JAAS you can in this post: User Login Validation with JAAS and JSF. I will let the JPA handle the tables Id generations. If you want to change the way of the Id creation you can check this posts to see how to do it: JPA SequenceGenerator, JPA TableGenerator – Simple Primay Key. The email will be unique; it will be the login identifier. Notice that a class to be declared as Entity, it only needs the following annotations: “@Entity” and “@Id”. The class does not need to implement the Serializable interface.Business – DAOs I will use a generic DAO to basic CRUD operations and others two DAOs: one for User and another for Dog. It will be very easy to understand its use: package com.dao;import java.util.List; import java.util.Map; import java.util.Map.Entry;import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.persistence.criteria.CriteriaQuery;public abstract class GenericDAO<T> { private final static String UNIT_NAME = 'CrudPU';@PersistenceContext(unitName = UNIT_NAME) private EntityManager em;private Class<T> entityClass;public GenericDAO(Class<T> entityClass) { this.entityClass = entityClass; }public void save(T entity) { em.persist(entity); }public void delete(T entity) { T entityToBeRemoved = em.merge(entity);em.remove(entityToBeRemoved); }public T update(T entity) { return em.merge(entity); }public T find(int entityID) { return em.find(entityClass, entityID); }// Using the unchecked because JPA does not have a // em.getCriteriaBuilder().createQuery()<T> method @SuppressWarnings({ 'unchecked', 'rawtypes' }) public List<T> findAll() { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); cq.select(cq.from(entityClass)); return em.createQuery(cq).getResultList(); }// Using the unchecked because JPA does not have a // ery.getSingleResult()<T> method @SuppressWarnings('unchecked') protected T findOneResult(String namedQuery, Map<String, Object> parameters) { T result = null;try { Query query = em.createNamedQuery(namedQuery);// Method that will populate parameters if they are passed not null and empty if (parameters != null && !parameters.isEmpty()) { populateQueryParameters(query, parameters); }result = (T) query.getSingleResult();} catch (Exception e) { System.out.println('Error while running query: ' + e.getMessage()); e.printStackTrace(); }return result; }private void populateQueryParameters(Query query, Map<String, Object> parameters) {for (Entry<String, Object> entry : parameters.entrySet()) { query.setParameter(entry.getKey(), entry.getValue()); } } } package com.dao;import javax.ejb.Stateless;import com.model.Dog;@Stateless public class DogDAO extends GenericDAO<Dog> {public DogDAO() { super(Dog.class); } } package com.dao;import java.util.HashMap; import java.util.Map;import javax.ejb.Stateless;import com.model.User;@Stateless public class UserDAO extends GenericDAO<User> {public UserDAO() { super(User.class); }public User findUserByEmail(String email){ Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put('email', email);return super.findOneResult(User.FIND_BY_EMAIL, parameters); } } About the code above:I hid some warnings because the JPA code does not “understand” generics yet. The method “findOneResult” is with protected access just to prevent external access from other classes; this method requires logic to populate the parameters as we can see in the UserDAO. The class GenericDAO has a complete CRUD methods plus a method that returns a single object given a NamedQuery. The UserDAO class has a method (findUserByEmail) that belongs only to the class; but it has all CRUD methods by inheritance. With this pattern of DAOs we got a code more flexible. The DogDAO has no method in it but only the CRUD methods; you could implement any method in the class without problem. Instead using a method to “save” and other to “update” your objects you could use one method “entityManager.merge()”. You will have the same result but you will need to pay attention to the Cascade options. I did not use Interfaces because EJB 3.1 allows us to have Stateless Local Session Beans without interface. If you are using an older EJB version you will need to implement an interface (how to Implement EJBs with interfaces we will see in this post, in the Façades page). I will not develop with interfaces my DAO/Model just to save space in this post. Remember: “Always program to an interface” (Design Pattern – Strategy). If you use the JBoss 4.2 you could use the org.jboss.annotation.ejb.LocalBinding or org.jboss.annotation.ejb.RemoteBinding annotations; in this annotation you can write the name that will be mapped and referred by the EJB.Business – Façades I will create Façades that will be the “bridge” between the View and the DAO. In the Façade we will leave all the business rules leaving the DAO only the “database” functions/transactions, e.g. CRUD and queries. Let us see how our class UserFacade and DogFacade will be: package com.facade;import java.util.List;import javax.ejb.Local;import com.model.Dog;@Local public interface DogFacade {public abstract void save(Dog dog);public abstract Dog update(Dog dog);public abstract void delete(Dog dog);public abstract Dog find(int entityID);public abstract List<Dog> findAll(); } package com.facade;import java.util.List;import javax.ejb.EJB; import javax.ejb.Stateless;import com.dao.DogDAO; import com.model.Dog;@Stateless public class DogFacadeImp implements DogFacade {@EJB private DogDAO dogDAO;@Override public void save(Dog dog) { isDogWithAllData(dog);dogDAO.save(dog); }@Override public Dog update(Dog dog) { isDogWithAllData(dog);return dogDAO.update(dog); }@Override public void delete(Dog dog) { dogDAO.delete(dog); }@Override public Dog find(int entityID) { return dogDAO.find(entityID); }@Override public List<Dog> findAll() { return dogDAO.findAll(); }private void isDogWithAllData(Dog dog){ boolean hasError = false;if(dog == null){ hasError = true; }if (dog.getName() == null || ''.equals(dog.getName().trim())){ hasError = true; }if(dog.getWeight() <= 0){ hasError = true; }if (hasError){ throw new IllegalArgumentException('The dog is missing data. Check the name and weight, they should have value.'); } } } package com.facade;import javax.ejb.Local;import com.model.User;@Local public interface UserFacade { public User findUserByEmail(String email); } package com.facade;import javax.ejb.EJB; import javax.ejb.Stateless;import com.dao.UserDAO; import com.model.User;@Stateless public class UserFacadeImp implements UserFacade {@EJB private UserDAO userDAO;public User findUserByEmail(String email) { return userDAO.findUserByEmail(email); } } About the code above:The DogFacadeImp class does all the work of protecting the DogDAO from the view. It might have the business rules and avoid access to the database if some data is missing or any other business rule has being broken. The UserFacade has only one method because we will not have a User crud in this post; the bean will only search for a User if the view does not find it in the HttpSession. If you use the JBoss 4.2 you could use the org.jboss.annotation.ejb.LocalBinding or org.jboss.annotation.ejb.RemoteBinding annotations; in this annotation you can write the name that will be mapped and referred by the EJB. I do a validation in the DogFacadeImp to be sure that the Dog has only valid data. Remember that everyone can send you invalid data and your view validation may not work as you expect. The data of your application is very important and a double check is always worth.The interfaces are annotated with the @Local but I remember you that this annotation is optional. If you do no write the @Local annotation your server will assume that your EJB is local by default. Business – Datasource (by module) We also need to setup our datasource. At first I tried to create a datasource by following this tutorial http://community.jboss.org/wiki/JBossAS7-DatasourceConfigurationForPostgresql (I do follow tutorials just like any other human being does), but several errors started to happen after deploy with EJBs and the JBoss could not locate the Postgres jar. If you are using the JBoss 6 or any version under it you do not need to create the module; just put the file in the “default/lib” folder. If you have any doubt about set up a datasource, I show how to do it, in the JBoss 6 or other version under it, here: User Login Validation with JAAS and JSF. Let us create the Postgres module. Inside your JBoss 7 create the directory: “YOUR_JBOSS/modules/org/postgresql/main”. Copy the jar to the created directory and create a file named “module.xml”; copy the code bellow inside the “module.xml” file: <?xml version='1.0' encoding='UTF-8'?> <module xmlns='urn:jboss:module:1.0' name='org.postgresql'> <resources> <resource-root path='postgresql-9.1-901.jdbc4.jar'/> </resources> <dependencies><module name='javax.api'/></dependencies> </module> Notice that inside the “module.xml” file we have the jar file name written, the name must be the same of the Postgres jar file name. To create the MySQL module create the following folder “YOUR_JBOSS/modules/com/mysql/main”. Copy the jar to the created directory and create a file named “module.xml”; copy the code bellow inside the “module.xml” file: <?xml version='1.0' encoding='UTF-8'?><!-- ~ JBoss copyrights ~ http://community.jboss.org/wiki/DataSourceConfigurationInAS7 --><module xmlns='urn:jboss:module:1.0' name='com.mysql'> <resources> <resource-root path='mysql-connector-java-5.1.15.jar'/> </resources> <dependencies> <module name='javax.api'/> </dependencies> </module> Let us edit the file “YOUR_JBOSS/standalone/configuration/standalone.xml”. Inside the key “<datasources>” add the code bellow: <datasources> <!-- Add this config: begin --> <datasource jndi-name='CrudDS' pool-name='CrudDS_Pool' enabled='true' jta='true' use-java-context='true' use-ccm='true'> <connection-url>jdbc:postgresql://localhost:5432/CrudDB</connection-url> <driver-class>org.postgresql.Driver</driver-class> <driver>postgresql-jdbc4</driver> <pool> <min-pool-size>2</min-pool-size> <max-pool-size>20</max-pool-size> <prefill>true</prefill> <use-strict-min>false</use-strict-min> <flush-strategy>FailingConnectionOnly</flush-strategy> </pool> <security> <user-name>postgres</user-name> <password>postgres</password> </security> <validation> <check-valid-connection-sql>SELECT 1</check-valid-connection-sql> <validate-on-match>false</validate-on-match> <background-validation>false</background-validation> <use-fast-fail>false</use-fast-fail> </validation> </datasource> <!-- Add this config: end --> <drivers> <!-- Add this config: begin --> <driver name='postgresql-jdbc4' module='org.postgresql'/> <!-- Add this config: end --> </drivers> To configure your datasource with MySQL take a look here: http://community.jboss.org/wiki/DataSourceConfigurationInAS7 Business – XML Configurations Let us see how our persistence.xml will be (this file must be inside the folder src/META-INF): <?xml version='1.0' encoding='UTF-8'?> <persistence version='1.0' xmlns='http://java.sun.com/xml/ns/persistence' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd'> <persistence-unit name='CrudPU' transaction-type='JTA'> <provider>org.hibernate.ejb.HibernatePersistence</provider> <jta-data-source>java:/CrudDS</jta-data-source> <properties> <property name='hibernate.hbm2ddl.auto' value='update'/> </properties> </persistence-unit> </persistence> We got a very simple code; it is just pointing to a datasource and the option to generate all the database tables with “update”. Add the EJB project to the JBoss. Create the database in the Postgres and start the JBoss; after you started it the JPA will create the tables. Check the image bellow to see the tables/sequences that the JPA created for us.Create a file named “jboss-web.xml” inside the WEB-INF folder and write the code bellow in it: <?xml version='1.0' encoding='UTF-8'?><jboss-web> <!-- URL to access the web module --> <context-root>CrudJSF</context-root><!-- Realm that will be used --> <security-domain>java:/jaas/CrudJSFRealm</security-domain> </jboss-web> In the file above we set up the Realm that our application will use. Let us insert the users in the database that will do the login by the JAAS (if you want to see more details about JAAS you can see it here: User Login Validation with JAAS and JSF). I will not get in the JAAS details because you can find every step detailed in the previous link. See in the image bellow the data that I inserted manually in the database (you should do the same):Continue to the second part of the tutorial. Reference: Full WebApplication JSF EJB JPA JAAS from our JCG partner Hebert Coelho at the uaiHebert blog....

Full WebApplication JSF EJB JPA JAAS – Part 2

View – Creation and JSF set up This tutorial continues from part 1. Let us create a new Dynamic Web Project. Create it like the image bellow:Pay attention: in some moment the Eclipse will ask you if you want to add the JSF Capabilities (auto complete), enable it. Like the screens bellow:After the project creation, let us edit the “web.xml” file; it should have the same code as bellow: <?xml version='1.0' encoding='UTF-8'?> <web-app xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='http://java.sun.com/xml/ns/javaee' xmlns:web='http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd' xsi:schemaLocation='http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd' id='WebApp_ID' version='3.0'> <display-name>CrudJSF</display-name> <welcome-file-list> <welcome-file>pages/protected/user/listAllDogs.xhtml</welcome-file> </welcome-file-list> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> <url-pattern>*.jsf</url-pattern> <url-pattern>*.xhtml</url-pattern> </servlet-mapping><!-- Protected area definition --> <security-constraint> <web-resource-collection> <web-resource-name>Restricted Area - ADMIN Only</web-resource-name> <url-pattern>/pages/protected/admin/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>ADMIN</role-name> </auth-constraint> </security-constraint> <security-constraint> <web-resource-collection> <web-resource-name>Restricted Area - USER and ADMIN</web-resource-name> <url-pattern>/pages/protected/user/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>USER</role-name> <role-name>ADMIN</role-name> </auth-constraint> </security-constraint><!-- Login page --> <login-config> <auth-method>FORM</auth-method> <form-login-config> <form-login-page>/pages/public/login.xhtml</form-login-page> <form-error-page>/pages/public/loginError.xhtml</form-error-page> </form-login-config> </login-config><!-- System roles --> <security-role> <role-name>ADMIN</role-name> </security-role> <security-role> <role-name>USER</role-name> </security-role> </web-app> You do not have to worry if some warning/error shows up; we will solve them later. Notice that I have added all the JAAS code that we will need (If you want a detailed post about these JAAS configurations you can check it here: User Login Validation with JAAS and JSF). According to the JAAS configurations a regular user (USER role) will only see the files inside the user folder, that will be only the listing of the dogs recorded in our database; the ADMIN will be able to do all the CRUD actions because all the pages are inside the admins folder. Our “faces-config.xml” should have the code bellow: <?xml version='1.0' encoding='UTF-8'?><faces-config xmlns='http://java.sun.com/xml/ns/javaee' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd' version='2.0'><navigation-rule> <navigation-case> <from-outcome>logout</from-outcome> <to-view-id>/pages/protected/user/listAllDogs.xhtml</to-view-id> <redirect/> </navigation-case> </navigation-rule> <navigation-rule> <navigation-case> <from-outcome>listAllDogs</from-outcome> <to-view-id>/pages/protected/user/listAllDogs.xhtml</to-view-id> </navigation-case> </navigation-rule> <navigation-rule> <navigation-case> <from-outcome>createDog</from-outcome> <to-view-id>/pages/protected/admin/createDog.xhtml</to-view-id> <redirect/> </navigation-case> </navigation-rule> <navigation-rule> <navigation-case> <from-outcome>updateDog</from-outcome> <to-view-id>/pages/protected/admin/updateDog.xhtml</to-view-id> </navigation-case> </navigation-rule> <navigation-rule> <navigation-case> <from-outcome>deleteDog</from-outcome> <to-view-id>/pages/protected/admin/deleteDog.xhtml</to-view-id> </navigation-case> </navigation-rule><application> <resource-bundle> <base-name>messages</base-name> <var>msgs</var> </resource-bundle> </application></faces-config> Notice that to some actions I used the redirect action. With this action we will update the requested link in the URL bar of the browser, after the URL get updated the JAAS will deny access to an illegal user. We also have a file that will contain all the messages of our system. You will notice that all the texts displayed in our pages are in this file (create a file named “messages.properties” inside the src folder): #Dog dog=Dog dogName=Name dogWeight=Weight#Dog messages dogCreateHeader=Create a new Dog dogUpdateHeader=Update the Dog dogDeleteHeader=Delete this Dog dogNameRequired=The dog needs a name. dogWeightRequired=The dog needs a weight.#Actions update=Update create=Create delete=Delete cancel=Cancel#Login loginHello=Hello loginErrorMessage=Could not login. Check you UserName/Password loginUserName=Username loginPassword=Password logout=Log Out View – Creation and JSF set up Let us now create the ManagedBeans. First, we need to add the EJB to the Web Project. Right click with your mouse on the JSF project > Properties:Java Build Path > Projects > Add > Check CrudEJB > OKFirst, let us create the DogMB: package com.mb;import java.util.List;import javax.ejb.EJB; import javax.ejb.EJBException; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext;import com.facade.DogFacade; import com.model.Dog;@ManagedBean @RequestScoped public class DogMB {@EJB private DogFacade dogFacade;private static final String CREATE_DOG = 'createDog'; private static final String DELETE_DOG = 'deleteDog'; private static final String UPDATE_DOG = 'updateDog'; private static final String LIST_ALL_DOGS = 'listAllDogs'; private static final String STAY_IN_THE_SAME_PAGE = null;private Dog dog;public Dog getDog() {if(dog == null){ dog = new Dog(); }return dog; }public void setDog(Dog dog) { this.dog = dog; }public List<Dog> getAllDogs() { return dogFacade.findAll(); }public String updateDogStart(){ return UPDATE_DOG; }public String updateDogEnd(){ try { dogFacade.update(dog); } catch (EJBException e) { sendErrorMessageToUser('Error. Check if the weight is above 0 or call the adm'); return STAY_IN_THE_SAME_PAGE; }sendInfoMessageToUser('Operation Complete: Update'); return LIST_ALL_DOGS; }public String deleteDogStart(){ return DELETE_DOG; }public String deleteDogEnd(){ try { dogFacade.delete(dog); } catch (EJBException e) { sendErrorMessageToUser('Error. Call the ADM'); return STAY_IN_THE_SAME_PAGE; }sendInfoMessageToUser('Operation Complete: Delete');return LIST_ALL_DOGS; }public String createDogStart(){ return CREATE_DOG; }public String createDogEnd(){ try { dogFacade.save(dog); } catch (EJBException e) { sendErrorMessageToUser('Error. Check if the weight is above 0 or call the adm');return STAY_IN_THE_SAME_PAGE; }sendInfoMessageToUser('Operation Complete: Create');return LIST_ALL_DOGS; }public String listAllDogs(){ return LIST_ALL_DOGS; }private void sendInfoMessageToUser(String message){ FacesContext context = getContext(); context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, message, message)); }private void sendErrorMessageToUser(String message){ FacesContext context = getContext(); context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message)); }private FacesContext getContext() { FacesContext context = FacesContext.getCurrentInstance(); return context; } } About the code above:All navigation you will find in the faces-config.xml. You should use constants or a resource bundle with the navigations of your pages; this approach is a better approach than just leave strings in your methods. Notice that we are only using @EJB to inject the EJB inside of the MB. This happens because we are using everything inside the same EAR. The JBoss 7 turns easy this localization. If the injection does not work with JBoss 6 (or if you are using the EJB jar outside the EAR) you can use the injection like this: @EJB(mappedName=“DogFacadeImp/local”). Notice that a message is displayed to the user of our system. We have a try/catch to each action that we execute in the Façade, if some error happens we will send an error message to the user. The correct actions would be to validate the data in the ManagedBean and in the Façade. Those validations have a low CPU cost. If you are using the JBoss 4.2 you will need to do a JNDI lookup like the code bellow(just like a said earlier in this post use the LocalBinding annotation). Annotate your class like this: @Stateless @LocalBinding(jndiBinding='MyBean') public class MyBeanImp implements MyBean{ @Override public String hello() { return 'Value From EJB'; } } // In your Servlet class you would lookup like the code bellow: public class Inject extends HttpServlet {private MyBean local;protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { InitialContext iniCtx = new InitialContext(); local = (MyBean) iniCtx.lookup('MyBean'); } catch (NamingException e) { e.printStackTrace(); }System.out.println(local.hello()); request.getRequestDispatcher('/finish.jsp').forward(request, response); }/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {} }Now Let us see the UserMB: package com.mb;import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.servlet.http.HttpServletRequest;import com.facade.UserFacade; import com.model.User;@SessionScoped @ManagedBean public class UserMB { private User user;@EJB private UserFacade userFacade;public User getUser(){ if(user == null){ ExternalContext context = FacesContext.getCurrentInstance().getExternalContext(); String userEmail = context.getUserPrincipal().getName();user = userFacade.findUserByEmail(userEmail); }return user; }public boolean isUserAdmin(){ return getRequest().isUserInRole('ADMIN'); }public String logOut(){ getRequest().getSession().invalidate(); return 'logout'; }private HttpServletRequest getRequest() { return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); } } About the code above:This MB is only used to store the session user of our application. You will use this MB to display the user name or any other action regarding the user of the application. Notice that this is a Session MB; we check just one time if the user is null, and if returns true, we will go to the database. With this condition we will go just once to the database saving performance. If the @EJB injection raises an exception, check the tips given in the DogMB above.View – Pages Bellow the pages, css and its respective paths:Do not mind with the interrogation icons or any other icon type that is displayed in the picture above. Those are versioning icons that points to my code. Always save your code. I am using RequestScope in the ManagedBean, which is why you will see the h:inputHidden in all my pages. I think it is a better approach for you to repeat this field with RequestScope MBs because you will have more free memory in your server instead using SessionScope MBs. /WebContent/resources/css/main.css .table { border-collapse: collapse; }.tableColumnsHeader { text-align: center; background: none repeat scroll 0 0 #E5E5E5; border-bottom: 1px solid #BBBBBB; padding: 16px; }.tableFirstLine { text-align: center; background: none repeat scroll 0 0 #F9F9F9; border-top: 1px solid #BBBBBB; }.tableNextLine { text-align: center; background: none repeat scroll 0 0 #FFFFFFF; border-top: 1px solid #BBBBBB; }.panelGrid { border: 1px solid; }.panelFirstLine { text-align: center; border-top: 1px solid #BBBBBB; }.panelNextLine { text-align: center; border-top: 1px solid #BBBBBB; } /WebContent/pages/public/login.xhtml <!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'> <html xmlns='http://www.w3.org/1999/xhtml' xmlns:f='http://java.sun.com/jsf/core' xmlns:h='http://java.sun.com/jsf/html' xmlns:ui='http://java.sun.com/jsf/facelets'> <h:head> <h:outputStylesheet library='css' name='main.css' /> </h:head> <h:body> <p>Login to access secure pages:</p> <form method='post' action='j_security_check'> <h:messages layout='table' errorStyle='background: #AFEEEE;' infoStyle='background: #AFEEEE;' globalOnly='true' /> <h:panelGrid columns='2'> <h:outputLabel value='Username: ' /> <input type='text' id='j_username' name='j_username' /> <h:outputLabel value='Password: ' /> <input type='password' id='j_password' name='j_password' /> <h:outputText value='' /> <h:panelGrid columns='1'> <input type='submit' name='submit' value='Login' /> </h:panelGrid> </h:panelGrid> <br /> </form> </h:body> </html> Notice how we import the css like if it was a library. The action that you see in the form tag, points to an unknown action to us, but is the JAAS the responsible to manage that. /WebContent/pages/public/loginError.xhtml <!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'> <html xmlns='http://www.w3.org/1999/xhtml' xmlns:f='http://java.sun.com/jsf/core' xmlns:h='http://java.sun.com/jsf/html' xmlns:ui='http://java.sun.com/jsf/facelets'> <h:head> <h:outputStylesheet library='css' name='main.css' /> </h:head> <h:body> #{msgs.loginErrorMessage} </h:body> </html> /WebContent/pages/protected/user/listAllDogs.xhtml <!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'> <html xmlns='http://www.w3.org/1999/xhtml' xmlns:f='http://java.sun.com/jsf/core' xmlns:h='http://java.sun.com/jsf/html' xmlns:ui='http://java.sun.com/jsf/facelets'> <h:head> <h:outputStylesheet library='css' name='main.css' /> </h:head> <h:body> <h:form> <h3>#{msgs.loginHello}: #{userMB.user.name} || <h:commandLink action='#{userMB.logOut()}' value='#{msgs.logout}' /> </h3><h:messages /> <h:dataTable value='#{dogMB.allDogs}' var='dog' styleClass='table' headerClass='tableColumnsHeader' rowClasses='tableFirstLine,tableNextLine' > <h:column> <f:facet name='header'> #{msgs.dogName} </f:facet>#{dog.name} </h:column> <h:column> <f:facet name='header'> #{msgs.dogWeight} </f:facet>#{dog.weight} </h:column> <h:column> <h:panelGrid columns='2'> <!-- Always save the id as hidden when you use a request scope MB --> <h:inputHidden value='#{dog.id}' /><h:commandButton action='#{dogMB.updateDogStart()}' value='#{msgs.update}' rendered='#{userMB.userAdmin}' > <f:setPropertyActionListener target='#{dogMB.dog}' value='#{dog}' /> </h:commandButton> <h:commandButton action='#{dogMB.deleteDogStart()}' value='#{msgs.delete}' rendered='#{userMB.userAdmin}' > <f:setPropertyActionListener target='#{dogMB.dog}' value='#{dog}' /> </h:commandButton> </h:panelGrid> </h:column> </h:dataTable> <!-- This button is displayed to the user, just to you see the error msg --> <h:commandButton action='createDog' value='#{msgs.create} #{msgs.dog}' /> </h:form> </h:body> </html> About the code above:Always remember to wrap your code with the h:form tag. There are frameworks (like Primefaces) that will not work without the h:form, h:head and h:body. We use the UserMB to display the user name and to logout our user. The <h:messages /> tag will display the messages sent by the DogMB. Notice that in the line 33 the id is hidden. It is a necessary value if you use RequestScope instead SessionScope. I rather use RequestScope than SessionScope, your server memory will have less data in it. Notice that the buttons have the rendered=”#{userMB.userAdmin}” to indicate that only the ADMIN role will have access to the delete/update. I am passing to my MB the selected dog through the tag : “f:setPropertyActionListener”. The “create” button does not have the rendered option. It is just to display to you if a regular user tries to access a page./WebContent/pages/protected/admin/createDog.xhtml <!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'> <html xmlns='http://www.w3.org/1999/xhtml' xmlns:f='http://java.sun.com/jsf/core' xmlns:h='http://java.sun.com/jsf/html' xmlns:ui='http://java.sun.com/jsf/facelets'> <h:head> <h:outputStylesheet library='css' name='main.css' /> </h:head> <h:body> <h:form> <h:messages/><h3>${msgs.dogCreateHeader}</h3> <h:panelGrid columns='2' styleClass='panelGrid' rowClasses='panelFirstLine,panelNextLine' > <h:outputLabel for='dogName' value='#{msgs.dogName}' /> <h:inputText id='dogName' value='#{dogMB.dog.name}' required='true' requiredMessage='#{msgs.dogNameRequired}' /><h:outputLabel for='dogWeight' value='#{msgs.dogWeight}' /> <h:inputText id='dogWeight' value='#{dogMB.dog.weight}' required='true' requiredMessage='#{msgs.dogWeightRequired}' > <f:convertNumber /> </h:inputText> </h:panelGrid> <h:panelGrid columns='2'> <h:commandButton action='#{dogMB.createDogEnd()}' value='#{msgs.create}' /> <h:commandButton action='#{dogMB.listAllDogs()}' value='#{msgs.cancel}' immediate='true' /> </h:panelGrid> <br/> </h:form> </h:body> </html> About the code above:The fields name and weight are required and will print an error message if you leave it empty. The cancel button needs the option immediate=“true”; with this option the JSF will not validate any field./WebContent/pages/protected/admin/deleteDog.xhtml <!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'> <html xmlns='http://www.w3.org/1999/xhtml' xmlns:f='http://java.sun.com/jsf/core' xmlns:h='http://java.sun.com/jsf/html' xmlns:ui='http://java.sun.com/jsf/facelets'> <h:head> <h:outputStylesheet library='css' name='main.css' /> </h:head> <h:body> <h:form> <h:messages/><h3>#{msgs.dogDeleteHeader}: #{dogMB.dog.name}?</h3> <h:inputHidden value='#{dogMB.dog.id}' /> <h:panelGrid columns='2'> <h:commandButton action='#{dogMB.deleteDogEnd()}' value='#{msgs.delete}' /> <h:commandButton action='#{dogMB.listAllDogs()}' value='#{msgs.cancel}' immediate='true' /> </h:panelGrid> <br/> </h:form> </h:body> </html> Notice that in the line 15 the id is hidden. It is a necessary value if you use RequestScope instead SessionScope. I rather use RequestScope than SessionScope, your server memory will have less data in it. /WebContent/pages/protected/admin/updateDog.xhtml <!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'> <html xmlns='http://www.w3.org/1999/xhtml' xmlns:f='http://java.sun.com/jsf/core' xmlns:h='http://java.sun.com/jsf/html' xmlns:ui='http://java.sun.com/jsf/facelets'> <h:head> <h:outputStylesheet library='css' name='main.css' /> </h:head> <h:body> <h:form> <h:messages/><h3>#{msgs.dogUpdateHeader}: #{dogMB.dog.name}</h3> <h:inputHidden value='#{dogMB.dog.id}' /> <h:panelGrid columns='2' styleClass='panelGrid' rowClasses='panelFirstLine,panelNextLine' > <h:outputLabel for='dogName' value='#{msgs.dogName}' /> <h:inputText id='dogName' value='#{dogMB.dog.name}' required='true' requiredMessage='#{msgs.dogNameRequired}' /><h:outputLabel for='dogWeight' value='#{msgs.dogWeight}' /> <h:inputText id='dogWeight' value='#{dogMB.dog.weight}' required='true' requiredMessage='#{msgs.dogWeightRequired}' > <f:convertNumber /> </h:inputText> </h:panelGrid> <h:panelGrid columns='2'> <h:commandButton action='#{dogMB.updateDogEnd()}' value='#{msgs.update}' /> <h:commandButton action='#{dogMB.listAllDogs()}' value='#{msgs.cancel}' immediate='true' /> </h:panelGrid> <br/> </h:form> </h:body> </html> About the code above:Notice that in the line 15 the id is hidden. It is a necessary value if you use RequestScope instead SessionScope. I rather use RequestScope than SessionScope, your server memory will have less data in it. The fields name and weight are required and will print an error message if you leave it empty. The cancel button needs the option immediate=“true”; with this option the JSF will not validate any field.View – JBoss 7 JAAS Configuration Now we need just a few more steps to finish our software (Finally!). We need to edit the JBoss configurations and to add our JAAS configurations. Open again the file “YOUR_JBOSS/standalone/configuration/standalone.xml” and search for the key: “<security-domains>”. Add the code bellow (In this post I show how to do this set up for JBoss 6 – User Login Validation with JAAS and JSF): <subsystem xmlns='urn:jboss:domain:security:1.0'> <security-domains> <!-- add me: begin --> <security-domain name='CrudJSFRealm' cache-type='default'> <authentication> <login-module code='org.jboss.security.auth.spi.DatabaseServerLoginModule' flag='required'> <module-option name='dsJndiName' value='CrudDS'/> <module-option name='principalsQuery' value='select password from users where email=?' /> <module-option name='rolesQuery' value='select role, 'Roles' from users u where u.email=?' /> </login-module> </authentication> </security-domain> <!-- add me: end --><!-- Other data... --> </security-domains> </subsystem> Running our Application Let us create an EAR to unite our projects. File > New > Other >EnterpriseApplication ProjectWe just need to have in our JBoss the EAR added.Let us run our application. Start the JBoss and access our application by the URL: http://localhost:8080/CrudJSF/. I wrote the pages with a simple CSS to make easier the understanding. Login as USER and you will not see the update/delete buttons; you will only see the Create button that we left there just to see an exception off illegal access. Take a look bellow at our pages: Logged as ADMIN:Logged as USER:That is all for today To download the source code of this post, click here. I hope this post might help you. If you have any doubt or comment just post it bellow. See you soon. \o_ Links that helped me: http://7thursdays.wordpress.com/2008/03/18/dependency-injection-in-jboss-42-hold-your-excitement/ http://jan.zawodny.pl/blog/2011/07/jboss-7-postgresql-9 http://blog.xebia.com/2011/07/19/developing-a-jpa-application-on-jboss-as-7/ http://community.jboss.org/wiki/DataSourceConfigurationInAS7 http://stackoverflow.com/questions/286686/how-to-create-conditions-based-on-user-role-using-jsf-myfaces/ http://www.mkyong.com/jsf2/jsf-2-datatable-example/ Reference: Full WebApplication JSF EJB JPA JAAS from our JCG partner Hebert Coelho at the uaiHebert blog....

Using the JavaFX AnimationTimer

In retrospect it was probably not a good idea to give the AnimationTimer its name, because it can be used for much more than just animation: measuring the fps-rate, collision detection, calculating the steps of a simulation, the main loop of a game etc. In fact, most of the time I saw AnimationTimer in action was not related to animation at all. Nevertheless there are cases when you want to consider using an AnimationTimer for your animation. This post will explain the class and show an example where AnimationTimer is used to calculate animations.The AnimationTimer provides an extremely simple, but very useful and flexible feature. It allows to specify a method, that will be called in every frame. What this method is used for is not limited and, as already mentioned, does not have anything to do with animation. The only requirement is, that it has to return fast, because otherwise it can easily become the bottleneck of a system.To use it, a developer has to extend AnimationTimer and implement the abstract method handle(). This is the method that will be called in every frame while the AnimationTimer is active. A single parameter is passed to handle(). It contains the current time in nanoseconds, the same as what you would get when calling System.nanoTime().Why should one use the passed in value instead of calling System.nanoTime() or its little brother System.currentTimeMillis() oneself? There are several reasons, but the most important probably is, that it makes your life a lot easier while debugging. If you ever tried to debug code, that depended on these two methods, you know that you are basically screwed. But the JavaFX runtime goes into a paused state while it is waiting to execute the next step during debugging and the internal clock does not proceed during this pause. In other words no matter if you wait two seconds or two hours before you resume a halted program while debugging, the increment of the parameter will roughly be the same!AnimationTimer has two methods start() and stop() to activate and deactivate it. If you override them, it is important that you call these methods in the super class.The Animation API comes with many feature rich classes, that make defining an animation very simple. There are predefined Transition classes, it is possible to define a key-frame based animation using Timeline, and one can even write a custom Transition easily. But in which cases does it make sense to use an AnimationTimer instead? – Almost always you want to use one of the standard classes. But if you want to specify many simple animations, using an AnimationTimer can be the better choice.The feature richness of the standard animation classes comes with a price. Every single animation requires a whole bunch of variables to be tracked – variables that you often do not need for simple animations. Plus these classes are optimized for speed, not for small memory footprint. Some of the variables are stored twice, once in the format the public API requires and once in a format that helps faster calculation while playing.Below is a simple example that shows a star field. It animates thousands of rectangles flying from the center to the outer edges. Using an AnimationTimer allows to store only the values that are needed. The calculation is extremely simple compared to the calculation within a Timeline for example, because no advanced features (loops, animation rate, direction etc.) have to be considered. package fxsandbox;import java.util.Random; import javafx.animation.AnimationTimer; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage;public class FXSandbox extends Application { private static final int STAR_COUNT = 20000; private final Rectangle[] nodes = new Rectangle[STAR_COUNT]; private final double[] angles = new double[STAR_COUNT]; private final long[] start = new long[STAR_COUNT]; private final Random random = new Random();@Override public void start(final Stage primaryStage) { for (int i=0; i<STAR_COUNT; i++) { nodes[i] = new Rectangle(1, 1, Color.WHITE); angles[i] = 2.0 * Math.PI * random.nextDouble(); start[i] = random.nextInt(2000000000); } final Scene scene = new Scene(new Group(nodes), 800, 600, Color.BLACK); primaryStage.setScene(scene); primaryStage.show(); new AnimationTimer() { @Override public void handle(long now) { final double width = 0.5 * primaryStage.getWidth(); final double height = 0.5 * primaryStage.getHeight(); final double radius = Math.sqrt(2) * Math.max(width, height); for (int i=0; i<STAR_COUNT; i++) { final Node node = nodes[i]; final double angle = angles[i]; final long t = (now - start[i]) % 2000000000; final double d = t * radius / 2000000000.0; node.setTranslateX(Math.cos(angle) * d + width); node.setTranslateY(Math.sin(angle) * d + height); } } }.start(); } public static void main(String[] args) { launch(args); } }Reference: Using the JavaFX AnimationTimer from our JCG partner Michael Heinrichs at the Mike’s Blog blog....

Measuring your IT OPS – Part 1

In my previous article I briefly explained the importance of measuring IT OPS to lay the foundations for Continuous Improvement (CI). I then listed what I think are few, indispensable IT OPS measurements that form the basis for a CI environment. The first of these is FALT, (Feature Average Lead Time). Which kind of measure is this and why is it important? FALT gives us at a glance the average lead time that passed between the time when such feature was requested by the business (or found its place in the backlog if you talk Agile, or in the processing queue if you are talking Lean) and the time when such feature was delivered into production. If it’s true that a deliverable requested by the business is more valuable today than tomorrow because earlier delivery maximises the Return On Investment (ROI), then it’s true that a shorter lead time means greater business value. Additionally, the longer it takes for a feature to be deployed into production the higher the cost (think simple multiplication of man days x average resource cost) and because of what we just said, the lower the ROI. For certain typologies of companies such as startups, small differences in lead times might make the difference between survival and failure. This second aspect is important; in recent months Continuous Delivery has increased in popularity; with their book, Humble and Farley talk about this new way of looking at software delivery as they realise that a software deliverable is all the more valuable the shorter the time for it to hit production, delivering value to the stakeholders who asked for it. Whereas in Agile a story is considered “Done” when it passes the demo to the Product Owner‘s satisfaction (I like the definition of done in Agile given by Mayank Gupta in this article) with Continuous Delivery a story is done when the functionality has been deployed to production and it’s ready to be used. This to the novice Agile practitioner might seem a small difference, but imagine you had 10+ features which passed UAT and ready to go into production; could you say that you are done? You’d be surprised how many Agile practitioners would answer “yes” but the reality is that none of those 10+ features is delivering any business value because the targeted audience can’t make use of them. Therefore to measure the Average Lead Time of a Feature we consider two dates: the date this requirement found its place is some queue (a backlog is just another queue without limits) and the date the feature hit production. One way of measuring FALT could be the following:Define your Classes Of Service (COS – A concept welcomed in Kanban). A Class Of Service (COS) is just a type of production deliverable; each organisation has got its types but just to name a few we could consider amongst them: business deliverable, production bug fix, evergreening, maintenance of legacy systems, etc. Define a spreadsheet with three sections: one to collect detailed data per COS; one to calculate averages and one to define validation lists (in our case the only one is the list of COS)An example of such spreadsheet can be found below:The first worksheet contains the detailed data per COS and a graph which has been created using the average lead times per COS calculated in the second worksheet, shown below:For this example, I also created a third worksheet containing a validation list for COS as shown below:   The validation list could then be used to constrain the values in the COS column.Looking at the graph (and at worksheet 2 if you like) it becomes then pretty obvious (and helpful) to see where the attention needs to be focused; it would appear that in this case Evergreening projects (which represent pure cost) are the major bottleneck, with an average 288 days from when the project entered the work queue to when it was finally deployed to production.Figures don’t necessarily need to be good or bad, that’s the whole point: it’s important to simply have them so that IT organisations can make up their own mind as to whether the figures look healthy or there are some bottlenecks that need to be resolved. For instance it might be that upon further investigation it was found that actually the very nature of Evergreening projects in this particular organisation requires long lead times because of the required coordination with downstream systems using the system being upgraded. If this IT organisation didn’t measure IT OPS and, say, delivered all the required features within a budget year, the risk of rushing into false positives would have likely been very high and at the question: “How is your IT doing” the (false positive) answer would have been: “Great! We delivered everything that was asked of us this year!”. The real question is: could have you done better?I hope you found this article useful. In my next one I’ll talk about a proposed way of measuring the Development Cost for a Deployed Feature (DECODEF), as mentioned in my previous article. Go to Part 2 Reference: Measuring your IT OPS – Part 1 from our JCG partner Marco Tedone at the Marco Tedone’s blog blog....

Measuring your IT OPS – Part 2

In my opening article I stated the importance of measuring IT OPS to provide the underlying framework for a Continous Improvement (CI) culture and to this effect I identified a list of IT OPS measurements which I consider key to understand how your IT organisation is performing. In the first article of this series I suggested a simple way of measuring the Feature Average Lead Time (FALT). This article is about measuring the Development cost of a Deployed Feature (DECODEF). This is probably the easiest figure to measure as, conceptually, is just the multiplication of man days times the average cost of your resources. Some interesting considerations emerge when considering the calculation of the average cost of people involved in a release. The practice of having off-shore teams is now widely adopted not only in enterprise-scale organisations but also in small-medium ones; as an example, here in the UK is quite conventional having service companies with part or whole of their teams in off-shore locations, where the cost of labour agrees more with the balance sheet, often by at least one order of magnitude. When one looks at off-shoring, usually the following team configurations are in place:Mixed Team: Part of the team is on-shore, part of the team is off-shore in some sort of mixed balance Off-Shore Team with On-Shore management: The technical team is off-shore and the management is on-shore, generally within the organisation head offices; Off-Shore Team: The whole team is off-shore including managementCalculating the average cost of staff requires some attention when considering teams spread throughout the world; it is quite a common practice defining different average daily rates, depending on the location and function of each resource (e.g. an on-shore manager is significantly more expensive than an on-shore resource but also an off-shore senior technical person or manager is more expensive than a more junior resource). To have meaningful figures my suggestion is to indetify and classify different types of resources working on your project (on/off shore, manager, developer, etc), how much time each resource has spent on a production deliverable and how much productive time each resource can dedicate to the project (weighting); any time entry tools, opportunely configured, could come to the rescue with periodical reports. A simple suggestion on how to calculate the cost of development, and one which works for all typologies defined above, is the following:Define the typology of your resources Calculate the average daily cost per typology of resource Define the weighting of each resource on the project. The weighting is the amount of productive time a resource can dedicate to a production deliverable Have a reporting tool to provide the total number of hours a resource worked on a production deliverable Calculate the man days that each resource worked on a production deliverable, by dividing the total number of hours per resource by the number of hours in an Ideal Day Multiply the average daily rate of a resource type by the man days she spent on the production deliverable Sum all results to obtain the total cost of development for a deployed feature, or DECODEFIt’s worth mentioning few things:It’s easier to follow this process if the project is organised in small, atomic tasks measurable in hours The measurement needs to be thorough, or the results won’t be accurate and informative It’s worth defining what is your team Ideal Day as defined by Mike Cohn in his book on Agile estimate and planning. In my teams I define an Ideal Day to be composed of six productive (not elapsed) hours. Not all resources could be available for a production deliverable 100% of their productive time; although not ideal some specially skilled people might work on more than one deliverable at one time. Some sort of weighting might therefore be requiredHere follows an example for the calculation of DECODEF in a Mixed Team scenario:Although the data is completely made up, please note the weighting, the number of hours spent on a production deliverable, the calculation of man days, the different resource types and the different average cost per resource type.Why am I insisting on production deliverable as opposed to project? In my world a project generally consists of a series of production deliverables and if it’s true that each of these provides business value to stakeholders, then at each deliverable the team is delivering business value. In order to know with a certain accuracy how much true value the team delivered, it is necessary to deduct the costs. Calculating the delivered business value sooner rather than later might provide some excellent insights with regards to the direction the project is taking. It might be the case that the business elarges budget as the project progresses; in this case I believe it’s preferrable to deliver business value whenever possible to show our sponsors that they are getting good value for money, or that they aren’t!. On the other hand, these measurements might show that it’s too costly to go ahead with the project compared to the benefits (ROI) and therefore there is no interest in continuing with it. Like in software development, early feedback is preferable to a big-bang approach.I hope that this article provided some insights on how to measure the cost of development but mostly why it’s important to measure them. Reference: Measuring your IT OPS – Part 2 from our JCG partner Marco Tedone at the Marco Tedone’s blog blog....

Introduction to BTrace for Java applications

The aim of this article is to learn how to dynamically trace/observe running Java applications (JDK 6+) using BTrace without changing the code and configuration params of the applications. What is BTrace? BTrace is an open source project that was started in 2007 and was originally owned by two people – A.Sundararajan and K. Balasubramanian. It gained fame thanks to Java One 2008 conference. BTrace helps us to pinpoint complicated code problems in the application. The problems that can be solved using BTrace include code bugs, unpredictable flows, concurrency problems and performance problems that happen under specific and usually hard to reproduce circumstances. BTrace dynamically (without restarting application) instruments (changes) bytecode of an application in the way that programmer defines. The goal of the instrumentation is to see what happens in a specific area of the code. If used beyond this scope it may harm applications’ flow and therefore is forbidden by a validator. For example let’s try to solve following problem – an important file gets deleted occasionally once a day. We want to find the code that does this. Therefore we would like to change ‘delete’ method of java.io.File and print a stack trace of the calling thread if the file name fits. With BTrace we can do this by writing a short and straightforward Java code. The following schema displays principles of BTrace work.In Target JVM there is a dynamically inserted BTrace agent (using attach API). BTrace client (either BTrace Command Line or Visual VM with BTrace plugin) sends commands to the agent and gets responses. BTrace agent instruments classes that are being loaded into Target JVM and reloads classes that have already been loaded. Writing a Tracing script Writing BTrace scripts is pretty simple and straightforward and has concepts similar to Aspect Oriented Programming concepts. import com.sun.btrace.annotations.*; import com.sun.btrace.BTraceUtils;@BTrace public class HelloWorld {@OnMethod(clazz="java.io.File",method="") public static void onNewFileCreated(String fileName) { BTraceUtils.println("New file is being created"); BTraceUtils.println(fileName); }Each BTrace script consists of Probes (pointcuts in Aspects slang) and Actions (advices). A probe defines when the instrumentation should be executed. Action defines the instrumentation. Probe can consist of the following:Method entry/exit Line number Field updated/accessed Method call/return (within specified method(s)) Exception throw (before) Synchronization entry/exit Timer Constructor entryAbilities and limitations of BTrace AbilitiesDynamically connect to any java6 + application and run any(*) codeLimitationsMust run with the same user as the traced application is running with – due to security concerns Supports Hotspot JVM only Is compiled separately from the target application – is not familiar with application classes May crush target application – I ran BTrace on our longevity setup which was heavily loaded with many Tracing scripts. Target application didn’t crush even once.Advanced BTrace BTrace community consists de facto of a single developer that works regularly on the project. Therefore don’t expect too much improvement and many new features in the next releases. (This is a good opportunity to contribute to the project as each developer will enhance the development significantly). Documentation of the project should be significantly improved – I found myself guessing many times while integrating this framework into the existing frameworks at my job. BTrace forum is a good way to get answers about the framework. In order to understand how the magic of BTrace works, knowledge in three fields is required – ‘Java Agents Development’, ‘Bytecode manipulation in java’ and ‘Java attach api’. I may write about some of these fields in the future. Related linked http://www.parleys.com/#st=5&id=1618&sl=1 http://kenai.com/projects/btrace Reference: Introduction to BTrace from our JCG partner Art Gourevitch at the The Art of Java blog....

JavaFX 2 GameTutorial Part 4

Introduction This is part four of a six part series related to a JavaFX 2 Game Tutorial. If you’ve missed Part 1, Part 2, or Part 3, I encourage you to go through them before beginning this tutorial. To recap, in Part 3 I gave you a little history of the many classic arcade style games and the different input devices that were used. I then showed you how to create a simple game similar to the famous arcade ‘Asteroids’. The controls (movement of the ship) were, however, more similar to those of the PC game ‘Star Craft’. In Part 3, you should have a good understanding of how to receive input from your keyboard and mouse.Figure 1 JavaFX 2 Game Tutorial Part 4This tutorial is about tweaking Part 2’s game engine and updating the existing ‘Asteroids’ style game from Part 3 to handle collision detection. In this tutorial, I will briefly talk about sprites and how to handle collision detection. The spaceship will now have the ability to generate a force field to protect itself from enemies and asteroids. This is reminiscent of the classic arcade ‘Asteroids Deluxe’. If you want to run the demo, scroll down and click on the WebStart button below. Please read the requirements before launching the game. What is a Sprite? According to Wikipedia, “a sprite is a two-dimensional image or animation that is integrated into a larger scene.” From the Java gaming world view, a sprite is an object containing image frames and additional data based on the context of an actor to be animated onto the scene area. In the days of Walt Disney, when cartoons were drawn with a pencil and paper, the artist produced many drawings that became animations. This example points to the creation of the flip book. I’m sure you’ve created flip books as a kid. I know I did. I used to doodle and make cool animations with all the corners of my notebooks. In our Asteroid type game, I created a sprite object which contains all of the images (ImageView) of the ship pre-rotated just like a flip book. To animate the ship turning, I made the current frame visible and the rest of the frames not visible. Similar to a flip book, it will appear to be rotated about its center (pivot) point. A sprite can also contain other information, such as velocity or health points.  Collision Detection When actors or sprites animate across the scene, the game engine will check each sprite against other sprites to determine if they have collided into one another. This process should be very efficient especially when you have numerous sprites moving about the screen. There are tradeoffs when it comes to being efficient. Because each cycle in the game loop will check for collision, being more accurate usually degrades your performance. Many games will use the bounding region of the image to determine if two sprites have collided into one another. Some games use rectangles as bounding regions. Shown below in figure 2 are two sprites colliding:Figure 2 Bounding box as a rectangular collision region.I’m sure you’ll know by now that most actors (images) in games don’t appear rectangular when pixels surrounding the actor are transparent. However, the actor or image is indeed rectangular even if the pixels are transparent or not.Figure 3 depicts an actor imageThose games which use rectangular bounding regions usually make the bounding box inscribed in the sprite’s image. Shown below in figure 4 two rectangular bounding regions (orange and green) are inscribed in the spaceship image.Figure 4 Two rectangles used as collision bounding boxes.I’m sure you will notice that the nose tip of the ship and wings are not covered by either bounding box. This means that when an asteroid overlaps the unbounded region of the sprite the collision will not occur. Some games use this strategy; you will notice that the sprites’ rectangular bounding regions are small and placed in key areas of the sprite image. Greater precision will be found with better algorithms for polygons and other non-rectangular shapes. In this blog entry, I basically use circles as bounding regions and not rectangles. I could have made each sprite contain an array of collision shapes, but instead, I chose to have only one collision region for each sprite. Each collision region will be a circle shape on the scene graph. For the spaceship, I inscribed the circle based on the center point of the ship with the radius extended to the cock pit of the ship. Shown below in figure 5 the bounded circular collision area of the ship is depicted as a red circle.Figure 5 The ship’s collision region.I chose a circle as the bounding region because of the relative ease to determine the collision of two objects based on the distance formula (Pythagorean theorem) which only requires each sprite’s bounding region’s center point and their radii. After calculating the distance based on the two center points, you will compare the result to see if it is less than or equal to the sum of the two radii. If the result does indeed come out to be less than or equal to the sum of the two radii then a collision has occurred. Figure 6 depicts how the distance formula relates to the two center points of circular bounding regions.Figure 6 distance formula between two center points.The following code creates the main game loop from the GameWorld class: @Override public void handle(javafx.event.ActionEvent event) {// update actors updateSprites();// check for collision checkCollisions();// removed dead things cleanupSprites();} The code below creates the checkCollision() method from the GameWorld class: protected void checkCollisions() { // check other sprite's collisions spriteManager.resetCollisionsToCheck(); // check each sprite against other sprite objects. for (Sprite spriteA : spriteManager.getCollisionsToCheck()) { for (Sprite spriteB : spriteManager.getAllSprites()) { if (handleCollision(spriteA, spriteB)) { // The break helps optimize the collisions // The break statement means one object only hits another // object as opposed to one hitting many objects. // To be more accurate comment out the break statement. break; } } } }The derived Game World (TheExpanse) class’ implementation of its handleCollision() method: /** * How to handle the collision of two sprite objects. * * @param spriteA Sprite from the first list. * @param spriteB Sprite from the second list. * @return boolean returns a true if the two sprites have collided otherwise false. */ @Override protected boolean handleCollision(Sprite spriteA, Sprite spriteB) { if (spriteA != spriteB) { if (spriteA.collide(spriteB)) {if (spriteA != myShip) { spriteA.handleDeath(this); } if (spriteB != myShip) { spriteB.handleDeath(this); } } }return false; } The Sprite Class’ default implementation of its collide() method using the distance formula: public boolean collide(Sprite other) {if (collisionBounds == null || other.collisionBounds == null) { return false; }// determine it's size Circle otherSphere = other.collisionBounds; Circle thisSphere = collisionBounds; Point2D otherCenter = otherSphere.localToScene(otherSphere.getCenterX(), otherSphere.getCenterY()); Point2D thisCenter = thisSphere.localToScene(thisSphere.getCenterX(), thisSphere.getCenterY()); double dx = otherCenter.getX() - thisCenter.getX(); double dy = otherCenter.getY() - thisCenter.getY(); double distance = Math.sqrt(dx * dx + dy * dy); double minDist = otherSphere.getRadius() + thisSphere.getRadius();return (distance < minDist); } The Sprite Class’ default implementation of its handleDeath() method: public void handleDeath(GameWorld gameWorld) { gameWorld.getSpriteManager().addSpritesToBeRemoved(this); } The Atom (an asteroid or missile) class will override the handleDeath() method: public void handleDeath(GameWorld gameWorld) { implode(gameWorld); super.handleDeath(gameWorld); } JavaFX 2 Sprite and Collision Demo This simple demo game will be a mix between StarCraft and Asteroids. When using the mouse to navigate the ship, you will notice that the controls will resemble StarCraft’s Battle Cruiser. The objective is to fire your weapon at the spheres before they hit your spaceship or other spheres which implode upon impact. Because this is a simple tutorial or even a game in its early stages of development, the game doesn’t keep track of the score. I encourage you to go to GitHub to download the code and enhance the game. For the sake of brevity, I will not be showing all of the code changes, but I trust you will visit GitHub here: https://github.com/carldea/JFXGen for all the demos and source code. Requirements:Java 7 or later JavaFX 2.1 or later Windows XP or later (Should be available soon for Linux/MacOS)A simple Asteroid type game called ‘The Expanse’. Instructions:Right mouse click (on Windows) to fly ship. Left mouse click (left click on Windows mouse) to fire weapon. Key press ’2? to change to large missiles. (blue circular projectiles) Other key press defaults to smaller missiles. (red circular projectiles) Space bar key press will toggle a force field to protect the ship from enemies and asteroids.Click on the Launch button below to start the demo: Continue to Part 5 of this tutorial. Related articles Definition of a sprite: http://en.wikipedia.org/wiki/Sprite_%28computer_graphics%29 Walt Disney: http://en.wikipedia.org/wiki/Walt_Disney How to make a flip book: http://www.bitrebels.com/design/how-to-create-a-flip-book/ JavaFX’s ImageView : http://docs.oracle.com/javafx/2/api/javafx/scene/image/ImageView.html Collision detection: http://zetcode.com/tutorials/javagamestutorial/collision/ AABBs Collision detection in Java: http://www.youtube.com/watch?v=JIxV-LXqa1g Pythagorean theorem: http://en.wikipedia.org/wiki/Pythagorean_theorem Distance formula: http://en.wikipedia.org/wiki/Distance Serious game of Asteroids Deluxe (Youtube): http://www.youtube.com/watch?v=6DG-GJENHgg Reference: JavaFX 2 GameTutorial Part 4 from our JCG partner Carl Dea at the Carl’s FX Blog blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below: