Posts

Showing posts from 2015

Tweaking HATEOAS with BOOT

Just before exploring more of HATEOAS, lets add Spring BOOT to the application. Now Spring Boot needs no introduction, beacause of its CoC (Convention of Confuguration) approach, be it Standalone or Web Based, Spring Boot is always "My Dear" as it frees us from all the headaches of dependencies, configurations, servers (in case of Web Application) etc. For more about Spring Boot, its extensive documentation is a must read. Here my intention is not to introduce Spring Boot directly but to integrate it with the existing WebApplicationInitializer, using ApplicationContextInitializer(for profiling and loading different properties based on the profile selected), using Spring-Boot-Actuator for different metrics and others. Lets start: In our previous post we have discussed on the WebApplicationInitializer for the Spring HATEOAS project i.e. SpringHateosApplicationConfig . All these things we are going to integrate it into Spring Boot StartUp class: @Impor

Spring HATEOAS

In this POST we try to focus on one of the primary priciples of REST i.e. HATEOAS - (H)ypermedia (A)s (T)he (E)ngine (O)f (A)pplication (S)tate and the way to implement HATEOAS with HAL - (H)ypertext (A)pplication (L)anguage This principle states that, the user's next course of action depends on the Hypermedia Links or the Hypertext included in the response which is dynamic and provides an uniform interface with REST architecture i.e. all the action that the user can perform is being contrained by the hyperlinks provided in the response i.e the user need not have any previous knowledge of the application. And HAL is basically a convention or a protocol for expressing Hyperlinks in either XML or JSON format. In this post we will concentrate only in JSON format. HAL with all its conventions is very interesting and systematic and the details can be explored HERE In this post I am going to describe my involvement with HATEOAS using spring and also implementing HAL

My rendezvous with Message Converters

Recently I have been exploring Spring @ResponseBody . My objective was to create a Handler Method, which will return content depending on the Accept header sent along with the request, i.e. if the request has application/json in the Accept header then the content returned will be in json format, if there is application/xml in the accept header then the content returned will be in xml format and so on. So in order to fulfill my objective, I annotated the Handler method with @ResponseBody , and using &ltmvc:annotation-driven/&gt in the Spring Configuration, automatically registers all the default HttpMessageConverters in the Application Context. So with all of my configurations in place, when I tried to invoke the Handler method (with Accept Header - application/json) , I surprisingly got error code 406 - Not Acceptable . But I could not understand the issue behind this case as all the configurations are in place, and the HttpMessageConverters are not getting kicke

Spring WS - Part 5

