Featured FREE Whitepapers

What's New Here?

jsf-logo

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....
jsf-logo

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....
javafx-logo

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....
agile-logo

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....
agile-logo

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....
enterprise-java-logo

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-logo

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....
software-development-2-logo

Where do Security Requirements come from?

One of the problems in building a secure application is that it’s not always clear what the security requirements are and where they are supposed to come from. Are security requirements supposed to come from the customer? Are they specified in the regulatory and compliance environment? Or are they implicit in the type of application that you are building – an online web store, real-time industrial control, a payroll system, a military weapons command system, an enterprise mobile app – and in the platform and technologies that you are using to build the system? The answer is: all of the above. In a recent post on how to manage security requirements in Agile projects, Rohit Sethi offers a useful way of looking at security requirements for any kind of software development work, Agile or not. He breaks security requirements down into 2 types: Security Stories A need to do, or not do, something in the system, which can be expressed in a story or a change request like other features. There’s no one way to get these requirements. Some requirements will come directly from the customer or operations or infosec or compliance or a partner, stated explicitly – if not always completely. You need to look harder for other security requirements, take time to understand the compliance and regulatory and legal requirements for the business and wade through the legalese to understand what your obligations are – both in the design of the system, and in how you design and build and operate it. Other requirements come from the basic patterns of the system that you are building. Any team developing an online web store or an enterprise mobile app should have a good understanding of the basic security problems that they may need to take care of – different kinds of systems have well-understood general requirements for authentication, authorization, auditing and logging, data privacy and confidentiality. Security stories are tracked and managed and prioritized like the rest your development work – the trick is to make sure that they are taken seriously by the team and by the customer, but at least they are visible to everyone on the project. Technical Security Constraints But there are other requirements that aren’t clear to the business and other stake holders – they’re hidden from outside of the development team, and sometimes hidden from the people on the development team as well. These are the things that developers have to do, or not do, to design and build software in a secure way given the architecture and the platform and technologies that they are using. Unlike requirements which are part of the problem space, these constraints are part of the solution space, part of the job of developing software properly. Some technical constraints are obvious to good, experienced developers who know how to write good, safe software: defensive programming, logging and auditing, not hard-coding passwords or storing secrets in the clear, using prepared statements for relational database access, and so on. Other technical constraints are much more obscure and specialised – developers may not understand or even be aware of these constraints unless they have training in secure software development and a good technical knowledge of the platform and language(s) and frameworks that they are working with, how to use them properly, what their security weak points are. Understanding Security requirements is part of your job as a Developer In Beautiful Security: Forcing Firms to Focus, Jim Routh explains that software security, like software quality, is generally implied in requirements for an application. In the same way that we expect a burger to be served hot and fresh, not stale and at room temperature, nobody should have to explicitly state that the software has to work, that you can’t deliver junk that is full of bugs and isn’t reliable, or code that isn’t secure. “… clearly, the omission of security from explicit requirements is no reason to believe that customers don’t care about it, or don’t understand its importance.” It’s up to us as developers to understand the business problems that we’re trying to solve and what our customers and partners need from a system – including understanding and confirming their security requirements. It’s up to us as developers to understand what kind of system we are building, and what the security and reliability and safety requirements for that kind of system should be. It’s up to us as developers to understand the platform and tools that we’re using, and how to use them properly. It’s up to us to find and understand security requirements and security constraints for a system. We can’t depend on other people to tell us these things, to make all of the steps explicit. This is our job, it’s what we get paid for. Reference: Where do Security Requirements come from? from our JCG partner Jim Bird at the Building Real Software blog....
java-logo

java.lang.NoClassDefFoundError: How to resolve – Part 2

