Showing posts with label Service. Show all posts
Showing posts with label Service. Show all posts

Thursday, 28 March 2013

Java ServiceLoader Example

Defining an API and developing the corresponding implementation has become an uber mainstream practice when developing large Java applications. Modularization is such an useful design principle, especially to avoid spaghetti code, for testing and debugging, and for re-implementation of old code.

Many developers seek to separate API interfaces and abstract classes from their implementation in separate packages. Yet, this almost always leads to cycles between java packages (api refers to impl, and vice-versa). There has been many frameworks, such as OSGi, supporting modularization, but the documentation has not always been good and complete. Many developers have struggled with class loading issues too.

Fortunately, Java has delivered the ServiceLoader utility since release 6. The example described in this post is available from Github in the Java-ServiceLoader directory. It is inspired from here.

Service & Implementation

We define a simple interface and its implementation:
package com.service.API;

public interface MyService {
    long getTime();
}


package com.service.API.Impl;

import com.service.API.MyService;

public final class MyServiceImpl implements MyService {

    public MyServiceImpl() { };

    @Override
    public long getTime() {
        return System.currentTimeMillis();
    }

}
The API and the implementation are located in different packages. Only the implementation refers to the API. The implementation must have a public parameterless constructor.

Service Loading

Next, we declare the implementation in a file having the fully qualified name of the API under the META-INF/services directory in the .jar:


The file contains fully qualified name of the implementation:

    com.service.API.Impl.MyServiceImpl

Next, we load the service using the ServiceLoader:
public class MyApp {

    public static <T> T loadService(Class<T> api) {

        T result = null;

        ServiceLoader<T> impl = ServiceLoader.load(api);

        for (T loadedImpl : impl) {
            result = loadedImpl;
            if ( result != null ) break;
        }

        if ( result == null ) throw new RuntimeException(
            "Cannot find implementation for: " + api);

        return result;

    }

    public static final MyService myService = loadService(MyService.class);

    public static void main(String[] args) {

        System.out.println("Time is: " + myService.getTime());

    }

}
The service implementation is loaded with the loadService static method. The main method prints the current time in milliseconds. It is that simple!

Monday, 11 February 2013

Securing A Service And JSP Pages

Securing A Spring Service

When a service is implemented in Spring, it can be secured with the @Secured annotation. It has a parameter where the list of roles can be defined. In order to enable this annotation, one must add the the following line in the Spring Security configuration XML file:

  <security:global-method-security secured-annotations="enabled"/>

A complete example is available here.

Securing A JSP Page

Spring defines its own set of JSP tags to control what is displayed to users. This is achieved with the Authorization tag. The Authentication tag can be used to retrieve user details data too.

Monday, 3 September 2012

Spring MVC-Service-DAO-Persistence Architecture Example

It is considered good practice to use modularity across Spring web applications. It keeps them maintainable and testable. This can be achieved by using controllers, services and data access objects (DAO). Typically, a user request is handled by a controller, which calls a service, which calls a data access object, which calls the persistence layer implementation.

Using services means that application functionalities can be tested without a test framework simulating user calls to controllers. Separating services from the persistence layer implementation via DAO, allows using an in-memory database (for example) by substituting production DAO implementations, by test DAO implementation pointing to an in-memory database.

The code example used in this post is available from Github in the Spring-MVC-Service-DAO-Persistence-Architecture directory. It is a variation of the Spring Web JPA Hibernate In-Memory example.

MVC Controller Calls The Service Implementation

The following controller is injected with an implementation of MyService. It handles /roundtrip user calls by calling its create() and Retrieve(id) methods, which creates and retrieves an instance of a MilliTimeItem object. It contains a unique ID and a timestamp in milliseconds.
@Controller
public class MyController {

    @Autowired
    private MyService myService;

    @RequestMapping(value = "/")
    public String home(Model model) {
        return "index";
    }

    @RequestMapping(value = "/roundtrip")
    public String persistenceStatus(Model model) {

        long id = myService.create();
        MilliTimeItem retr = myService.retrieve(id);
 
        model.addAttribute("RoundTrip", retr);
 
        return "roundtrip";

    }

}

Service Implementation calls Data Access Objects (DAO)

The DAO is injected in the MyService implementation. The createAndRetrieve() calls the DAO createMilliTimeItem() and getMilliTimeItem() methods. It returns the created and retrieved item.
public class MyServiceImpl implements MyService {

    @Autowired
    private MyPersistenceDAO myDAO;

    @Transactional
    long create();
 
    @Transactional
    MilliTimeItem retrieve(long id);

}

Data Access Object Implementation Calls The Persistence Layer

The DAO implementation is injected with the JPA EntityManager:
@Repository
public class MyPersistenceDAOImpl implements MyPersistenceDAO {

    @PersistenceContext
    private EntityManager em;

    @Override
    public long createMilliTimeItem() {
 
        MilliTimeItem mti = new MilliTimeItem();
        mti.setMilliTime(System.currentTimeMillis());

        em.persist(mti);
        long result = mti.getID();
        em.detach(mti);
 
        return result;
 
    }

    @Override
    public MilliTimeItem getMilliTimeItem(long id) {
        return em.find(MilliTimeItem.class, id);
    }

}

Running the Example

After compiling this example with Maven, it can be run with mvn tomcat:run. Then, browse http://localhost:8585/spring-mvc-service-dao-persistence-architecture/.

The generated output is:
Created MilliTimeItem's ID: 1
Created MilliTimeItem's value: 1346691836108

More Spring related posts here.