Sonntag, 30. Oktober 2011

Spring Dependencies Structure

Based on the "Diagram of Spring 3.0 module dependencies" from Osvaldas Grigas and the spring poms I made a simple yUML diagram. The diagram gives a short overview of the spring components and there dependencies. The green marked component is the core functionality of spring. The blue marked components provides functions based on the spring core.

Here the source of the yUML diagram, if you like to add some aspects or change something feel free and reuse it.
[Spring Test {bg:red}]-.->[Spring Context {bg:green}]
[Spring Test {bg:red}]-.->[Spring JDBC {bg:blue}]
[Spring Test {bg:red}]-.->[Spring ORM {bg:blue}]
[Spring Test {bg:red}]-.->[Spring TX {bg:blue}]
[Spring Test {bg:red}]-.->[Spring Web {bg:blue}]
[Spring Test {bg:red}]-.->[Spring Web MVC {bg:blue}]
[Spring ORM {bg:blue}]-.->[Spring JDBC {bg:blue}]
[Spring JDBC {bg:blue}]-.->[Spring TX {bg:blue}]
[Spring Web MVC {bg:blue}]-.->[Spring Context Support {bg:green}]
[Spring Web MVC {bg:blue}]-.->[Spring Web {bg:blue}]
[Spring Web {bg:blue}]-.->[Spring Context {bg:green}]
[Spring TX {bg:blue}]-.->[Spring Context {bg:green}]
[Spring JMS {bg:blue}]-.->[Spring Context {bg:green}]
[Spring OXM {bg:blue}]-.->[Spring Context {bg:green}]
[Spring Context {bg:green}]-.->[Spring AOP {bg:green}]
[Spring Context {bg:green}]-.->[Spring Beans {bg:green}]
[Spring Context {bg:green}]-.->[Spring Core {bg:green}]
[Spring Context {bg:green}]-.->[Spring Expression {bg:green}]
[Spring Context Support {bg:green}]-.->[Spring Context {bg:green}]
[Spring Beans {bg:green}] -.->[Spring Core {bg:green}]
[Spring AOP {bg:green}] -.->[Spring Core {bg:green}]
[Spring AOP {bg:green}] -.->[Spring Beans {bg:green}]
[Spring Expression {bg:green}]-.->[Spring Core {bg:green}]
[Spring Core {bg:green}]-.->[Spring ASM {bg:green}]
view raw spring.yuml hosted with ❤ by GitHub

Links

Donnerstag, 27. Oktober 2011

Spring Customize Annotation Scanning

A really nice feature in Spring 3.0 is to have custom annotation. Why do you like to have own annotations? Because you could provide some semantic details about the component types. For example when you have a spring bean which is facade, why not use a annotation with the name facade?

Here the spring wiring for beans with the annotation facade:
<context:component-scan base-package="demo.design">
<context:include-filter type="annotation"
expression="com.seitenbau.demo.stereotypes.Facade" />
</context:component-scan>

The facade annotation:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Facade {}
view raw Facade.java hosted with ❤ by GitHub

And here a demo facade spring bean:
@Facade
public class AddressFacadeImpl implements AddressFacade
{
private AddressService addressService;
private UserRepository userRepository;
@Override
public List<AdresseBean> getAdresses() throws ApplicationException
{
return addressService.getAdresses();
}
@Override
public void saveAdresse(AdresseBean adresse) throws ApplicationException
{
addressService.saveAdresse(adresse);
}
@Override
public boolean userExists(String username)
{
return userRepository.userExists(username);
}
@Autowired
public void setAddressService(AddressService addressService)
{
this.addressService = addressService;
}
@Autowired
public void setUserRepository(UserRepository userRepository)
{
this.userRepository = userRepository;
}
}

Spring DI with Java Standard Annotations

In Spring it is easy to use the Java annotations for dependency injection (JSR 330), the Java annotation for post construct and pre destroy (JSR 250) and the Java API and Annotations for validation (JSR 303).

Why should I use this standard APIs and annotation in a Spring based application? Because when using this standards, the code has only dependency on standard APIs (javax). And the code could also be used in another implementation e.g. of the JSR 330.