This article is part 2 of our NoClassDefFoundError troubleshooting series. Take a look at part 1. It will focus and describe the simplest type of NoClassDefFoundError problem. This article is ideal for Java beginners and I highly recommend that you compile and run the sample Java program yourself. The following writing format will be used going forward and will provide you with: - Description of the problem case and type of NoClassDefFoundError - Sample Java program “simulating” the problem case - ClassLoader chain view - Recommendations and resolution strategies NoClassDefFoundError problem case 1 – missing JAR file The first problem case we will cover is related to a Java program packaging and / or classpath problem. A typical Java program can include one or many JAR files created at compile time. NoClassDefFoundError can often be observed when you forget to add JAR file(s) containing Java classes referenced by your Java or Java EE application. This type of problem is normally not hard to resolve once you analyze the Java Exception and missing Java class name. Sample Java program The following simple Java program is split as per below: - The main Java program NoClassDefFoundErrorSimulator - The caller Java class CallerClassA - The referencing Java class ReferencingClassA - A util class for ClassLoader and logging related facilities JavaEETrainingUtil This program is simple attempting to create a new instance and execute a method of the Java class CallerClassA which is referencing the class ReferencingClassA. It will demonstrate how a simple classpath problem can trigger NoClassDefFoundError. The program is also displaying detail on the current class loader chain at class loading time in order to help you keep track of this process. This will be especially useful for future and more complex problem cases when dealing with larger class loader chains. package org.ph.javaee.training1;import org.ph.javaee.training.util.JavaEETrainingUtil;/** * NoClassDefFoundErrorTraining1 * @author Pierre-Hugues Charbonneau * */ public class NoClassDefFoundErrorSimulator { /** * @param args */ public static void main(String[] args) { System.out.println("java.lang.NoClassDefFoundError Simulator - Training 1"); System.out.println("Author: Pierre-Hugues Charbonneau"); System.out.println("http://javaeesupportpatterns.blogspot.com"); // Print current Classloader context System.out.println("\nCurrent ClassLoader chain: "+JavaEETrainingUtil.getCurrentClassloaderDetail()); // 1. Create a new instance of CallerClassA CallerClassA caller = new CallerClassA(); // 2. Execute method of the caller caller.doSomething(); System.out.println("done!"); } }package org.ph.javaee.training1;import org.ph.javaee.training.util.JavaEETrainingUtil;/** * CallerClassA * @author Pierre-Hugues Charbonneau * */ public class CallerClassA { private final static String CLAZZ = CallerClassA.class.getName(); static { System.out.println("Classloading of "+CLAZZ+" in progress..."+JavaEETrainingUtil.getCurrentClassloaderDetail()); } public CallerClassA() { System.out.println("Creating a new instance of "+CallerClassA.class.getName()+"..."); } public void doSomething() { // Create a new instance of ReferencingClassA ReferencingClassA referencingClass = new ReferencingClassA(); } }package org.ph.javaee.training1;import org.ph.javaee.training.util.JavaEETrainingUtil;/** * ReferencingClassA * @author Pierre-Hugues Charbonneau * */ public class ReferencingClassA {private final static String CLAZZ = ReferencingClassA.class.getName(); static { System.out.println("Classloading of "+CLAZZ+" in progress..."+JavaEETrainingUtil.getCurrentClassloaderDetail()); } public ReferencingClassA() { System.out.println("Creating a new instance of "+ReferencingClassA.class.getName()+"..."); } public void doSomething() { //nothing to do... } }package org.ph.javaee.training.util;import java.util.Stack; import java.lang.ClassLoader;/** * JavaEETrainingUtil * @author Pierre-Hugues Charbonneau * */ public class JavaEETrainingUtil { /** * getCurrentClassloaderDetail * @return */ public static String getCurrentClassloaderDetail() { StringBuffer classLoaderDetail = new StringBuffer(); Stack<ClassLoader> classLoaderStack = new Stack<ClassLoader>(); ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); classLoaderDetail.append("\n-----------------------------------------------------------------\n"); // Build a Stack of the current ClassLoader chain while (currentClassLoader != null) { classLoaderStack.push(currentClassLoader); currentClassLoader = currentClassLoader.getParent(); } // Print ClassLoader parent chain while(classLoaderStack.size() > 0) { ClassLoader classLoader = classLoaderStack.pop(); // Print current classLoaderDetail.append(classLoader); if (classLoaderStack.size() > 0) { classLoaderDetail.append("\n--- delegation ---\n"); } else { classLoaderDetail.append(" **Current ClassLoader**"); } } classLoaderDetail.append("\n-----------------------------------------------------------------\n"); return classLoaderDetail.toString(); } }Problem reproduction In order to replicate the problem, we will simply “voluntary” omit one of the JAR files from the classpath that contains the referencing Java class ReferencingClassA. The Java program is packaged as per below: - MainProgram.jar (contains NoClassDefFoundErrorSimulator.class and JavaEETrainingUtil.class ) -CallerClassA.jar (contains CallerClassA.class ) - ReferencingClassA.jar (contains ReferencingClassA.class ) Now, let’s run the program as is: Recommendations and resolution strategies ## Baseline (normal execution) ..\bin>java -classpath CallerClassA.jar;ReferencingClassA.jar;MainProgram.jar org.ph.javaee.training1.NoClassDefFoundErrorSimulatorjava.lang.NoClassDefFoundError Simulator - Training 1 Author: Pierre-Hugues Charbonneauhttp://javaeesupportpatterns.blogspot.comCurrent ClassLoader chain: ----------------------------------------------------------------- sun.misc.Launcher$ExtClassLoader@17c1e333 --- delegation --- sun.misc.Launcher$AppClassLoader@214c4ac9 **Current ClassLoader** -----------------------------------------------------------------Classloading of org.ph.javaee.training1.CallerClassA in progress... ----------------------------------------------------------------- sun.misc.Launcher$ExtClassLoader@17c1e333 --- delegation --- sun.misc.Launcher$AppClassLoader@214c4ac9 **Current ClassLoader** -----------------------------------------------------------------Creating a new instance of org.ph.javaee.training1.CallerClassA... Classloading of org.ph.javaee.training1.ReferencingClassA in progress... ----------------------------------------------------------------- sun.misc.Launcher$ExtClassLoader@17c1e333 --- delegation --- sun.misc.Launcher$AppClassLoader@214c4ac9 **Current ClassLoader** -----------------------------------------------------------------Creating a new instance of org.ph.javaee.training1.ReferencingClassA... done!What happened? The removal of the ReferencingClassA.jar, containing ReferencingClassA, did prevent the current class loader to locate this referencing Java class at runtime leading to ClassNotFoundException and NoClassDefFoundError. This is the typical Exception that you will get if you omit JAR file(s) from your Java start-up classpath or within an EAR / WAR for Java EE related applications. ClassLoader view Now let’s review the ClassLoader chain so you can properly understand this problem case. As you saw from the Java program output logging, the following Java ClassLoaders were found: Classloading of org.ph.javaee.training1.CallerClassA in progress... ----------------------------------------------------------------- sun.misc.Launcher$ExtClassLoader@17c1e333 --- delegation --- sun.misc.Launcher$AppClassLoader@214c4ac9 **Current ClassLoader** -----------------------------------------------------------------** Please note that the Java bootstrap class loader is responsible to load the core JDK classes and is written in native code ** ## sun.misc.Launcher$AppClassLoader This is the system class loader responsible to load our application code found from the Java classpath specified at start-up. ##sun.misc.Launcher$ExtClassLoader This is the extension class loader responsible to load code in the extensions directories (<java_home>/lib/ext, or any other directory specified by the java.ext.dirs system property). As you can see from the Java program logging output, the extension class loader is the actual super parent of the system class loader. Our sample Java program was loaded at the system class loader level. Please note that this class loader chain is very simple for this problem case since we did not create child class loaders at this point. This will be covered in future articles. Recommendations and resolution strategies Now find below my recommendations and resolution strategies for NoClassDefFoundError problem case 1: - Review the java.lang.NoClassDefFoundError error and identify the missing Java class  -Verify and locate the missing Java class from your compile / build environment  -Determine if the missing Java class is from your application code, third part API or even the Java EE container itself. Verify where the missing JAR file(s) is / are expected to be found - Once found, verify your runtime environment Java classpath for any typo or missing JAR file(s) - If the problem is triggered from a Java EE application, perform the same above steps but verify the packaging of your EAR / WAR file for missing JAR and other library file dependencies such as MANIFEST. Please feel free to post any question or comment. The part 3 will be available shortly. Reference: java.lang.NoClassDefFoundError: How to resolve – Part 2 from our JCG partner Pierre-Hugues Charbonneau at the Java EE Support Patterns & Java Tutorial blog....
devops-logo

The importance of measuring your IT operations

How could one tell if an IT organisation is working well? A simple measure could be to check the delivered business functionalities versus the requested ones; if IT delivered all that was requested by the business one could assume that the IT organisation works well; viceversa if IT didn’t deliver the majority/totality of what was requested it seems clear that it’s not working well. However the number of actual versus projected deliverables is a rather superficial way to measure the effectiveness of an IT department; what measures the effectiveness of an IT organisation is the answer to the following question: “Is the IT department under consideration performing at its best?”. Suddendly the number of deliverables loses significance; how does one measure whether an IT organisation is performing at its best? I believe the answer lies in the accurate measurement of IT Operations (IT OPS). In fact only thorough data collection allows an IT organisation to answer two simple questions:How is IT performing? (Where are we at now?) How would we like IT to perform? (Where do we want to go?)Regardless of the IT methodology used, the answer to the two questions above requires meticolous measurement of IT OPS.The challenge now is to identify the metrics that need to be measured in order to answer the two questions above. In this first article I’m just going to suggest some of them, while in subsequent articles I’ll attempt to describe each one of them in more detail and provide a framework on how one could go about measuring them.I think that the following are fundamental metrics in IT OPS:Feature Average Lead Time (FALT). This is the average number of days it takes for a request, from the moment was originated, to hit production. Development Cost for a Deployed Feature (DECODEF). This is the development cost of getting a feature deployed into production. It comes down to bare people cost. Keep The Lights On (KTLO) cost for an information system. This is the infrastructure cost for a particular service. Number and Cost of Production Bugs after a release (NCPB). This measure is meant to provide both a figure around quality and a figure around quantity. Cost of mainteining Legacy Systems (COLS). This is the people cost in interacting with Legacy systems for issue investigation, small enhancements, production bugs Cost of Evergreening (COE). This is the cost of keeping the various technologies to a version which is supported by third party vendors. Business Value of each Deliverable to production (BUVD). This is perhaphs the most difficult figure to get since it’s not an exact science (how would one quantify the business value of Evergreening?)Why is measuring IT OPS so important? Well, my answer is that while deliverables stats tell you whether your IT is delivering, IT OPS lay the foundation for a Continuous Improvement culture and it’s only through continuous improvement that an IT organisation can reach operational excellence.In subsequent articles I’ll try to delve in detail on each IT OPS measurement; I will try to provide a framework that can be used as is or customised to obtain sensisble figures around the above measurements.Reference: The importance of measuring your IT operations from our JCG partner Marco Tedone at the Marco Tedone’s blog blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
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:
Close