Spring WS provides an easy integration with various WS-Security features with the help of interceptors like Wss4jSecurityInterceptor, XwsjSecurityInterceptor. We are going to explore here very basic feature of WS-SECURITY i.e. implementing Security using with UserNameTokenAuthentication We are going to use Wss4jSecurityInterceptor as it is very easy to configure. We are going to use configure two interceptors: 1) One for the Server End. 2) Other for the Client End. For Server End The configuration for Wss4jSecurityInterceptor is as follows: @Bean public Wss4jSecurityInterceptor wss4jSecurityInterceptor() { /** * The SecurementActions for UsernameToken is commented, as the * UsernameToken is to be added by the client, the server-side * interceptor would only validate that. * */ Wss4jSecurityInterceptor wss4jSecurityInterceptor = new Wss4jSecurityInterceptor(); wss4jSecurityInterceptor.setValidationActions("UsernameToken");

Spring WS - Part 4

Another interesting and essential feature is the attachment part. Now I found two things out here. The attachment can be inline within the SOAP message body (suitable as long as the attachment size is not too long) or we can enable MTOM feature within the marshaller and leverage the MTOM-XOP feature. For the attachment to be inline with the SOAP message body, no actual configuration are required, everything is being taken care by the Spring WS framework, except the following: &ltxs:element name="getCountryRequest"&gt &ltxs:complexType&gt &ltxs:sequence&gt &ltxs:element name="name" type="xs:string"/&gt &ltxs:element name="file" type="xs:base64Binary" xmime:expectedContentTypes="application/octet-stream"&gt&lt/xs:element&gt &lt/xs:sequence&gt &lt/xs:complexType&gt &lt/xs:e

Spring WS - Part 3

Now let's go into little details of the whole App So from the Client Controller, we invoke the service with the help of WebServiceTemplate after contructing appropiate request model. The configuration for WebServiceTemplate can be found in SpringWSApplicationConfig.java . It can be seen that in the request model we are attaching a file. We have used MTOM here for the attachment purpose, which we will discuss in detail in upcoming posts. So the requuest before reaching the specified endping, which is being determined by EndpintMapping implementation passes through a series of interceptors configured in SpringWSApplicationConfig.java in addInterceptors bean. I have used here two Spring WS in-built interceptors: 1) SoapEnvelopeLoggingInterceptor.java 2) PayloadLoggingInterceptor.java They are basically logging interceptors and one Custom interceptor i.e. CountryInterceptor.java The code for Custom interceptor is already provided above. Now to use Custom inter

Spring WS - Part 2

The Service endpoint class is: @Endpoint public class CountryEndpoint { static final Logger log = LoggerFactory.getLogger(CountryEndpoint.class); private static final String NAMESPACE_URI = "http://spring.io/guides/gs-producing-web-service"; private CountryRepository countryRepository; /*@Autowired public CountryEndpoint(CountryRepository countryRepository) { this.countryRepository = countryRepository; }*/ @PayloadRoot(namespace = NAMESPACE_URI, localPart = "getCountryRequest") public void getOriginalDetails(@RequestPayload GetCountryRequest request) throws Exception { log.debug("***** Web Service Endpoint is Hit ****** "); DataHandler fileDataHandler = request.getFile(); log.debug("The DataHandler is {}",fileDataHandler); log.debug("The ContentType {}, {}-----> {}",fileDataHandler.getContentType(),fileDataHandler.getDataSource().getClass(),fileDataHandler.getAllCommands().toString()); InputSt

Spring WS - Part 1

So lets start..... My configurations files are as follows: 1) SpringWSApplicationInitializer.java 2) SpringWSApplicationConfig.java Instead of web.xml I am using WebApplicationInitializer public class SpringWSApplicationInitializer implements WebApplicationInitializer { static final Logger log = LoggerFactory.getLogger(SpringWSApplicationInitializer.class); public void onStartup(ServletContext servletContext) throws ServletException { // TODO Auto-generated method stub log.debug(" ********* Spring WS Application StartUP in Progress............ ********** "); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.register(SpringWSApplicationConfig.class); /** * Configuring MessageDispatcherServlet for Spring Web Services * */ ServletRegistration.Dynamic dispatcherWS = servletContext.addServlet("springws", new MessageDispatcherServlet(context)); dispatcherWS.setIni

Spring Web Services

Recently I was trying to explore Web Services using Spring i.e. Spring WS. So I went through the official documentation of Spring WS and after traversing it a bit I found it quite easy to configure and the concept of Contract First Web Services makes it more interesting keeping in mind all the real time situations. So I decided to prepare a demo application to get an idea about its various features and believe me starting from configuring to testing my first Spring-based web services was really cool except in some places where I got stuck like the endpoint url for invoking the Web Services as the service endpoint url for invoking the web services and the one present in the generated WSDL are not identical, so I had a little hard time in figuring the right endpoint url for invoking the service. The WSDL generated here from a xsd with the help of a Spring injected (in Configuration File SpringWSApplicationConfig.java ) bean seems to me more of a request response format fo

Use of @Configurable annotation.

Not, all types(beans) used in a Spring Based Application are Spring managed. Sometimes, we need to inject some dependency into some Types which are not Spring Managed. The most common example being, injection of Service or DAO layer within the Entity class. Now the instances of Entity classes are being created using the new operator, i.e. they are not Spring Managed. Now we want to inject the corresponding Service or DAO Type which is Spring Managed within these Entity Types, and these can be performed with the help of @Configurable . It is the Aspects, which performs all the underlying engineering and ,makes this thing possible. Let's see an example. @Configurable public class Person { @Autowired ResourceBundleThemeSource themeSource; private String firstName; private String lastName; private int age; private Address address; @CustomDateFormat Date birthDate; MultipartFile profile; public String getFirstName() { return firstName; } public voi

Spring Roo!!!!! But a Different Demeanour

When I had my first interaction with Spring Roo , I was trying to figure the features that makes it an absolute pleasure to use. After traversing through the code that it generates, I found the following interesting features and I believe that there is more to be explored of it. 1) InterType Declarations with Aspects. 2) Use of @Configurable annotation. 3) Use of JSP's in XML format i.e. (.jspx) 4) Use of Spring Theme and Localization. 5) Use of Apache Tiles 3 in Views. First, of all I will start with @Configurable annotation. I am going to discuss my experience with each of the above mentioned features separately. I have tried to use them separately in a Spring based Application.

Explore Spring 4 Features: WebSocket (Part II)

Now for the phase II to be in action, a asynchronous task needs to be scheduled, which at regular intervals, with the help of a Scheduler would post messages to MessageBroker.When the client would connect to the MessageBroker over WebSocket, it would start receiving the messages. Now, here we cannot use Spring Scheduling features i.e. @EnableScheduling or @EnableAsync , as when we use @EnableWebSocketMessageBroker , then Spring automatically configures two schedulers by default,and Spring 4 does not allow more than two Schedulers at a time. To overcome this limitation, we are using an implementation of SchedulingConfigurer. In its implementation, we are injecting a service. We will be calling a method of the service at regular interval, which will send messages to the MessageBroker. The code for SchedulingConfigurer implementation is: @Configuration @EnableScheduling public class SpringWebSchedulingConfig implements SchedulingConfigurer { @Autowired IMessageServi

Explore Spring 4 Features: WebSocket (Part I)

First of all Wish you a Very Happy New Year WebSocket with Spring 4 One of the interesting features of Spring 4 is introduction of WebSockets in Spring. Now the first Question which arises is what is WebSocket? Definition: WebSocket is a protocol which allows for communication between the client and the server/endpoint using a single TCP connection. This protocol is an important new capability for web applications: full-duplex, two-way communication between client and server. It aims at making web more interactive including Java applets, XMLHttpRequest. An abstract of the actual process which happens behind the scene for WebSocket is: During initialization of this protocol,HTTP is used only for the initial handshake, which relies on a mechanism built into HTTP to request a protocol upgrade (or in this case a protocol switch) to which the server can respond with HTTP status 101 (switching protocols) if it agrees. Assuming the handshake succeeds the TCP socket unde