Adam Bien's Weblog
- Alle
- General
- Blog Statistics
- Publications
- Netbeans
- RIA / Java FX
- Fun
- Enterprise Architekturen, Leitfaden für Effiziente Softwareentwicklung
- Java / JEE / Architecture
- Java EE 5 Architectures And Idioms
- Productive Java EE - Rethinking Best Practices
- Events
- In The Clouds
- Java EE 5 Architectures
- JavaONE 2007
- JavaONE 2009
- Real World Java EE Patterns - Rethinking Best Practices
- JavaONE 2008
How To Debug Unit Tests In Netbeans 6.7
In Netbeans 6.7 you can invoke, and especially debug unit tests in the following way:
1. From test results:
- Invoke context menu on a given test and select 'Debug'
2. From project
- Select test file and choose "Debug->Debug Test File" from main menu or press Ctrl_Shift_F6 (on Mac Cmd_Shift_F6)
The way on how test are executed is changed right after 6.5, you may get more insight from http://www.netbeans.org/issues/show_bug.cgi?id=119922
Please also check http://www.netbeans.org/issues/show_bug.cgi?id=158812, to track the recent changes.
Thanks to Alexei Mokeev for providing this information - I was shortly before filing a P1 bug :-). In my opinion the Netbeans 6.5 way was more intuitive.
Posted at 08:44AM Jul 02, 2009 by Adam Bien in Netbeans | Kommentare[6]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices
Netbeans 6.7 (prev. Netbeans 7.0) - For Clouds - Detailed Overview
Netbeans 6.7 (7.0) features - detailed view (kenai, maven, javaee). Someone translated this article from German. Thanks for the translation!
If you want to try out kenai go to: http://kenai.com/projects/javaee-patterns/, or open "Kenai" Tab --> Open Project and enter: javaee-patterns.
Posted at 09:28AM Jun 30, 2009 by Adam Bien in Real World Java EE Patterns - Rethinking Best Practices | Kommentare[1]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices
Netbeans 6.7 (prev. Netbeans 7.0) Is Ready To Download
You can download it from here. Btw. if you need some samples to test Glassfish v3 / Mercurial / EJB 3.1 / JPA / Java EE Patterns - you can check out (actually pull) some code from here: http://kenai.com/projects/javaee-patterns/. All tested with 6.7 the "Java" edition. Search for javaee-patterns in the Kenai tab.
Posted at 05:21PM Jun 29, 2009 by Adam Bien in General | Kommentare[0]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices
EJB 3.1 And REST - The Lightweight Hybrid
The Local / Remote interfaces in EJB 3.1 are optional. You can still, however, expose a Session bean as a RESTFul (JSR-311) service.
package com.abien.patterns.business.rest.boundary;
import com.abien.patterns.business.rest.control.Service;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@Stateless
@Path("current")
public class ServiceFacade {
@EJB
Service service;
@GET
public String getDate(){
return service.getCurrentDate().toString();
}
}
The Service is just another, usual, @Local bean:
@Stateless
public class Service {
public Date getCurrentDate(){
return new Date();
}
}
A ServiceFacade becomes available via REST, just denoting it with the JAR-RS annotations. Its both an EJB 3.1 and a REST-resource - it is available under http://localhost:8080/EJBRestHybrid/resources/current (tested with Glassfish v3 preview). It will return the current time as String (Mon Jun 29 08:19:32 CEST 2009). The additional @Stateless has the following advantages:
- Injection capabilities: you can easily inject other EJBs, EntityManagers, JMS-resources, DataSources or JCA connectors
- Transactions: all changes made in a REST-call will be automatically and transparently synchronized with the database
- Single threading programming model -> the old EJB goodness.
- Monitoring: an EJB is visible in JMX
- Throttling: its easy to restrict the concurrency of an EJB using ThreadPools or bean pools
- Vendor-independence: EJB 3 runs on multiple containers, without any modification (and without any XML in particular :-))
Exposing a protocol-neutral ServiceFacade directly via REST can make it REST-dependent. E.g. you may pass JAXB-enabled classes as parameters / return - values. It will be hard then to expose the ServiceFacade through other channels. On the other hand - if REST is all you need, it is the simplest and leanest approach. There are no additional libraries needed - everything is already included in a Java EE 6 container (in Glassfish v3 the whole EJB 3.1 container is < 1 MB...).
The whole example project (tested with Netbeans 6.7rc3 and Glassfish v3 Preview) with source code was pushed into http://kenai.com/projects/javaee-patterns. In Netbeans 6.7 you will have to enable Glassfish v3 capabilities. If you are using vi or emacs :-), you will have to include the Java EE 6 API to the classpath.
[This sample is based on the ServiceFacade pattern from the "Real World Java EE Patterns" book]
Posted at 09:05AM Jun 29, 2009 by Adam Bien in Real World Java EE Patterns - Rethinking Best Practices | Kommentare[2]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices
Glassfish Is Gaining Momentum - A Study
...Java projects that target Java EE, GlassFish is the leading application server for new project starts with 73% of all Java EE projects. Project starts, the number of new projects across all communities for a given time period, is a leading indicator, and a reliable predictor of the percentages add up to more than 100%...
An interesting study with lot of information and statistics. The study, however, was "Prepared for: Sun", but realized by Sourceforge. Read the whole story.
[Thanks Daniel N. for the hint!]
Posted at 10:00AM Jun 28, 2009 by Adam Bien in General | Kommentare[0]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices
Unit Testing EJB 3.1 ...When 0.8 Seconds Are Too Long [SOURCE CODE INCLUDED]
EJB 3 are just POJOs, so there is no need to unit-test them inside the EJB container. You could just instantiate them in the unit test. Sometimes it is needed to change a behavior of a session bean, to cause an exception or test the boundary in another:
@Stateless
public class ServiceFacade {
@EJB
Service service;
public boolean isOne(){
int nr = service.getNumber();
return (nr == 1);
}
}
I would like to test, whether the ServiceFacade returns "false" in case the number is not 1.The problem:
@Stateless
public class Service {
public int getNumber(){
return 1;
}
}
...its hardcoded....
Mockito is just perfect for testing such cases.
import com.abien.business.nointerface.control.Service;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class ServiceFacadeTest {
@Test
public void twoIsFalse(){
Service service = mock(Service.class);
when(service.getNumber()).thenReturn(2);
ServiceFacade facade = new ServiceFacade();
facade.service = service;
assertFalse(facade.isOne());
}
}
You can easily change the return value of every (non-final) class for test purposes. The whole project, with mockito libraries, was pushed into http://kenai.com/projects/javaee-patterns (tested with Netbeans 6.7rc3 and Glassfish v3 Preview).
The whole test is executed in 0.2 seconds on my machine. Four times faster than 0.8 :-). Btw. Glassfish v3 (with EJB 3.1 container) starts in about 5-10 seconds - the whole application is deployed in about 2 seconds...
[In the Real World Patterns - Rethinking Best Practices book several unit-testing strategies are discussed - but not mockito. It will change in the Iteration Two]
Posted at 09:00AM Jun 26, 2009 by Adam Bien in Real World Java EE Patterns - Rethinking Best Practices | Kommentare[4]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices
How To Unit-Test EJB 3 ...in 0.8 Seconds [source code included]
EJB 3 are just annotated classes - so it is straight forward to unit-test them. However, you will have to "emulate" the Dependency Injection and boot the EntityManager by yourself. It will cost you few additional lines of code. EJB 3.1 will solve the problem entirely - with an embeddable container. Meanwhile you can use openEJB for boot the entire container within Unit-Test:
public class HelloBeanTest {
private Hello hello;
@Before
public void bootContainer() throws Exception{
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.LocalInitialContextFactory");
Context context = new InitialContext(props);
hello = (Hello) context.lookup("HelloBeanLocal");
}
openEJB provide an own JNDI-SPI implementation, and plugs so naturally as JNDI-provider. Only one line (the bold one) makes your dependent on openEJB. You could even factor out the settings into jndi.properties. You will get from the lookup a fully-featured EJB 3 with injected dependencies and persistence (additional, but still lean, configuration is required here)
@Test
public void hello(){
assertNotNull(hello);
String message = "hugo";
String echo = hello.hello(message);
assertNotNull(echo);
assertEquals(message,echo);
}
The EJB is just an usual one:
public interface Hello {
public String hello(String message);
}
@Stateless
@Local(Hello.class)
public class HelloBean implements Hello{
public String hello(String message){
return message;
}
}
The whole source, project and needed libraries are pushed into: http://kenai.com/projects/javaee-patterns/. openEJB is lean - the only problem is the amount of libraries needed to run the test. I would prefer a single JAR. Maven, however, solves the problem for you in general.
Btw. I would really like to test Glassfish v3 Embeddable Container - should be available soon...
[This sample is not in my book :-)]
Posted at 09:00AM Jun 25, 2009 by Adam Bien in Real World Java EE Patterns - Rethinking Best Practices | Kommentare[4]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices
Generic CRUD Service aka DAO - EJB 3.1/0 Code - Only If You Really Needed
The term Data Access Object (DAO) is actually wrong. An object has state and behavior, and the behavior even can depend on the state. DAO is stateless, only only consists of data manipulation operations. Data Access Procedure (DAP) would be a more exact term. A Data Access Service, or "CRUD Service" would be a better, and even buzzword-compatible, term :-).
javax.persistence.EntityManager is already a perfect realization of the DAO (DAP) pattern - it is directly injectable into Services (I will cover Services later) or ServiceFacades. Just for CRUD use cases - DAOs are not needed - they would degrade to plain delegates and so dead code. In real projects, however, you will get likely some reusable queries, which should be maintained in a central place. In that case it is absolutely worth to introduce a DAO. If you really need it, you could deploy one DAO-instance, for all use cases. It is easy with generics:
public interface CrudService {
public T create(T t);
public T find(Class type,Object id);
public T update(T t);
public void delete(Class type,Object id);
public List findWithNamedQuery(String queryName);
public List findWithNamedQuery(String queryName,int resultLimit);
public List findWithNamedQuery(String namedQueryName, Map parameters);
public List findWithNamedQuery(String namedQueryName, Map parameters,int resultLimit);
}
The interface-implementation is actually a Service, which always has to be executed behind a ServiceFacade:
@Stateless
@Local(CrudService.class)
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public class CrudServiceBean implements CrudService {
@PersistenceContext
EntityManager em;
public T create(T t) {
this.em.persist(t);
this.em.flush();
this.em.refresh(t);
return t;
}
@SuppressWarnings("unchecked")
public T find(Class type,Object id) {
return (T) this.em.find(type, id);
}
public void delete(Class type,Object id) {
Object ref = this.em.getReference(type, id);
this.em.remove(ref);
}
public T update(T t) {
return (T)this.em.merge(t);
}
public List findWithNamedQuery(String namedQueryName){
return this.em.createNamedQuery(namedQueryName).getResultList();
}
public List findWithNamedQuery(String namedQueryName, Map parameters){
return findWithNamedQuery(namedQueryName, parameters, 0);
}
public List findWithNamedQuery(String queryName, int resultLimit) {
return this.em.createNamedQuery(queryName).
setMaxResults(resultLimit).
getResultList();
}
public List findByNativeQuery(String sql, Class type) {
return this.em.createNativeQuery(sql, type).getResultList();
}
public List findWithNamedQuery(String namedQueryName, Map parameters,int resultLimit){
Set> rawParameters = parameters.entrySet();
Query query = this.em.createNamedQuery(namedQueryName);
if(resultLimit > 0)
query.setMaxResults(resultLimit);
for (Entry entry : rawParameters) {
query.setParameter(entry.getKey(), entry.getValue());
}
return query.getResultList();
}
}
The only problem are the parameters. The number of parameters is not known in advance, so it has to be passed from the application. I used a simple Builder-Utility, which makes the parameter construction a bit more concise.
public class QueryParameter {
private Map parameters = null;
private QueryParameter(String name,Object value){
this.parameters = new HashMap();
this.parameters.put(name, value);
}
public static QueryParameter with(String name,Object value){
return new QueryParameter(name, value);
}
public QueryParameter and(String name,Object value){
this.parameters.put(name, value);
return this;
}
public Map parameters(){
return this.parameters;
}
}
The query-construction is almost fluent:
int size = this.crudServiceBean.findWithNamedQuery(Book.BY_NAME_AND_PAGES,
with("name",book.getName()).
and("pages", book.getNumberOfPages()).
parameters()).
size();
assertEquals(1,size);
I used the implementation above in many Glassfish v2(1) projects, but never in that puristic way. I always added project-specific queries - the actual added value. I wouldn't deploy DAOs just for CRUD, but many architects love it. Its sometimes easier to deploy some superfluous code - just to avoid more expensive discussions :-).
I pushed the origin sample project into http://kenai.com/projects/javaee-patterns - with some unit-tests and two variants. I tested the sample project with Glassfish Prelude v3 and WAR-deployment with Netbeans 6.7m1 - it should work with 6.7rc3 as well.
[The code was originally published in this Real World Java EE Patterns book, Page 141]
Posted at 09:00AM Jun 24, 2009 by Adam Bien in Real World Java EE Patterns - Rethinking Best Practices | Kommentare[9]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices
Beans With Both Views (@Local And @Remote) - An Anti Pattern?
It seems to be a pre assumption, that an EJB should have only one view - either @Remote or @Local. The views are not only useful for distribution, but also for the expression of visibility and private / public contracts in particular. A ServiceFacade is the only artifact, which is allowed to be visible from outside the container, so it can come with @Remote. Others, like, Services are not allowed to be exposed directly to the outside world.
If you are using @Remote interfaces, all the parameters and return values have to be copied. This is what the spec says. The application servers provide their own proprietary and not-portable solutions to pass the the parameters and return values "per reference" and not "per value". The business @Local interfaces have the "per reference" semantics as well. All parameters and return values are returned directly and not copied.
The @Local and @Remote interfaces can be aligned with the private (or more precisely package-wide) and public visibility and so the principle of encapsulation / data hiding as well. @Remote is visible to the outside world, and @Local is not. Therefore @Remote could be considered as public and @Local as package-wide visibility.
Especially the public contracts of a ServiceFacade should remain as stable as possible, every change could break potentially many clients. However, there is often needed, to provide a pragmatic access to the component's API, without breaking the API. This is easily achievable with EJB 3:
- You have to provide both interfaces @Local and @Remote
- @Remote interface defines the public contract
- @Local inherits from the @Remote. @Local can remain empty at the beginning
- The Bean implements the @Local interface and exposes both.
public interface BookOrderingServiceLocal extends BookOrderingServiceRemote{ public void cancelOrder(String id); } public interface BookOrderingServiceRemote { public void order(String isbn,String name); public Object referenceTest(Object reference); }@Stateless @Local(BookOrderingServiceLocal.class) @Remote(BookOrderingServiceRemote.class) @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public class BookOrderingServiceBean implements BookOrderingServiceLocal {
I have still no idea, why a Session Bean with two views was considered as an anti-pattern. I used that since several years - the approach works perfectly and is application server independent.
[See also: Dual View Facade Strategy on page 60 in Real World Java EE Patterns]
Posted at 08:00AM Jun 22, 2009 by Adam Bien in Real World Java EE Patterns - Rethinking Best Practices | Kommentare[5]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices
Written In The Clouds, Published With The Cloud and Pushed Into The Cloud
In the contrary to the previous books, which were entirely written in trains, "Real World Java EE Patterns - Rethinking Best Practices" was mainly written in the airplanes - and so clouds. More precisely not in the clouds, but actually above them :-)
I decided to self-publish the book on lulu.com. You have to choose the templates and upload the content - "into the cloud". It was interesting to watch, how the cover was postprocessed and splitted, the preview created, formatting validated etc. This whole process is parallelizeable and could (is?) be processed by multiple workers concurrently - actually well suited for the cloud and "pay as you go".
Instead of burning the sample code on the CD, I wanted to publish them as an opensource project (http://kenai.com/projects/javaee-patterns), and get the community involved (very like the p4j5 - with over 100 observers and few committers). kenai.com is a perfect platform for that. You can create the project (after an invitation) in seconds and will get the whole infrastructure like chat, bugzilla, mercurial, continuus integration, wiki and forums. Netbeans 6.7 integration is really remarkable and seamless. The infrastructure works well. ...after 24h I got the first issue filed :-). kenai.com comes with RESTFul API and is only an instance of itself. The continuus integration is probably leveraging some grid technology - and so "clouds" already.
I'm using mercurial as SCM. It feels also cloudy. You are committing the changes locally and can push the change-set into the default repository. In the case of kenai.com - it is the cloud again.
In two days I got 26 members on javaee-patterns, and had some nice discussions about Java EE on twitter (is running on S3 and probably EC2 - and so clouds).
2 years ago I wouldn't consider this book something special, but nowadays it is completely cloud-ready :-). Btw. the book is about Java EE 5/6 a perfect cloud technology...
Posted at 02:36PM Jun 20, 2009 by Adam Bien in Real World Java EE Patterns - Rethinking Best Practices | Kommentare[0]
[my tweets]
Rss My book: Real World Java EE - Rethinking Best Practices

