Showing posts with label spring. Show all posts
Showing posts with label spring. Show all posts

Tuesday, January 7, 2014

Sproogle 0.0.3 Released

Sproogle (Spring/Google Integration) 0.0.3 has now been cut and promoted and will be available for download from Maven Central under the com.mattwhipple.sproogle group.  Information on the project itself is available on GitHub: https://github.com/mwhipple/sproogle .

Note

The mention in the Spring Blog makes me realize the description should be made more specific.  Presently this project is focusing on using Google Closure Templates in Spring and further "integration" is meant to be code/library integration and not service, EIP style integration.  I'll be changing the project description to be more clear and use a less overloaded synonym.  

Notable Changes

  • There are now alternate Interfaces made available so that templates can be easily rendered to Strings rather than expecting to be used only in the Spring MVC View rendering flow
  • A jQuery plugin was created to allow quickly rendering exposed closure templates within a specified element.  Sample usage has been added in the sample project.
  • TruthyRequestParameterActiveDelegatePackageProvider can now be configured to store the result in the users session.  This could be used for purposes such as passing ?debug=true in one request which would continue to use debug delegate templates for the rest of that session or until ?debug=false is passed, or this could also be easily leveraged for purposes like A/B testing.
This will be the last planned release under 0.0.x, the next being 0.1.0 which will include the cleanup and removal of some deprecated code and therefore introducing minor backwards incompatibilities.

Update