Here a simple code snippet, which shows how to use this three Java standards in a spring bean.

import javax.validation.constraints.NotNull;
public class Person {
@NotNull // JSR 303
private String name;
public String getName(){ return name; }
public void setName(String name){ this.name = name;}
}
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Named;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
@Named("personService") // JSR 330
public class PersonServiceImpl implements PersonService {
@Inject // JSR 330
Validator validator; // JSR 303
@PostConstruct // JSR 250
public void init() {
System.out.println("Do Init");
}
@PreDestroy // JSR 250
public void destroy() {
System.out.println("Do Init");
}
@Override
public void save(Person person) {
Set<ConstraintViolation<Person>> validate = validator.validate(person);
for (ConstraintViolation<Person> constraintViolation : validate)
System.out.println(constraintViolation.getMessage());
}
@Override
public boolean isValidTester(Person person){
Set<ConstraintViolation<Person>> validate = validator.validate(person);
return validate.isEmpty();
}
}


And here the spring context configuration.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="demo" />
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
</beans>

You could also mix the Spring annotations with the JSR 330 annotation. I think a good strategy is to use the JSR 330 annotation when every its possible and makes sense. In some cases you would use the spring specific annotations.

Which annotations do you prefer to use in a Spring application?

For more details see the spring documentation:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/

Dienstag, 25. Oktober 2011

OSGi - How to get the Bundle Context in a Java Object Instance

In most cases I use DS components, when I need the bundle context instance, the DS Framework injects me the bundle context in the activation method of my component. In most components I don’t like to have a dependency on OSGi APIs in my DS components, but thats another topic.

But sometimes I need an OSGi service or the BundleContext also in non OSGi / DS controlled class. E.g. when I like to write a JAX-WS web service class. There are many ways to get the Bundle Context into this type of Objects. One is to get the Bundle Context from the ClassLoader (which should implements the BundleReference interface). Here a short demo code snippet how to get the bundle API and also the bundle context of a class.

import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleReference;
import org.osgi.framework.ServiceReference;
import org.osgi.service.packageadmin.PackageAdmin;
public class MyDemoClass
{
public PackageAdmin getService()
{
// Howto get a bundle context
BundleContext ctx =
BundleReference.class.cast(MyDemoClass.class.getClassLoader())
.getBundle()
.getBundleContext();
// Only demo code ugly service handling
ServiceReference serviceReference = ctx.getServiceReference(PackageAdmin.class.getName());
return PackageAdmin.class.cast(ctx.getService(serviceReference));
}
}


Comment: "However, this requires the code to have the permission to access the class loader." OSGi Core Specification see section 3.8.9.

Better implementation (thanks at Holger for the hint) is by using the OSGi FrameworkUtil class. See the second code snippet:

import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
import org.osgi.service.packageadmin.PackageAdmin;
public class MyDemoClass
{
public PackageAdmin getService()
{
// get bundle instance via the OSGi Framework Util class
BundleContext ctx = FrameworkUtil.getBundle(MyDemoClass.class).getBundleContext();
ServiceReference serviceReference = ctx.getServiceReference(PackageAdmin.class.getName());
return PackageAdmin.class.cast(ctx.getService(serviceReference));
}
}


Another solution could be a holder class with a static field, which holds the actual bundle context instance. This also works when the code does not have the permission to access the class loader.

Montag, 17. Oktober 2011

OSGi RFC-0172 Declarative Services Annotations Runtime?

I had with Peter Kriens and Neil Bartlett on Twitter an interesting discussion about "Why the DS annotations in the DRAFT RFC-0172 Declarative Services Annotations should be process at runtime or compile time".

Here in this post I like to show my opinion why to process annotations at runtime.

Runtime Annotations kills DS lazyness?
Peter says at twitter "One of the best things about DS is its lazyness, we do not want to kill this".

My option is that with runtime annotations we do not kill the DS lazyness.
I think we do not need to scan the bundles classes and load them all, to find the DS components in the system. The simplest solution is to have the components with the full qualified class name in the bundle MANIFEST.MF here a sample code snippet:

Manifest-Version: 1
Bnd-LastModified: 1317237778791
Bundle-ManifestVersion: 2
Bundle-Name: org.eclipselabs.occ.marsrobot.robot
Bundle-SymbolicName: org.eclipselabs.occ.marsrobot.robot
Service-Component:
OSGI-INF/org.eclipselabs.occ.marsrobot.robot.internal.RobotComponent.xml,
org.eclipselabs.occ.marsrobot.world.WorldComponent.class
...
view raw MANIFEST.MF hosted with ❤ by GitHub


The next thing is we need a way to read the annotations without loading the class into the class loader to support bundles e.g. with "Bundle-ActivationPolicy: lazy". All information for the DS model is in the system in the byte code (when we use runtime annotations). Because of that, we can read the information for the DS components from the bytecode. Reading annotations from the bytecode is a simple way to provide all the lazyness we have with the XML model. To show this I create a very simple prototype which use the javassist library to process the annotation at runtime in a OSGi framework see https://github.com/tux2323/annotation.processing.osgi/.

Reading Annotations at Runtime is a Performance Issue?
Peter says: "So byte code scanning does not take any time?"

XML reading at runtime does also take time; do you think reading XML can be done faster than reading byte code? All information are in the byte code is reading the byte code really a performance issue? I believe we could make reading the information for the DS components from the byte code almost as fast as reading it from the XML files.

Detect errors early?
Another statement from Peter pro XML model for DS is "Detect errors early".

Yes when the annotation is process at runtime, we won’t also have a static testing tool like bnd which checks at compile time, if everything is okay with the model and shows the problems in the IDE. Why do we need the XML model for doing this?

Why runtime Annotation?
Neil asked me on Twitter "Why would you do at runtime what you can do better at build time?".

My statement is: I would like to process the annotations at runtime, because I don't like to have information in two places in my system, only when there are technical reasons, for doing this. Because of that I think it would be nice to have runtime annotations.

When we have runtime annotations then the SCR Implementation can also decide to support them at runtime or generate at build time the XML Model e.g. via bnd. The most Java frameworks (EJB3, JAXB, JAX-RS...) use runtime annotations for their components, why do OSGi like to go a different way?"

XML and Annotations
Neil asks me on twitter "Sorry I don't understand. You want the runtime to look at both the annotations *and* the XML?"

Short answer: yes.

Long answer: When we support runtime annotations to describe DS components, which should be process at runtime, we must also support the old XML way to be backward compatible. So I like to have both XML and annotations like in the Spring framework. In Spring you could describe a bean via XML and if you like you can describe the spring bean by annotations.

Thanks
Thanks at Neil and Peter for the great discussion. At this point again I would like to say when you use at the moment DS you should use the cool annotations from BND. This is at the moment the best way to develop DS components, I think.

Links

Samstag, 15. Oktober 2011

JUnit > 4.10 Rules

It's been a long time ago that I last wrote about JUnit. A number of improvements and releases have been made. There have been lot improvements around the topic JUnit rules added. Today I had little bit free time to look into this new JUnit features.

Class Rules
Now there are also class rules in JUnit. A class rule extends the idea of test method-level rules and can be used to add logic, which should be invoked for or after all test methods. A simple use-case could be, when you need a HTTP server in the test, you could have a class rule to start and stop the server. Here a simple code snippet that starts and stops a HTTP server.

import org.junit.ClassRule;
import org.junit.Test;
public class ServerTest {
@ClassRule
public static ServerRule serverRule = new ServerRule();
@Test
public void invokeServletWithRequestOne()
{
}
@Test
public void invokeServletWithRequestTwo()
{
}
}
view raw ServerTest.java hosted with ❤ by GitHub


Test Sequence
  1. Start HTTP Server
  2. Run Test : invokeServletWithRequestOne()
  3. Run Test : invokeServletWithRequestTwo()
  4. Stop HTTP Server


Composition of JUnit Rules with RuleChain Feature
In JUnit 4.10 now you can order rules via a rule chain. This is really nice to reuse rules and combine them. Here a simple RuleChain code snippet.

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
public class ServletTest {
// Starts and Stops the Jetty HTTP Server
ServerRule startServerRule = new ServerRule();
// Creates a SUT servlet instance add it
// and remove it from the Jetty Server.
ServletRule servletRule = new ServletRule(startServerRule.server);
@Rule
public TestRule chain = RuleChain
.outerRule(startServerRule)
.around(servletRule);
@Test
public void invokeServletWithRequestOne()
{
}
@Test
public void invokeServletWithRequestTwo()
{
}
}


