Archief ‘Algemeen’ categorie
Door: gnoij, 8 March 2010
A common problem with typecasting a lazy loaded entity to its child is a ClassCastException. This exception occurs because the dynamic created proxy implements the baseclass and has no knowledge about its subclasses.
Suppose we have a class B which extends A and a class C which has class A as a member as shown below.
The following test will fail with a ClassCastException on the last line.
The methods save(), clearSession() and retrieve() are just helper methods which implement the Hibernate session methods save(), clear() and get().
A search on the Internet shows a couple of solutions for this problem.
- Using interfaces as a proxy in the hibernate mappings. This will result in accessing the object through its interface only so all methods must be exposed in the interface. I don’t want to expose every public or protected method in the interface which are not intended for use by external parties.
- Using the Visitor Pattern to access the correct childclass. This means that users of these objects must write a lot of code just to use some getters. I don’t want to burden someone else with a local Hibernate problem.
- Using ((HibernateProxy)object).getHibernateLazyInitializer().getImplementation() whenever a typecast of an object to its child class is needed.
All of the solutions mentioned above are not suitable for me so I decided on another solution which is a variant of solution 3.
With a slight modification of the method getA() in class C, exposing the HibernateProxy is avoided.
Now the test completes without failure.
This has to be done for every getter which can return a lazy loaded proxy.
And if you (like me) don’t want Hibernate code in your domain model, you can move this code to the persistence layer and use dependency injection to use it.
It’s still not an elegant solution (IMHO there isn’t one), but its the best usable for me.
Gepost in Algemeen, Java API, Object Relational Mapping | 1 reactie »
Door: Jan-Kees van Andel, 27 February 2010
I like the maven-jetty-plugin. If I download an Open Source project, I usually first look for this baby, because it allows me to quickly run the code in a tested environment. This saves me from a lot of configuration, which would otherwise cause me to lose interest. This often doesn’t take long…
Also, you can completely configure the server in your POM, centralizing configuration and making it thus easy to store server settings in version control. Also, the mvn-jetty-plugin benefits from your existing Maven project configuration, like dependencyManagement.
Some of my buddies at Apache even use the maven-jetty-plugin on a daily basis for their real work. I never got this far, mostly because I’m more familiar with Tomcat, but also because I didn’t really see it as a mature development tool. However, today I decided to give it a chance.
The first attempt
So, I created a simple webapp in my favorite IDE: IntelliJ IDEA and added a Maven2 POM to enable Maven2 support. All well so far.
This was the initial version of my POM:
All was fine, my test app was running, but I needed to enable Unified EL to test MyFaces BeanValidator.
Adding UEL libraries
So, I added a dependency to the UEL API and Impl in my POM, but there was an issue. Every web container already provides the old Expression Language in the jsp-api.jar. So I’m not allowed to package my own EL libraries.
However, I’m quite stubborn, so I tried anyway:
So, let’s give it a try:
mvn jetty:run-exploded
(MyFaces 2.0 requires exploded deployment in Jetty).
Result? BOOOM!
The fix, replacing libraries
The error is completely appropriate. You’re just not allowed to package your own version of the servlet libraries. That’s the job of the servlet container. Failing to do so will result in the error shown above.
So we need to fix this issue by somehow replacing the Jetty libraries or at least changing the way Jetty loads its jsp-api.jar. This is no trivial task however, since jetty is initialized by Maven and doesn’t have a fixed directory structure on disk.
So we need to have some way in Maven to configure the Jetty libraries.
First, Jetty doesn’t have an endorsed mechanism, so that’s a no-go.
But the fix is actually quite easy, just pass some dependencies into the jetty plugin in the POM.
The final POM looks like this:
As you can see, Maven takes care of the heavy lifting. You only need to specify your dependencies and they will override any dependencies with the same groupId, artifactId and type.
So, now I don’t have any reason not to use mvn-jetty-run to test my code!
Happy coding!
Gepost in Algemeen, JavaServer Faces, Maven | Geen reacties »
Door: Michel.Schudel, 3 February 2010
Using the Spring DefaultMessageListenerContainer makes it easy for you to connect to a jms resource like a Queue so you can pick up messages from that queue.
Using this container in Websphere (6.0, 6.1, 7) some problems occur when you want to do the following:
- You use a resource environment reference for your destination, specified in the web.xml, for the Destination.
- You use the property
destinationName on the DefaultMessageListenerContainer in combination with a JndiDestinationResolver to look up your resource environment reference like this: java:comp/env/jms/(your destination)
problem
When you try to start the application, you will get an exception like this: javax.naming.NameNotFoundException: Name "comp/env/jms/(your destination)" not found in context "java:"., although you are sure that your resource environment reference is defined correctly.
cause
The cause of this problem lies in the fact that the lookup occurs in a Thread started by the DefaultMessageListenerContainer, which is unmanaged by Websphere. This thread will not have the jndi queue bindings in its InitialContext.
solution
You can either:
- Specifiy the jndi object beforehand with a
JndiObjectFactoryBean, or a
<jee:jndi-lookup id="myqueue" jndi-name="java:comp/env/jms/(your destination)"/>, and then
setting the destination property of the DefaultMessageListenerContainer to the ref myqueue, so no actual lookup occurs within the thread of the listener itself.
-
Delegate the listener’s thread to Websphere with the help of the Spring class
WorkManagerTaskExecutor. You can then set the property taskExecutor on the message listener container to reference this class. See the IBM article here for details on how to do this.
Gepost in Algemeen | 3 reacties »
Door: Stephan Oudmaijer, 16 January 2010
Spring 3.0 has support for REST style WebServices, the Spring MVC controllers facilitate the functionality. In this example I will show an example of how to implement a basic REST service that uses XML marshalling to sent information over HTTP. Disclamier: this is not an in depth tutorial for building REST style WebServices.
The Spring MVC controller
The Spring 3.0 REST support relies havily on Spring MVC. We should use the Controller class for implementing a REST style WeService. To declare a Controller I use the Spring annotation based configuration. In this example the ProductRestService class is annotated with @Controller annotation. In order for Spring to pick-up the annotation Spring needs to be configured to scan for annotation (see the Spring configuration section).
REST uses templates that describe the URI to be used to invoke a WebService method. These URI templates can contain variable placeholders which allow for passing information to the WebService. The URI should typically contain all the information required for invoking a WebService method.
The @RequestMapping annotation allowes you to define the URI and HTTP method that are mapped to a method. In this example I have annotated the ProductRestService.getProductById(Long productId) with the @RequestMapping.
The value of the @RequestMapping, in this case: /products/{productId} , defines the URI that is mapped to this method. The productId variable needs to be defined when invoking the method and will be resolved automatically by Spring MVC with the value from the request URI. You can use the @PathVariable to inject the value of the productId variable directly into a method parameter.
The @ResponseBody annotation tells Spring to marshall the return value of the method to the HTTP response body. Spring allowes you to configure HTTP message converters that take care of conversion of the return value to a format which is accepted by the client. In this example the return value will be marshalled to XML using XStream.
package com.oudmaijer.spring.rest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* This is an example REST style MVC controller. It serves as an
* endpoint for retrieving Product Objects.
*/
@Controller
public class ProductRestService {
/**
* This method returns a specific Product. The URI to request a Product is
* specified in the @RequestMapping.
*
* @param productId the identifier of the requested product
* @return a Product
*/
@RequestMapping(value="/products/{productId}", method = RequestMethod.GET)
@ResponseBody
public Product getProductById(@PathVariable Long productId) {
Product p = new Product();
p.setId(productId);
return p;
}
}
Spring configuration
The configuration is where all the magic happens. It is important to define the <mvc:annotation-driven /> element at the end of the configuration file or else Spring will not register the marshallingHttpMessageConverter. It took me some time to figure this out ;(
You need to add the MessageConverters to the configuration in order to get the OXM marshalling to work. Spring uses the requests Accept header to determine which converter to use.
Maven2 dependencies
You need to add a couple of Maven2 dependencies to get the project up and running. Below is the entire pom.xml.
Web deployment descriptor: web.xml
Last but not least the web.xml. Since the REST support in Spring is based on Spring MVC you need to define the DispatcherServlet. Make sure to map the correct URL pattern to the DispatcherServlet.
Invoking the service
This example only supports the HTTP GET method. If you want to test or build a client that uses REST WebServices you should use the RestTemplate in Spring. We can easily validate if the example WebService is running by accessing the service through Firefox. This will result in the following response.

For more information on REST support in Spring 3.0 please refer to the Spring reference documentation.
Gepost in Algemeen | 2 reacties »
Door: Sander Abbink, 15 January 2010
If you want to test objects in isolation it is often usefull to use Mocks. Here is how you can do this with the Mockito framework.
First the maven dependency:
org.mockito
mockito-all
1.8.1
If you don’t use a Maven plugin in let’s say Eclipse, then you can create a directory testlib which contains the jar. Add this jar to the buildpath (this won’t affect the Maven build).
It is also handy to use the following static imports:
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
Tip for Eclipse: if you want to prevent organize imports (ctrl+shift+o) to resolve the static imports: java -> code style -> organize imports -> Number of static imports needed for (set to 1).
Creating a Mock object:
List mockedlist = mock(ArrayList.class);
mockedlist.add("Hello");
String value = mockedlist.get(0);
mockedlist.get(5);
All the methods in ArrayList are mocked. So the String “Hello” won’t actually be added to the List (e.g. value == null). Also get(5) won’t throw an IndexOutOfBoundsException.
You can also stub method calls, like this:
List mockedlist = mock(ArrayList.class);
when(mockedlist.get(0)).thenReturn("Hello");
Or verify invocations:
String value = "Hello";
verify(mockedlist).get(0);
verify(mockedlist).add(eq(value));
verifyNoMoreInteractions(mockedlist);
eq is a method in the Matchers class. It will verify that an object is added to the mocked List which is equal to the String “Hello”. If you use a Matcher for one argument in a method, then you have to use a Matcher for all the other arguments too.
See javadoc for the other Matchers methods http://mockito.googlecode.com/svn/branches/1.5/javadoc/org/mockito/Matchers.html
You can also write your own Matcher, although this is rarely neccesary. An example:
class IsStringEqualButNotSame extends ArgumentMatcher {
private String originalString;
public IsStringEqualButNotSame (String originalString) {
this.originalString= originalString;
}
public boolean matches(Object value) {
return ((String)value).equals(originalString) && value != originalString;
}
}
String value = "Hello";
verify(mockedlist).add(argthat(new IsStringEqualButNotSame(value));
This Matcher will match if a String is logically equal but the object is not the same. Not the best example but you can make Matchers this way.
Spying on real objects. You can spy a real object to verify interactions or to stub only one particular method. An example:
List myList = new ArrayList<>()
List myListSpy = spy(myList);
myListSpy.get(5); // will throw IndexOutOfBoundsException
when(myListSpy.get(5)).thenReturn("Hello"); // will throw IndexOutOfBoundsException
If you stub a method like the example above the real method will still be called. You must use a slightly different syntax for this:
doReturn("Hello").when(myListSpy.get(5));
Additional sources:
Mockito site
Mockito vs EasyMock
Not really related to Mockito. If you annotate a method with @Before this method will be called before every unittest in the class.
If you annotate a method with @BeforeClass this method will only be called once. This method must be static.
Gepost in Algemeen | 2 reacties »
Door: Peter Schuler, 14 January 2010
As promised in my previous post I will blog some more about JPA and how to use it. In this post I will go into the locking features of JPA 2.0 including the new pessimistic lock options.
This post will:
- introduce the new locking features of the JPA;
- introduce both pessimistic locking and optimitic locking concepts;
- give a quick recap about JPA versioning;
- talk about the connection between locking and design;
- and finally compare both locking strategies.
JPA 2.0 now supports Pessimistic Locking:
A great omission of JPA 1.0 was the lack of pessimistic locking. Therefore it was necessary to fall back on the support of the underlying implementation to use the JPA is situation where pessimistic locking was required. This can happen when JPA shares a database with another process which does not know or supports versioning based optimistic locking.
JPA 2.0 now supports the following locking modes:
- OPTIMISTIC (==READ in JPA 1.0)
- OPTIMISTIC_FORCE_INCREMENT (==WRITE in JPA 1.0)
- PESSIMISTIC_READ
- PESSIMISTIC_WRITE
- PESSIMISTIC_FORCE_INCREMENT (A hybrid of both strategies)
- READ (kept around for backward compatibility)
- WRITE (kept around for compatibility)
Object can be locked by using the find() or refresh() operation of the EntityManager. For example:
Order order = entityManager.find(Order.class, 10, LockModeType.PESSIMISTIC_READ);
SELECT ID, PRODUCT, AANTAL, VERSION, orderId FROM ORDER_TABLE WHERE (orderId = ?) FOR UPDATE.
As you can see the FOR UPDATE is added to the select query telling the database to get an exclusive lock on this selected row.
You can also use the lock() method on the entityManager and specify a Lock Mode on Queries (JPQL / Named and Criteria).
Now that we know how to unleash the power of pessimistic locking we need to learn how to use it well.
Locking Strategies: a quick recap….
Locking is a means to prevent data form becoming corrupted because two different processes are editing the same data. If we use locking correctly no two processes can edit (or if required) access the same data. Thus data can never be inconsistent.
As already mentioned there are two locking strategies: optimistic locking and pessimistic locking. I will describe both strategies and give an overview of their pro’s and con’s.
Pessimistic locking
This strategy is the standard locking provided by the database. It will protect data by limiting access to a single process. This is achieved by keeping track of all the currently active locks. If another process wants to access locked data it will have to wait until the other process releases the lock. Of course this introduces a whole range of potential errors like lock timeouts and deadlocks.
This locking strategy is called pessimistic because of the assumption that locking is always necessary to avoid corruption. Based on that assumption it introduces significant overhead in order to keep track of which process is assessing which data. Compare pessimistic locking to a traffic light. It will only allow vehicles to pass when it knows for sure that no one will be in the way.
Using pessimistic locking has some pro’s:
- The database is in charge and protects your data. Independent from application logic.
- A process or thread can only proceed if it has the right locks. Thus it is guaranteed that there will be no conflicts once the lock is acquired.
- Processes are put on hold until they can acquire the lock. (This blessing can also be a curse because a process can overwrite data the moment the lock is released. This feels like a missing update but is technically the correct behaviour. But as long as you read and write in the same transction you’re data is never stale.)
No pro’s without con’s:
- Keeping track of all those locks introduces significant overhead. Even if there is no data being accessed simultaneous the database still locks.
- The locking can lead to deadlocks and lock time out. These errors are hard to recover from and take a long time before the calling process is informed.
- Must be supported by the database.
So pessimistic locking depends on the database restricting access to data. But this comes at high overhead and hard-to-recover errors.
Optimistic locking
As pessimistic locking is embedded in the DBMS, optimistic locking is a strategy that by-passes the database. It will detect conflicts only when they occur. This is done introducing a version number to every table you want to protect. If you read data you will get the version number. If you alter the data you first check the version number again, and when holding the previous read value, update the record and increment the version number. If some one has “changed the data right from under you” you will see a different version number and know that there is a conflict. I will refer to the optimistic lock procedure as check&update.
This strategy is called optimistic because it never bothers to lock. It assumes that process will not bother each other until they do.
Using optimistic locking has some big pro’s:
- There is no (at least very little) overhead involved in locking.
- Optimistic locking is fast and easy to use, especially because it works implicitly. If you specify a @Version the upate&check will be performed automatically.
- It’s very efficient.
- It is database independent. No special features are required.
There are also some drawbacks:
- It will only detect conflicts, not prevent them. When it occurs it’s the application that must resolve the conflict. For example by showing the user a diff or an option to override the current version in the database.
- If a conflict occurs only one process is allowed to proceed. The others have their database transaction rolled back. This is far more expensive than waiting until you get the database lock.
- It will only work if everyone accessing the database plays by the versioning rules. The database does not enforce it.
- It can be considered ‘unfair’ as the process that writes the data first wins, opposed to the process that first acquired the lock.
- Sometimes optimistic locking is not sufficient. Locking a complete table to protect against insert for example.
So optimistic locking depends on the calling processes to respect the versioning rules. This makes it possible to detect conflicts and eliminates the need to keep of all the locks and gives Optimistic locking a huge advantage.
However when conflicts occurs it is up to the application to patch things up.
JPA support for optimistic locking
JPA supports optimistic locking based on versioning right from the first release. All you need to do is declare an attribute of your class with a @Version annotation.
For example:
@Entity
public class Order {
@id @GeneratedValue
private Integer id;
@Version
private Integer version;
}
The above code will result in a Order table with a primary key and version column. JPA will check and update the version after every change to Order.
More on JPA versioning can be found here.
Lock scope.
At first glance versioning seems to be the preferred strategy. It’s easy to use and with little overhead. However there is one more aspect to take into account when dealing with locking. That is what I call ‘the lock scope’.
Versioning will only lock (check&update) records that were changed. Databases will only lock records you tell it to lock by doing a SELECT … FOR UPDATE. Both procedures prevent processes from corrupting the database. But it will not prevent breaking business rules!
Let’s look at the following example:

This is a typical Order->OrderLine example. Order has a set of OrderLines which keep a price and quantity for every single item in Order. Let’s assume that there is a business rule that the total amount of money of an Order must stay below $10.000. This is easily achieved by adding a check on order to make sure that every addition/alteration of OrderLines will not break this rule.
A problem occurs when another process comes in and adds OrderLines to an Order at the same time. No single process knows all OrderLines. To make the check work in a concurrent environment you need to make the OrderLine updates in a serial order. In other words: the Order needs to be locked before any additions can be made to OrderLines. This ensures that the business rule can be enforced.
The JPA can achieve this by using one of the two lock levels: OPTIMISTC_FORCE_INCREMENT or PESSIMITC_WRITE. Both will give you a exclusive lock to make sure no other process can edit the same data.
This example illustrates that there are situations in which you need to think ahead about locking. Both versioning and database locks won’t help you out-of-the-box . You need to determine the right lock scope. Determining the lock scope is a business question and needs to be defined based on the functional design and then translated to technical requirements.
Choosing a locking Strategy.
Ok .. now you know about the pro’s and con’s of both locking strategies. You know how to use them technically and you know you need to think about the lock scope. So which strategy is for winners?
As you probably have guessed there is no straightforward answer.
Optimistic locking has little overhead and is easy to use, especially because it works implicitly in JPA. But you need to make sure that everyone using the database uses the same versioning approach. It’s also more expensive in terms of conflict resolving.
Optimistic locking is the preferred strategy if:
- You’re application has a private database.
- All the applications using the database know and use versioning.
- It is unlikely that there will be a lot of conflicts. (eg. Users editing the same data.)
Pessimistic locking will protect data on the database level. It will prevent conflicts by putting the process in a queue to wait for the lock. If there are a lot of collisions this gives a better change of more processes making it through. However having to keep a large lock administration involves a lot of overhead even if there a no conflicts.
So pessimistic locking it the preferred strategy if:
- Other non-versionized processes will edit the data you need to lock.
- You predict / see that there will be a lot of colissions.
For those among us unable to choose, JPA offers a hybrid solution. If you use the lock option PESSIMISTIC_FORCE_INCREMENT both Pessimitic and Optimisic locks are acquired at the same time. Offcourse you’re cutting of both your hands when using this option for every database call…. “Just to be sure .. “. You’ll end up with the bad from both locking strategies. But this hybird option can be a life saver when a particular table or operation must be protected at a database level and still has to participate in versionized transactions.
More information on locking
And don’t forget to think about the lock scope!
This is the second installment of my blogs about the JPA. Next time we’ll go into the new Criteria API of JPA 2.0.
- Special thanks to Martijn Blankestijn for the Order example and Jouke Stoel for test reading.
Gepost in Algemeen, Java API, Object Relational Mapping | Geen reacties »
Door: Stephan Oudmaijer, 29 December 2009

JA-SIG Central Authentication Service (CAS) is an enterprise level, open-source, single sign on solution with a Java server component and various client libraries written in a multitude of languages including PHP, PL/SQL, Java, .Net, PHP, Perl and more.
Both Spring Security 3.0 and Spring 3.0 where released this month. Spring Security provides excelent support for CAS. In Spring Security 3.0 a couple of CAS integration components have been changed (renamed). The configuration is also a bit different from Spring Security 2.0.x.
How CAS works
The CAS Server webapp should be deployed on an application server. Applications can use the CAS Server for the authentication process. CAS only provides authentication and no authorisation. The authorisation should be implemented (using Spring Security) by the applications using the CAS Server.
How Spring Security fits in
Lets say an user tries to access a protected resource within an application using Spring Security. Spring Security intercepts the request and checks if the user should be authenticated. If so, the user is forwarded tot the CAS login page. The users typically enters his username and password and submits it to the CAS server. If the user was successfully authenticated by CAS, the users will be redirected back to the application where it was accessing a protected resource. The redirect URL now contains a ticket generated by CAS. Spring Security will use this ticket to validate against CAS if the ticket is valid for this user. If so, the user details will be loaded by Spring Security. If the user is also authorised to access the protected resource, access will be granted.
Configuration
For my demo I use the CAS server webapp version 3.3.4. I have it deployed on Apache Tomcat 6.0.20. In the demo I access the CAS Server using HTTP, this should be HTTPS in a production environment! I have deployed the applications using the following URLs:
The CAS Server web application: http://localhost:8080/cas-server-webapp-3.3.4/
The application using CAS: http://localhost:8080/spring-security-cas/
I use Maven2 for managing my dependencies, the following libraries should be added to the pom.xml.
Maven2 dependencies
org.springframework
spring-core
3.0.0.RELEASE
false
org.springframework
spring-webmvc
3.0.0.RELEASE
false
org.springframework.security
spring-security-core
3.0.0.RELEASE
false
org.springframework.security
spring-security-config
3.0.0.RELEASE
false
org.springframework.security
spring-security-cas-client
3.0.0.RELEASE
false
Spring Security configuration
Please be aware that the Spring Security reference documentation is not 100% accurate on the CAS integration.
web.xml
webapp
contextConfigLocation
/WEB-INF/applicationContext-security.xml
org.springframework.web.context.ContextLoaderListener
springSecurityFilterChain
org.springframework.web.filter.DelegatingFilterProxy
springSecurityFilterChain
/*
index.html
index.jsp
Thats it, try it yourself!
Original article posted at: http://oudmaijer.com
Gepost in Algemeen | Geen reacties »
Door: Stephan Oudmaijer, 21 December 2009
The last month of 2009 has brought some exciting Java news, both Java EE 6 and Spring 3.0 have become final this month!
Spring Framework 3.0 GA
Spring 3.0 GA is compatible with Java EE 6 final in terms of runtime environments now (e.g. on GlassFish v3 as released last week) and supports JPA 2.0 final already (e.g. using EclipseLink 2.0). We also support the newly introduced @ManagedBean (JSR-250 v1.1) annotation for component scanning now, which nicely complements our @Inject (JSR-330) support for annotation-driven dependency injection.
* Spring expression language (SpEL): a core expression parser for use in bean definitions, allowing for references to nested bean structures (e.g. properties of other beans) as well as to environmental data structures (e.g. system property values) through a common #{…} syntax in property values.
* Extended support for annotation-based components: now with the notion of configuration classes and annotated factory methods (as known from Spring JavaConfig). Spring also allows for injecting configuration values through @Value expressions now, referring to configuration settings via dynamic #{…} expressions or static ${…} placeholders.
* Powerful stereotype model: allows for creating ’shortcut’ annotations through the use of meta-annotations, e.g. for default scopes and default transactional characteristics on custom stereotypes. Imagine a custom @MyService annotation indicating @Service, @Scope(“request”) and @Transactional(readOnly=true) through a single annotation.
* Standardized dependency injection annotations: Spring 3.0 comes with full support for the JSR-330 specification for Dependency Injection in Java – annotation-driven injection via @Inject and its associated qualifier and provider model, as an alternative to Spring’s own @Autowired and co.
* Declarative model validation based on constraint annotations: Spring-style setup of a JSR-303 Bean Validation provider (such as Hibernate Validator 4.0). Comes with an annotation-driven validation option in Spring MVC, exposing a unified view on constraint violations through Spring’s binding result facility.
* Enhanced binding and annotation-driven formatting: Converter and Formatter SPIs as an alternative to standard PropertyEditors. Formatting may be driven by annotations in a style similar to JSR-303 constraints, e.g. using @DateTimeFormat. Also, check out the new mvc namespace for convenient setup of formatting and validation in Spring MVC.
* Comprehensive REST support: native REST capabilities in Spring MVC, such as REST-style request mappings, URI variable extraction through @PathVariable parameters, and view resolution driven by content negotiation. Client-side REST support is available in the form of a RestTemplate class.
* Rich native Portlet 2.0 support: Spring MVC fully supports Portlet 2.0 environments and Portlet 2.0’s new event and resource request model. Includes specialized mapping facilities for typical portlet request characteristics: @ActionMapping, @RenderMapping, @ResourceMapping, @EventMapping.
* Object/XML Mapping (OXM): as known from Spring Web Services, now in Spring Framework core. Marshalling and Unmarshaller abstractions with out-of-the-box support for JAXB 2, Castor, etc. Comes with integration options for XML payloads in Spring MVC and Spring JMS.
* Next-generation scheduling capabilities: new TaskScheduler and Trigger mechanisms with first-class cron support. Spring 3.0 comes with a convenient task namespace and also supports @Async and @Scheduled annotations now. This can be executed on top of native thread pools or server-managed thread pools.
Java EE 6
From Roberto Chinnici’s weblog:
With the closing of the final approval ballot earlier today, it is now official: the JCP Executive Committee has given a green light to the release of the Java EE 6 platform specification. The final release will happen on December 10, when GlassFish v3 will be available. For more details of the ballot, with comments from several EC members, please refer to the JCP web site. Of course the excitement of the event drove me to watch live the ballot close at midnight PT and tweet about it!
Several other Java EE component JSRs were approved at the same time: Servlet 3.0, JPA 2.0, EJB 3.1, Connector 1.6, CDI 1.0. All other components, be they full JSRs or maintenance releases (MRs, for insiders), had been previously approved. I should also mention here that, being part of the platform JSR (JSR-316) the Java EE 6 Web Profile too was approved, and so was the Managed Beans 1.0 specification I talked about in prior blog entries. So, yes, now we really have profiles in Java EE: let’s put them to good use!
We are going to have more white papers, tutorials, etc. coming up for the final release in a few days. In the meantime, even a casual perusal of the javadocs will show a number of new APIs in key areas: JAX-RS, Dependency Injection, CDI, Bean Validation. I see a bright future for these APIs, and fully expect them to become key components of Java EE applications in the coming years. I also happen to think that the level of integration that we achieved between these new APIs and some of the existing ones represents a valuable principle that can guide the evolution of Java EE going forward; certainly I expect future Java EE APIs to be held to the same strict criteria for integration with the rest of the platform that JAX-RS, Bean Validation and CDI were held to in this release.
Java EE 6 includes:
- Java Persistency API 2.0
- JavaServer Faces 2.0
- Enterprise JavaBeans 3.1
- Servlet 3.0
- Context and Dependecy Injection (a.k.a. WebBeans)
- Dependency Injection (@Inject)
- JAX-RS
- Web Profile
- and much more…
See also this article for more information: http://java.sun.com/developer/technicalArticles/JavaEE/JavaEE6Overview.html
So if you are bored during the christmas holiday, you can try out the new Java EE 6 features using GlassFish v3 and NetBeans 6.8. But also IntelliJ 9 and Eclipse 3.5.1 feature Java EE 6 support.
Gepost in Algemeen | Geen reacties »
Door: Ron Thijssen, 16 December 2009
Just received an email message from the jsr-314 mailing list, where Ed Burns states that he will be working on creating the new Sun Certified JSF Developer exam.
Looking foreward on taking this examen when it’s finished, but first let’s submit some questions
I’m going heads-down trying to help create the new Sun Certified JSF
Developer exam (and accompanying course) so I’ll be slower than usual to
respond to emails.
If you need an immediate response, call me on my phone below.
If you want to help out with the exam, submit questions here:
<http://bit.ly/jsf2certexam>.
Thanks for your understanding!
Ed
Gepost in Algemeen | Geen reacties »
Door: gnoij, 7 December 2009
Het is alweer enige tijd geleden dat ik heb geschreven over temporale patterns. In dit deel wil ik het bitemporale pattern uitbreiden met bitemporale collections. Werd met de bitemporale property nog een enkele property historisch gemaakt, in dit deel maken we een lijst historisch. Dat wil zeggen dat er meerdere elementen van een historische lijst tegelijkertijd geldig kunnen zijn.
De klasse BiTemporalObject uit het derde deel blijft hetzelfde. En naast de BiTemporalProperty voor enkelvoudige historische relaties krijgen we nu ook een klasse BiTemporalCollection voor meervoudige historische relaties.
BiTemporalCollection
public class BiTemporalCollection {
protected List alleHistorischeVersies = new ArrayList();
public BiTemporalCollection() {
super();
}
public List getActueleVersies() {
return getVersieOp(new Date(), new Date());
}
public List getVersieOp(final Date registratieTijdstip, final Date peilDatum) {
return (List) CollectionUtils.select(this.alleHistorischeVersies, new Predicate() {
public boolean evaluate(Object object) {
return ((BiTemporalObject) object).isGeldigOp(registratieTijdstip, peilDatum);
}
});
}
public void voegActueleVersieToe(BiTemporalObject actueleVersie) {
if (actueleVersie == null) {
throw new IllegalArgumentException("actueleVersie is null");
}
this.alleHistorischeVersies.add(actueleVersie);
}
public void wijzigActueleVersie(BiTemporalObject nieuweVersie, BiTemporalObject oudeVersie) {
if (nieuweVersie == null) {
throw new IllegalArgumentException("nieuweVersie is null");
}
if (oudeVersie == null) {
throw new IllegalArgumentException("oudeVersie is null");
}
beeindigVorigeVersie(nieuweVersie, oudeVersie);
this.alleHistorischeVersies.add(nieuweVersie);
}
private void beeindigVorigeVersie(final BiTemporalObject nieuweVersie, final BiTemporalObject oudeVersie) {
BiTemporalObject afTeVoerenVersie = zoekActueleVersie(oudeVersie, nieuweVersie.getIngangsdatum(), nieuweVersie.getOpvoerTijdstip());
if (afTeVoerenVersie == null) {
throw new IllegalStateException("Geen oude actuele versie gevonden!");
}
beeindigVersie(afTeVoerenVersie, nieuweVersie.getIngangsdatum(), nieuweVersie.getOpvoerTijdstip());
}
public void beeindig(final BiTemporalObject actueleVersie, final Date einddatum) {
BiTemporalObject afTeVoerenVersie = zoekActueleVersie(actueleVersie, einddatum, new Date());
if (afTeVoerenVersie == null) {
throw new IllegalStateException("Geen oude actuele versie gevonden!");
}
beeindigVersie(afTeVoerenVersie, einddatum, new Date());
}
public void beeindig(final Date einddatum) {
List afTeVoerenVersies = (List) CollectionUtils.select(this.alleHistorischeVersies, new Predicate() {
public boolean evaluate(Object object) {
BiTemporalObject versie = (BiTemporalObject) object;
return versie.isGeldigOp(new Date(), einddatum);
}
});
CollectionUtils.forAllDo(afTeVoerenVersies, new Closure() {
public void execute(Object input) {
beeindigVersie((BiTemporalObject) input, einddatum, new Date());
}
});
}
private void beeindigVersie(BiTemporalObject versie, Date einddatum, Date registratieTijdstip) {
BiTemporalObject kopieVersie = versie.kopieer(einddatum, registratieTijdstip);
this.alleHistorischeVersies.add(kopieVersie);
}
private BiTemporalObject zoekActueleVersie(final BiTemporalObject actueleVersie, final Date peildatum, final Date registratieTijdstip) {
return (BiTemporalObject) CollectionUtils.find(this.alleHistorischeVersies, new Predicate() {
public boolean evaluate(Object object) {
BiTemporalObject versie = (BiTemporalObject) object;
return versie.equals(actueleVersie) && versie.isGeldigOp(registratieTijdstip, peildatum);
}
});
}
De wijzigingen ten opzichte van de BiTemporalProperty uit het vorige deel zijn dat er nu niet één maar meer versies tegelijkertijd geldig kunnen zijn (getActueleVersies) en dat we versies kunnen toevoegen (voegActueleVersieToe) en kunnen wijzigen (wijzigActueleVersie). Bij deze laatste methode we de te wijzigen versie meegeven, zodat deze beëindigd kan worden en de nieuwe versie toegevoegd wordt. Ook kunnen we alle versies van de collection beëindigen (beeindig) of een enkele versie (die dan weer aan de methode meegegeven moet worden).
Een voorbeeld
In dit voorbeeld wordt het voorbeeld uit deel 3 uitgebreid met een manager (zelf ook een werknemer), die meerdere werknemers onder zich heeft.
Manager
public class Manager extends Werknemer {
private static final long serialVersionUID = 1L;
private BiTemporalCollection werknemers = new BiTemporalCollection();
public Manager() {
super();
}
public Manager(String naam) {
super(naam);
}
public void voegWerknemerToe(Werknemer werknemer, Date ingangsdatum) {
this.werknemers.voegActueleVersieToe(new WerknemerRelatie(werknemer, ingangsdatum));
}
public List getTeManagenWerknemers() {
List relaties = getWerknemerRelaties();
CollectionUtils.transform(relaties, new Transformer() {
public Object transform(Object object) {
return ((WerknemerRelatie)object).getWerknemer();
}
}) ;
return relaties;
}
public List getTeManagenWerknemers(Date registratieTijdstip, Date peildatum) {
List relaties = getWerknemerRelaties(registratieTijdstip, peildatum);
CollectionUtils.transform(relaties, new Transformer() {
public Object transform(Object object) {
return ((WerknemerRelatie)object).getWerknemer();
}
}) ;
return relaties;
}
public List getWerknemerRelaties() {
return this.werknemers.getActueleVersies();
}
public List getWerknemerRelaties(Date registratieTijdstip, Date peildatum) {
return this.werknemers.getVersieOp(registratieTijdstip, peildatum);
}
public void wijzigWerknemer(Werknemer nieuweWerknemer, Werknemer oudeWerknemer, Date wijzigingsdatum) {
WerknemerRelatie nieuweRelatie = new WerknemerRelatie(nieuweWerknemer, wijzigingsdatum);
WerknemerRelatie oudeRelatie = bepaalWerknemerRelatie(oudeWerknemer);
this.werknemers.wijzigActueleVersie(nieuweRelatie, oudeRelatie);
}
private WerknemerRelatie bepaalWerknemerRelatie(final Werknemer werknemer) {
return (WerknemerRelatie)CollectionUtils.find(this.werknemers.getActueleVersies(), new Predicate() {
public boolean evaluate(Object obj) {
return ((WerknemerRelatie)obj).getWerknemer().equals(werknemer);
}
});
}
public void stopManagenVanWerknemer(Werknemer werknemer, Date einddatum) {
WerknemerRelatie relatie = bepaalWerknemerRelatie(werknemer);
this.werknemers.beeindig(relatie, einddatum);
}
public void stopManagen(Date einddatum) {
this.werknemers.beeindig(einddatum);
}
}
Deze klasse representeert de manager. Als een manager een werknemer gaat managen, wordt de werknemer toegevoegd aan de lijst van te managen werknemers (voegWerknemerToe). Als een werknemer wordt vervangen door een andere werknemer wordt de methode wijzigWerknemer aangeroepen, waardoor de relatie met de oude werknemer wordt beëindigd en de nieuwe werknemer wordt begonnen. Als een werknemer uit dienst gaat of naar een andere afdeling, stopt de manager met het managen van deze werknemer (stopManagenVanWerknemer), waardoor de historische relatie van de manager met de werknemer wordt beëindigd. Als de manager stopt met managen (stopManagen), wordt de relatie met alle gemanagede werknemers beëindigd.
De historische relatie van de manager met de werknemer wordt gerepresenteerd door de klasse WerknemerRelatie.
WerknemerRelatie
public class WerknemerRelatie extends BiTemporalObject {
private static final long serialVersionUID = 1L;
private Werknemer werknemer;
protected WerknemerRelatie() {
super();
}
protected WerknemerRelatie(Werknemer werknemer, Date ingangsdatum) {
super(ingangsdatum);
this.werknemer= werknemer;
}
public Werknemer getWerknemer() {
return this.werknemer ;
}
}
De test ziet er als volgt uit:
public void testManager() {
Manager jan = new Manager("Jan");
// simuleer de opvoer tijd 1-1-2003
Date aanvangsdatum = DateUtils.maakDate(2003, 1, 1);
BiTemporalObject.TEST_OPVOER_TIJDSTIP = aanvangsdatum;
Afdeling inkoop = new Afdeling("Inkoop");
jan.setAfdeling(inkoop, aanvangsdatum);
Werknemer kees = new Werknemer("Kees");
kees.setAfdeling(inkoop, aanvangsdatum);
jan.voegWerknemerToe(kees, aanvangsdatum);
Werknemer piet = new Werknemer("Piet");
piet.setAfdeling(inkoop, aanvangsdatum);
jan.voegWerknemerToe(piet, aanvangsdatum);
assertEquals(2, jan.getTeManagenWerknemers().size());
assertTrue(jan.getTeManagenWerknemers().contains(kees));
assertTrue(jan.getTeManagenWerknemers().contains(piet));
Date wijzigingsdatum = DateUtils.maakDate(2006, 1, 1);
BiTemporalObject.TEST_OPVOER_TIJDSTIP = wijzigingsdatum;
Werknemer johan = new Werknemer("Johan");
johan.setAfdeling(inkoop, wijzigingsdatum);
// Johan vervangt Piet, die uit dienst gaat
jan.wijzigWerknemer(johan, piet, wijzigingsdatum);
piet.uitDienst(wijzigingsdatum);
assertEquals(2, jan.getTeManagenWerknemers().size());
assertTrue(jan.getTeManagenWerknemers().contains(johan));
assertFalse(jan.getTeManagenWerknemers().contains(piet));
// jan managete gisteren piet nog wel
Date gisteren = DateUtils.maakDate(2005, 12, 31);
assertTrue(jan.getTeManagenWerknemers(new Date(), gisteren).contains(piet));
Date einddatum = DateUtils.maakDate(2009, 1, 1);
BiTemporalObject.TEST_OPVOER_TIJDSTIP = wijzigingsdatum;
jan.stopManagenVanWerknemer(kees, einddatum);
kees.uitDienst(einddatum);
assertEquals(1, jan.getTeManagenWerknemers().size());
assertFalse(jan.getTeManagenWerknemers().contains(kees));
jan.stopManagen(einddatum);
assertTrue(jan.getTeManagenWerknemers().isEmpty());
}
In deze test maken we een manager Jan aan, die werkt op de afdeling Inkoop op 1 januari 2003. Vanaf deze dag begint hij ook met het managen van twee werknemers Kees en Piet. Vanaf 1 januari 2006 vervangt een nieuwe werknemer Johan Piet, die uit dienst gaat. Op 1 januari 2009 stopt Jan met het managen van al zijn werknemers.
Hibernate mappings
De hibernate mapping van de klasse WerknemerRelatie is analoog aan de mapping van de AfdelingRelatie uit deel 3.
De mapping van de werknemer is uitgebreid met de subclass Manager, die de werknemers als BiTemporalCollection property mapt.
Werknemer.hbm.xml
<hibernate-mapping package="nl.ordina.bitemporal.example" default-access="field">
<class name="Werknemer" table="Werknemer" discriminator-value="Werknemer">
<id name="id" column="id">
<generator class="identity"></generator>
</id>
<discriminator column="type" />
<version name="versie" />
<!-- properties -->
<property name="naam" column="naam" />
<!-- de verwijzing naar de afdelingrelatie -->
<component name="afdelingRelatie"
class="nl.ordina.temporal.bitemporal.BiTemporalProperty"
lazy="false">
<bag name="alleHistorischeVersies"
cascade="all, delete-orphan" >
<key column="werknemerId" />
<one-to-many
class="AfdelingRelatie" />
</bag>
</component>
<subclass name="Manager" discriminator-value="Manager">
<!-- de verwijzing naar de werknemerrelatie -->
<component name="werknemers"
class="nl.ordina.temporal.bitemporal.BiTemporalCollection"
lazy="false">
<bag name="alleHistorischeVersies"
cascade="all, delete-orphan" >
<key column="managerId" />
<one-to-many
class="WerknemerRelatie" />
</bag>
</component>
</subclass>
</class>
</hibernate-mapping>
LET OP: In bovenstaand artikel wordt gesproken over BiTemporalCollection. Dit is niet dezelfde als de BiTemporalCollection van Fowler , wat eigenlijk de BiTemporalProperty uit deel 3 is.
Gepost in Algemeen, Java language, Tools/Frameworks, patterns | Geen reacties »
| |