There was an issue with the transitive dependency of the Jackson module on the main project in 0.0.3, so 0.0.4 has just been promoted and should be preferred. (I'm blaming it on jinxing myself with that last sentence).  

Saturday, December 8, 2012

Transparent REST client code for your services using Spring 3 and RESTEasy

The advantages to creating REST services has been re-iterated enough to be skipped here.  I will quickly mention my personal most practical favorite is that it allows the I/O of the service to be visible enough that the endpoints can be easily debugged in isolation using curl.  One of the big dangers is that the simplicity of creating client code can lead to issues like duplication and inconsistency as on- off code is thrown together.  Ironically the simplicity that is the strength of REST can become its weakness as the need for structure is so dramatically reduced.  Most JAX-RS implementations (I think) provide support for a client package where you can be left with the best of both worlds: a simple REST service and a means to automatically generate
structured client code.

RESTEasy is being used because the target environment is running JBoss servers.  Alternative JAX-RS implementations such as Jersey and CXF should offer similar mechanisms, though they were not researched thoroughly.

Background

Basic Objectives

This solution assumes that both a service and a client package for that service are being developed.  There is nothing to prevent the client solution from being used by itself, but it would likely not be justifiable considering the relative complexity of the produced system and the associated dependencies.

The basic goals are as follows:
  • The service should be a simple, standard REST service
  • Java client could should be able to transparently access the service
  • The API information should be DRY between systems
  • It should be easier to code than alternatives

The simple client alternative

More often than not it seems as though REST clients are created directly using HttpClient or (in Spring) using the RestTemplate.  This a very simple and straightforward approach.  Additionally...it is quite likely the most viable alternative when accessing a third party service that does not provide a specific client package.  In particular this would make sense if the service is implemented in another language (and I would probably recommend using a language that allows for faster development unless there's a reason for Java.

Possible Issues

(All of these could be avoided of course)
  • The API information (including DTOs) is likely to be duplicated in the client and the server
  • Management of the connection and serialization concerns may need to be addressed (and therefore likely to be buggy)
  • The connection may be implemented outside of a properly defined layer and interface

RESTEasy Proxy Client in Spring

RESTEasy provides a proxy client that can be used to connect to a defined service interface.  The documentation demonstrates how it can be used, but (as it is framework agnostic) does not provide integration information.  Using Spring 3 programmatic configuration allows for seamless automatic creation of a service layer which can be used to access the remote REST API.  This keeps the definition of the service consolidated between client and server and therefor eases maintenance.  Additionally it allows the client system to call the proxy and be provided with an object without concern of where it is coming from, and allowing the RESTEasy code to properly handle the details.

Implementation

The Interface

The JAX-RS information should be provided in the form of an Interface if that is not normally practiced.  The JAX-RS Interface is what drives everything, it should be packaged in a location that is accessible to both the client and the server (as should any DTOs), within the client module would work as a default.  Simple example:

@Path(ExampleResource.PATH)
public interface ExampleResource {
  public static final String PATH = "/collection/";

  @GET
  @Path("/{id}")
  @Produces(Mediatype.APPLICATION_JSON)
  Example findOne(@PathParam("id") Long id);

}

The Server

The server should provide the endpoint that implements the created Interface.  This is standard JAX-RS behavior.  It could be done directly on top of an existing service, I personally like to keep it in a controller layer to ensure that it can remain resource oriented while the services may be more message oriented.

The Client (the actual significant part)

Now the fun way to bridge the gap left in the RESTEasy docs of how to tie those client proxies in to your system.  Using Spring 3 annotations for programmatic configuration you can add the following to a re-usable client module:

@Configuration
public class RestClientConfiguration {
  @Value("${restServiceRoot}")
  private String restServiceRoot;

  public ServiceBeanConfiguration() {
    RegisterBuiltin.register(
      ResteasyProviderFactory.getInstance());
  }

  @Bean
  public ExampleResource exampleResourceClientService() {
    return ProxyFactory.create(ExampleResource.class, restServiceRoot);
  }
}

This creates a new Spring bean named "exampleResourceClientService" (the name of the method or specified as a value for @Bean) which can then just be injected as needed (ideally using the Interface) and called like Example example = exampleResourceClientService.findOne(id);.  Additionally the above assumes you have a property named restServiceRoot which points to the server (such as "http://myservice.example.com/rest").

Conclusion

Following the above you should be able to create a client jar that can be included in any project and scanned to get an easily maintained client package for very little work.  Additional services can be created by adding new methods to the configuration class, and further customizations can be easily applied.  You end up with a nice simple REST API but with the kind of client proxy that is normally associated with heavier communication technologies.

Saturday, October 6, 2012

Why Constructor Injection Should Be Used

Spring and other DI frameworks normally support 2 types of injection, setter injection and constructor injection.  Since setter injection is the more flexible it has become the far more popular approach, but making better use of constructor injection makes code clearer and more robust.

Setter Injection and JavaBeans

Setter injection will always get you where you want to be.  It also has the advantage of being in line with the standard JavaBean approach of using a default nullary constructor and then setting what is needed.  To start, in the context of more modern languages the concept of the standard JavaBeans is laughable. The idea that code like:

Person me = new Person();
me.setFirstName("Matt");
me.setMood("Laughing");

is some kind of win for convention is absurd.  It is verbose, and a visual correspondence to an underlying data structure is lost.  It is preferable to telescopic constructors with ambiguous arguments, but it doesn't seem to offer enough benefit to justify potential problems (Groovy does offer some nice sugar that addresses this, but this is about Java).

What's the problem?

Nullary constructors lead to objects that are an inconsistent state if they have have required members.  Continuing the example above, suppose every person must have a first name.  When that object is first created, it does not have a first name until that setter is called.  This is almost certainly not an issue in this code since everything is wrapped up in the same stack frame and so nothing should be able to accidentally sneak in between those 2 statements.  But it does limit the use of that class into only being operated on in thread safe contexts such as above.  The class itself is not inherently thread safe.

The other possible issue is mutability.  First names can change, but suppose this Person is being stored in some database where it has a numeric primary key.  Mucking around with that id after the object exists could be a recipe for disaster, locking the  id would make everything a lot safer.

Spring Cleaning

The simplest example for this problem in a DI container is looking at a typical Spring managed beans.  In general most layered applications with persistence will consist of a service layer which interacts with the repository layer.  The code with setter injection (with annotations, and javax.inject since I like standards) could be something like (there may be typos since I'm IDE dependent but am not using one, and I'm omitting the @Transactional annotation(s)).

@Service
public class SomeServiceImpl implements SomeService() {
  
  private SomeRepository someRepository;

  @Inject //Or on the variable itself
  public void setSomeRepository(SomeRepository someRepository) {
   this.someRepository = someRepository;
  }

  @Override
  public void updateSomeData(DataStruct struct) {
   //Do some magic
   someRepository.storeData(struct);
  }
}

The possibility of "updateSomeData" being called when the object is in an inconsistent state is more apparent in this type of class where you'd expect calls from multiple clients.  But...Spring takes care of that for you by wiring all of your beans together on start-up.  But this does become an issue when the bean is used outside of the context of Spring.  One of the pursuits of frameworks like Spring is to allow your code to remain decoupled from the underlying framework, but the code above is operating under a potentially fatal presumption.

Constructor Version

@Service
@Transactional
public class SomeServiceImpl implements SomeService() {
  
  private final SomeRepository someRepository;

  @Inject //Or on the variable itself
  public SomeServiceImpl(SomeRepository someRepository) {
    if (someRepository == null) throw new NullPointerException();
    this.someRepository = someRepository;
  }

  @Override
  public void updateSomeData(DataStruct struct) {
   //Do some magic
   someRepository.storeData(struct);
  }
}

As you can see there is no substantial difference in code length, but this class is far stronger.  Spring operates in virtually the same way, but the annotation is moved to the new constructor (the xml version does add a slight amount of extra knowledge but still less than 10 minutes to process).  Objects of this class cannot be in an inconsistent state, its dependencies are checked and locked before the object is made available (throwing the NPE in the style recommended in Effective Java by Joshua Bloch, but other approaches could work).

An additional benefit is that the code has a clearer intent.  By defining the key dependencies of a class as constructor dependencies (and as final where relevant), the class becomes more self-describing: "These are the pieces that I am useless without and will blow up if I don't have them".  This can then be augmented by setter injection for those other managed beans which are looser, less essential dependencies (such as Strategies that may be used in 1 or 2 methods, or a service which will by bypassed if not available).  

Conclusion

Constructors provide a powerful means to ensure that your objects are in a consistent state throughout their life and can help minimize needless mutability and their exposed API.  A possible downside of Spring (and other DI containers) is that the easy and consistent setter usage  can discourage the use of constructors.  Proper use of constructors in place of setters leads to more resilient and more intentional code.  

Sunday, September 23, 2012

Using Spring Form Binding When the View Resolver Doesn't Support It (Take 2)

So in an earlier post (what is now Take 1), I covered how to expose Spring form binding to pass through everything that is needed in the event that your View resolver of choice doesn't support it (more information is available in that post).  At the time I used a handler interceptor to move the logic outside of the View resolver.   This introduced the small annoyance that there was a check on each request to see whether this was the right kind of view.  Additionally as discovered later, this also presents problems elsewhere...so time to push it back into the view resolver where it belongs.

Broken Exceptions

What caught up with me using that approach was using Spring exception handling.  Adding an exception handler to a controller, for instance, can prevent you from having to worry about system errors in addition to expected error conditions.  You obviously shouldn't be doing much with Spring form binding in your exception handling, but it's nice to be able to do something like throw the user back out to the form they were using (or another form for that matter) with an appropriate message.  For instance I was working on a form that was processed locally before communicating with a remote service.  In the case of most errors I wanted to give the user a chance to try again, but I didn't want to pollute the local code with _all_ of the remote concerns.

Into the View Resolver

But where?  Like before I wanted to keep this piece decently modularized and Spring didn't provide much to help.  After fishing through the source code for a bit the best place seemed to be to intercept the call to render() on the View interface.

 public void render(Map<String, ?> model, HttpServletRequest request,
   HttpServletResponse response) throws Exception {

This can be modified using a Decorative wrapper:

public class RequestContextViewDecorator implements View {

 private final View innerView;
 private final ApplicationContext applicationContext;
 
 public RequestContextViewDecorator(View innerView, ApplicationContext applicationContext) {
  this.innerView = innerView;
  this.applicationContext = applicationContext;
 }

The first issue is getting around that pesky wildcard capture "?" in the model. This is easily done by a small method to get back a known safe type:

 private Map<String, Object> getTypedMap(Map<String, ?> model) {
  Map%lt;String, Object> typedMap = new HashMap%lt;String, Object>();
  typedMap.putAll(model);
  return typedMap;
 }

This could easily be refactored in to an abstract class and then use a Template abstract method which receives the typed map if you have other classes doing similar things or like to add extra classes to keep things focused.  This object then inherits the same behavior covered from the first post, throwing what it needs in the model and then delegating to the wrapped View:

        @Override
 public void render(Map%lt;String, ?> untypedModel, HttpServletRequest request,
   HttpServletResponse response) throws Exception {

  Map model = getTypedMap(untypedModel);
   
  if (exposeSpringMacroHelpers) {
   if (!model.containsKey(MODEL_KEY)) {
    model.put(MODEL_KEY, new RequestContext(request, response, ((WebApplicationContext) applicationContext).getServletContext(), model));
   }
  }
....
        innerView.render(model, request, response);
     }


Now just plug in to to your view resolver (in this case the Surf(again) view resolver):


public class RequestContextPageViewResolver extends PageViewResolver {
 
 @Override
 protected View loadView(String viewName, Locale locale) throws Exception {
  return new RequestContextViewDecorator(super.loadView(viewName, locale), this.getApplicationContext());
 }
}


And there you have it (after you wire in your View resolver of choice in your Spring config): a nice OOP way of integrating the request context needed for Spring form binding in a modular way to a View resolver which for some reason or another does not have the functionality in its inheritance hierarchy.

Sunday, August 12, 2012

Using Spring Form Binding When the View Resolver Doesn't Support It

Spring form binding is a convenient way to get valid data objects from a user in Spring MVC. If you need to use a View technology other than JSP, however, things may not just work, so here's some information that may fill in the gaps.

The situation

The particular situation I encountered involves using Freemarker for a template language.  Above and beyond just Freemarker I'm also using Spring Surf, so the standard solution (covered below) doesn't apply.  This post covers a direct usable solution that works in a technology agnostic way (aside from Spring) and should at least provide information for other solutions.  

Standard solution and what's going on

The standard means of setting up Freemarker (and other View technologies) for Spring form binding is to add some settings to the view resolver configuration.  Something along the lines of:

<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
   <property name="exposeSpringMacroHelpers"><value>true</value></property>
   <property name="exposeRequestAttributes"><value>true</value></property>
   <property name="exposeSessionAttributes"><value>true</value></property>
</bean>

where the first property does the needed set-up for form binding (the other two merge request and session info into the model).  Tracking this down through the source code this setting is ultimately passed from the view resolver to the AbstractTemplateView (source) which adds a RequestContext to the model (and does the request & session merging).

Re-using that behavior

Unfortunately this is normally re-used through inheritance, and in the case of Spring Surf neither the relevant view resolver nor the AbstractTemplateView class are in the used hierarchy.  It could also be argued that this functionality shouldn't really be handled by the view resolver at all since it is more of an application concern, though I'd see both sides of the possible argument having pretty even weight.  I'd certainly argue that one way or the other it should be made more modular: for speed I resorted to the cut and paste route.

A sensible place to get the Model set up as needed for the View to hook in to it would be right in between when the Controller is done doing it's work and before the View resolver does its resolving.  In Spring this can be done with the postHandle hook of a HandlerInterceptor.  For consistency I've borrowed the same properties/flags as the AbstractTemplateView.  An additional caveat due to being moved before the View resolver is that every request will be intercepted, even those that aren't relevant and possibly don't have a Model such as those handled by a MessageConverter.  An additional null check takes care of that.

A sample interceptor would then be something like (season to taste):

public class RequestContextInterceptor extends HandlerInterceptorAdapter implements ApplicationContextAware {
  private ApplicationContext applicationContext;

  private boolean exposeSpringMacroHelpers = true;
  private boolean exposeRequestAttributes = true;
  private boolean exposeSessionAttribute = true;

  public static final String MODEL_KEY = "springMacroRequestContext";

  public void setExposeSpringMacroHelpers(boolean exposeSpringMacroHelpers) {
    this.exposeSpringMacroHelpers = exposeSpringMacroHelpers;
  }
//...Other setters

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

  //When using mesage converters or other non model requests
  if (modelAndView == null) return;

  if (exposeSpringMacroHelpers) {
    if (!modelAndView.getModel().containsKey(MODEL_KEY)) {
     //Throw together a usable RequestContext...seems to require ApplicationContextAware-ness
      modelAndView.addObject(MODEL_KEY, new RequestContext(request, response,((WebApplicationContext) applicationContext).getServletContext(), modelAndView.getModel()));
    }
  }

  if (exposeRequestAttributes) {
    //...Code stolen from AbstractTemplateView
  }
  //..Session code stolen from AbstractTemplate View
}

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
  }
}

This can then be wired in to Spring:

    <mvc:interceptors>        
        <bean class="com.example.handlerinterceptors.RequestContextInterceptor">
          <property name="exposeSpringMacroHelpers" value="true"/>
          <property name="exposeRequestAttributes" value="true"/>
        </bean>
    </mvc:interceptors>

To avoid conflicts, disable the settings in the view resolver configuration.

For Freemarker there is also a form binding library that is normally automatically exposed for use.  Rather than muck around with getting that working and also because I like to be able to easily reference the source for that file, I opted to just download and use the file as a normal Freemarker import.

And there you have it: guidelines for a usable solution that is more portable than the out-of-box offering or at least some guidance that may help lead whee you need to go.