Test Sequence
  1. Start new Jetty Server (rule = ServerRule)
  2. Create new Servlet Instance and add it to the Server (rule = ServletRule)
  3. Run Test : invokeServletWithRequestOne()
  4. Remove Servlet from Server (rule = ServletRule)
  5. Stop Jetty Server (rule = ServerRule)
  6. Start new Jetty Server (rule = ServerRule)
  7. Create new Servlet Instance and add it to the Server (rule = ServletRule)
  8. Run Test : invokeServletWithRequestTwo()
  9. Remove Servlet from Server (rule = ServletRule)
  10. Stop Jetty Server (rule = ServerRule)


Interface MethodRule is deprecated
The type MethodRule is now deprecated because the name makes no sense anymore because now we have class and method-level rules. A rule now should be of the type TestRule.

Thanks
Thanks at David Saff and Kent Beck for the work on JUnit and the cool rule features we have now in JUnit.

Links

Donnerstag, 13. Oktober 2011

OSGi Declarative Service Naming and Implementation Patterns

Here some simple OSGi declarative service (DS) naming and implementation patterns I prefer to use.

1. Naming Pattern - Component Name
A DS component name should end with Component e.g. RobotComponent.

public class RobotComponent implements Robot {}

2. Naming Pattern - Start and Stop Method
For methods, which should be called on, activate or deactivate a DS component the following names should be used:
  • start(…) and stop(…)
  • startup(…) and shutdown(…)
  • initialize(…) and deinitialize (…)
  • activate(…) and deactivate(…)

public class RobotComponent implements Robot {
      public void activate(){...}
      public void deactivate(){...}
}

3. Naming Pattern - Service Lifecycle Methods
For the service lifecycle method the following method name patterns should be uses:
  • bind${serviceName}(…) and unbind${serviceName}(…)
  • set${serviceName}(…) and unset${serviceName}(…)
  • add${serviceName}(…) and remove${serviceName}(…)
e.g. void bindRobot(Robot robot) and unbindRobot(Robot robot)


DS method name for bind more then one service instance 0..n or 1..n should become the name add* and remove*.

public class RobotComponent implements Robot {
      public void setEngine(Engine engine){...}
      public void unsetEngine(Engine engine){...}
      public void addSensor(Sensor sensor){...}
      public void removeSensor(Sensor sensor){...}
}


4. Implementation Pattern - Behavior Symmetry
When there is logic for start (activate) or set something there should always be logic for stopping or unset.

5. Implementation Pattern - Avoid Implicit Immediate Components
When a DS component not provide a Service then the component is immediate activate when all reference service are available. When the code is changed and the component know provide a service, then the component is activated when the first client component like to use the service. When a component should be activate immediate then I think avoid implicitly immediate components add always immediate=true.

6. Implementation Pattern - Use Annotations for DS Components
Use BND or Apache Felix SCR annotations to describe DS components.

Links

Mittwoch, 12. Oktober 2011

10 min - Domain Driven Design (lightning talk )

Here my slides from my lightning talk about Domain Driven Design. The slides I have not really needed in the lightning talk. Because my notebook crashed and I only could show slide number one. And because of that I only used the first slide. With the first slide I give a 10 minutes overview of domain driven design, keywords, patterns and core ideas. I think this basics ideas behind domain driven design every software developer should know.


I think the following patterns, keywords and ideas should be known by everyone how developed OO software:
  • Ubiquitous Language
  • Domain
  • Domain Layer
  • Entities
  • Value Object
  • Repository
  • Aggregate
  • Service
  • Factory (e.g. Dependency Injection, Spring, Google Guice...)
  • Assertion
  • ...
For those who could not be in my lighting talk, should have a look at the domain driven demo application. Everyone should have read the book by Eric Evans about Domain Driven Design. Okay the book is not update at all, but I think the most stuff in the book is still correct.

Links and Ressources