Featured FREE Whitepapers

What's New Here?

spring-logo

Bootstrap a Web Application with Spring 3

1. Overview This is the first of a series of tutorials about setting up a RESTfull web application using Spring 3.1 with Java based configuration. The article will focus on bootstrapping the web application, discussing how to make the jump from XML to Java without having to completely migrate the entire XML configuration. 2. The Maven pom.xml     <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org</groupId> <artifactId>rest</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging><dependencies><dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> <exclusions> <exclusion> <artifactId>commons-logging</artifactId> <groupId>commons-logging</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>${cglib.version}</version> <scope>runtime</scope> </dependency></dependencies><build> <finalName>rest</finalName><plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.6</source> <target>1.6</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build><properties> <spring.version>3.2.2.RELEASE</spring.version> <cglib.version>2.2.2</cglib.version> </properties></project> 2.1. Justification of the cglib dependency You may wonder why cglib is a dependency – it turns out there is a valid reason to include it – the entire configuration cannot function without it. If removed, Spring will throw: Caused by: java.lang.IllegalStateException: CGLIB is required to process @Configuration classes. Either add CGLIB to the classpath or remove the following @Configuration bean definitions The reason this happens is explained by the way Spring deals with @Configuration classes. These classes are effectively beans, and because of this they need to be aware of the Context, and respect scope and other bean semantics. This is achieved by dynamically creating a cglib proxy with this awareness for each @Configuration class, hence the cglib dependency. Also, because of this, there are a few restrictions for Configuration annotated classes:Configuration classes should not be final They should have a constructor with no arguments2.2. The cglib dependency in Spring 3.2Starting with Spring 3.2, it is no longer necessary to add cglib as an explicit dependency. This is because Spring is in now inlining cglib – which will ensure that all class based proxying functionality will work out of the box with Spring 3.2. The new cglib code is placed under the Spring package: org.springframework.cglib (replacing the original net.sf.cglib). The reason for the package change is to avoid conflicts with any cglib versions already existing on the classpath. Also, the new cglib 3.0 is now used, upgraded from the older 2.2 dependency (see this JIRA issue for more details). 3. The Java based web configuration @Configuration @ImportResource( { "classpath*:/rest_config.xml" } ) @ComponentScan( basePackages = "org.rest" ) @PropertySource({ "classpath:rest.properties", "classpath:web.properties" }) public class AppConfig{@Bean    public static PropertySourcesPlaceholderConfigurer properties() {    return new PropertySourcesPlaceholderConfigurer();    } } First, the @Configuration annotation – this is the main artifact used by the Java based Spring configuration; it is itself meta-annotated with @Component, which makes the annotated classes standard beans and as such, also candidates for component scanning. The main purpose of @Configuration classes is to be sources of bean definitions for the Spring IoC Container. For a more detailed description, see the official docs. Then, @ImportResource is used to import the existing XML based Spring configuration. This may be configuration which is still being migrated from XML to Java, or simply legacy configuration that you wish to keep. Either way, importing it into the Container is essential for a successful migration, allowing small steps without to much risk. The equivalent XML annotation that is replaced is: <import resource=”classpath*:/rest_config.xml” /> Moving on to @ComponentScan – this configures the component scanning directive, effectively replacing the XML: <context:component-scan base-package="org.rest" /> As of Spring 3.1, the @Configuration are excluded from classpath scanning by default – see this JIRA issue. Before Spring 3.1 though, these classes should have been excluded explicitly: excludeFilters = { @ComponentScan.Filter( Configuration.class ) } The @Configuration classes should not be autodiscovered because they are already specified and used by the Container – allowing them to be rediscovered and introduced into the Spring context will result in the following error: Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name ‘webConfig’ for bean class [org.rest.spring.AppConfig] conflicts with existing, non-compatible bean definition of same name and class [org.rest.spring.AppConfig] And finally, using the @Bean annotation to configure the properties support - PropertySourcesPlaceholderConfigurer is initialized in a @Bean annotated method, indicating it will produce a Spring bean managed by the Container. This new configuration has replaced the following XML: <context:property-placeholder location="classpath:persistence.properties, classpath:web.properties" ignore-unresolvable="true"/> For a more in detph discussion on why it was necessary to manually register the PropertySourcesPlaceholderConfigurer bean, see the Properties with Spring Tutorial. 3.1. The web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns=" http://java.sun.com/xml/ns/javaee"      xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"     id="rest" version="3.0"><context-param> <param-name>contextClass</param-name> <param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext </param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value>org.rest.spring.root</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener><servlet> <servlet-name>rest</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextClass</param-name> <param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext </param-value> </init-param> <init-param> <param-name>contextConfigLocation</param-name> <param-value>org.rest.spring.rest</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>rest</servlet-name> <url-pattern>/api/*</url-pattern> </servlet-mapping><welcome-file-list> <welcome-file /> </welcome-file-list></web-app> First, the root context is defined and configured to use AnnotationConfigWebApplicationContext instead of the default XmlWebApplicationContext. The newer AnnotationConfigWebApplicationContext accepts @Configuration annotated classes as input for the Container configuration and is needed in order to set up the Java based context. Unlike XmlWebApplicationContext, it assumes no default configuration class locations, so the “contextConfigLocation” init-param for the Servlet must be set. This will point to the java package where the @Configuration classes are located; the fully qualified name(s) of the classes are also supported. Next, the DispatcherServlet is configured to use the same kind of context, with the only difference that it’s loading configuration classes out of a different package. Other than this, the web.xml doesn’t really change from a XML to a Java based configuration. 4. Conclusion The presented approach allows for a smooth migration of the Spring configuration from XML to Java, mixing the old and the new. This is important for older projects, which may have a lot of XML based configuration that cannot be migrated all at once. This way, the web.xml and bootstrapping of the application is the first step in a migration, after which the remaining XML beans can be ported in small increments. In the next article on REST with Spring, I cover setting up MVC in the project, configuration of the HTTP status codes, payload marshalling and content negotiation. In the meantime, you can check out the github project.   Reference: Bootstrap a Web Application with Spring 3 from our JCG partner Eugen Paraschiv at the baeldung blog. ...
spring-security-logo

Securing a RESTful Web Service with Spring Security 3.1, part 3

1. Overview This tutorial shows how to Secure a REST Service using Spring and Spring Security 3.1 with Java based configuration. The article will focus on how to set up the Security Configuration specifically for the REST API using a Login and Cookie approach. 2. Spring Security in the web.xml The architecture of Spring Security is based entirely on Servlet Filters and, as such, comes before Spring MVC in regards to the processing of HTTP requests. Keeping this in mind, to begin with, a filter needs to be declared in the web.xml of the application: <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> The filter must necessarily be named ‘springSecurityFilterChain’  to match the default bean created by Spring Security in the container. Note that the defined filter is not the actual class implementing the security logic but a DelegatingFilterProxy with the purpose of delegating the Filter’s methods to an internal bean. This is done so that the target bean can still benefit from the Spring context lifecycle and flexibility. The URL pattern used to configure the Filter is /* even though the entire web service is mapped to /api/* so that the security configuration has the option to secure other possible mappings as well, if required. 3. The Security Configuration <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:sec="http://www.springframework.org/schema/security" xsi:schemaLocation="http://www.springframework.org/schema/securityhttp://www.springframework.org/schema/security/spring-security-3.1.xsdhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsd"><http entry-point-ref="restAuthenticationEntryPoint"> <intercept-url pattern="/api/admin/**" access="ROLE_ADMIN"/><form-login authentication-success-handler-ref="mySuccessHandler" /><logout /> </http><beans:bean id="mySuccessHandler" class="org.rest.security.MySavedRequestAwareAuthenticationSuccessHandler"/><authentication-manager alias="authenticationManager"> <authentication-provider> <user-service> <user name="temporary" password="temporary" authorities="ROLE_ADMIN"/> <user name="user" password="user" authorities="ROLE_USER"/> </user-service> </authentication-provider> </authentication-manager></beans:beans> Most of the configuration is done using the security namespace – for this to be enabled, the schema locations must be defined and pointed to the correct 3.1 XSD versions. The namespace is designed so that it expresses the common uses of Spring Security while still providing hooks raw beans to accommodate more advanced scenarios. 3.1. The <http> element The <http> element is the main container element for HTTP security configuration. In the current implementation, it only secured a single mapping: /api/admin/**. Note that the mapping is relative to the root context of the web application, not to the rest Servlet; this is because the entire security configuration lives in the root Spring context and not in the child context of the Servlet. 3.2. The Entry Point In a standard web application, the authentication process may be automatically triggered when the client tries to access a secured resource without being authenticated – this is usually done by redirecting to a login page so that the user can enter credentials. However, for a REST Web Service this behavior doesn’t make much sense – Authentication should only be done by a request to the correct URI and all other requests should simply fail with a 401 UNAUTHORIZED status code if the user is not authenticated. Spring Security handles this automatic triggering of the authentication process with the concept of an Entry Point – this is a required part of the configuration, and can be injected via the entry-point-ref attribute of the <http> element. Keeping in mind that this functionality doesn’t make sense in the context of the REST Service, the new custom entry point is defined to simply return 401 whenever it is triggered: @Component( "restAuthenticationEntryPoint" ) public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{@Override public void commence( HttpServletRequest request, HttpServletResponse response, AuthenticationException authException ) throws IOException{ response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized" ); } } 3.3. The Login Form for REST There are multiple ways to do Authentication for a REST API – one of the default Spring Security provides is Form Login – which uses an authentication processing filter – org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter. The <form-login> element will create this filter and will also allow us to set our custom authentication success handler on it. This can also be done manually by using the <custom-filter> element to register a filter at the position FORM_LOGIN_FILTER – but the namespace support is flexible enough. Note that for a standard web application, the auto-config attribute of the <http> element is shorthand syntax for some useful security configuration. While this may be appropriate for some very simple configurations, it doesn’t fit and should not be used for a REST API. 3.4. Authentication should return 200 instead of 301 By default, form login will answer a successful authentication request with a 301 MOVED PERMANENTLY status code; this makes sense in the context of an actual login form which needs to redirect after login. For a RESTful web service however, the desired response for a successful authentication should be 200 OK. This is done by injecting a custom authentication success handler in the form login filter, to replace the default one. The new handler implements the exact same login as the default org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler with one notable difference – the redirect logic is removed: public class MySavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {private RequestCache requestCache = new HttpSessionRequestCache();@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { SavedRequest savedRequest = requestCache.getRequest(request, response);if (savedRequest == null) { clearAuthenticationAttributes(request); return; } String targetUrlParam = getTargetUrlParameter(); if (isAlwaysUseDefaultTargetUrl() || (targetUrlParam != null && StringUtils.hasText(request.getParameter(targetUrlParam)))) { requestCache.removeRequest(request, response); clearAuthenticationAttributes(request); return; }clearAuthenticationAttributes(request); }public void setRequestCache(RequestCache requestCache) { this.requestCache = requestCache; } } 3.5. The Authentication Manager and Provider The authentication process uses an in-memory provider to perform authentication – this is meant to simplify the configuration as a production implementation of these artifacts is outside the scope of this post. 3.6 Finally – Authentication against the running REST Service Now let’s see how we can authenticate against the REST API – the URL for login is /j_spring_security_check – and a simple curl command performing login would be: curl -i -X POST -d j_username=user -d j_password=userPasshttp://localhost:8080/spring-security-rest/j_spring_security_check This request will return the Cookie which will then be used by any subsequent request against the REST Service. We can use curl to authentication and store the cookie it receives in a file: curl -i -X POST -d j_username=user -d j_password=userPass -c /opt/cookies.txthttp://localhost:8080/spring-security-rest/j_spring_security_check Then we can use the cookie from the file to do further authenticated requests: curl -i --header "Accept:application/json" -X GET -b /opt/cookies.txthttp://localhost:8080/spring-security-rest/api/foos This authenticated request will correctly result in a 200 OK: HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Content-Type: application/json;charset=UTF-8 Transfer-Encoding: chunked Date: Wed, 24 Jul 2013 20:31:13 GMT[{"id":0,"name":"JbidXc"}] 4. Maven and other trouble The Spring core dependencies necessary for a web application and for the REST Service have been discussed in detail. For security, we’ll need to add: spring-security-web and spring-security-config – all of these have also been covered in the Maven for Spring Security tutorial. It’s worth paying close attention to the way Maven will resolve the older Spring dependencies – the resolution strategy will start causing problems once the security artifacts are added to the pom. To address this problem, some of the core dependencies will need to be overridden in order to keep them at the right version. 5. Conclusion This post covered the basic security configuration and implementation for a RESTful Service using Spring Security 3.1, discussing the web.xml, the security configuration, the HTTP status codes for the authentication process and the Maven resolution of the security artifacts. The implementation of this Spring Security REST Tutorial can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is.   Reference: Spring REST Service Security 3 from our JCG partner Eugen Paraschiv at the baeldung blog. ...
spring-logo

Building a RESTful Web Service with Spring 3.1 and Java based Configuration, part 2

1. Overview This article shows how to set up a REST in Spring – the Controller and HTTP response codes, configuration of payload marshalling and content negotiation. 2. Understanding REST in Spring The Spring framework supports 2 ways of creating RESTful services:using MVC with ModelAndView using HTTP message convertersThe ModelAndView approach is older and much better documented, but also more verbose and configuration heavy. It tries to shoehorn the REST paradigm into the old model, which is not without problems. The Spring team understood this and provided first-class REST support starting with Spring 3.0. The new approach, based on HttpMessageConverter and annotations, is much more lightweight and easy to implement. Configuration is minimal and it provides sensible defaults for what you would expect from a RESTful service. It is however newer and a a bit on the light side concerning documentation; what’s more, the reference doesn’t go out of it’s way to make the distinction and the tradeoffs between the two approaches as clear as they should be. Nevertheless, this is the way RESTful services should be build after Spring 3.0. 3. The Java configuration @Configuration @EnableWebMvc public class WebConfig{ // } The new @EnableWebMvc annotation does a number of useful things – specifically, in the case of REST, it detect the existence of Jackson and JAXB 2 on the classpath and automatically creates and registers default JSON and XML converters. The functionality of the annotation is equivalent to the XML version: <mvc:annotation-driven /> This is a shortcut, and though it may be useful in many situations, it’s not perfect. When more complex configuration is needed, remove the annotation and extend WebMvcConfigurationSupport directly. 4. Testing the Spring context Starting with Spring 3.1, we get first-class testing support for @Configuration classes: @RunWith( SpringJUnit4ClassRunner.class ) @ContextConfiguration( classes = { ApplicationConfig.class, PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class ) public class SpringTest{@Test public void whenSpringContextIsInstantiated_thenNoExceptions(){ // When } } The Java configuration classes are simply specified with the @ContextConfiguration annotation and the new AnnotationConfigContextLoader loads the bean definitions from the @Configuration classes. Notice that the WebConfig configuration class was not included in the test because it needs to run in a Servlet context, which is not provided. 5. The Controller The @Controller is the central artifact in the entire Web Tier of the RESTful API. For the purpose of this post, the controller is modeling a simple REST resource – Foo: @Controller @RequestMapping( value = "foo" ) class FooController{@Autowired IFooService service;@RequestMapping( method = RequestMethod.GET ) @ResponseBody public List< Foo > getAll(){ return service.getAll(); }@RequestMapping( value = "/{id}", method = RequestMethod.GET ) @ResponseBody public Foo get( @PathVariable( "id" ) Long id ){ return RestPreconditions.checkNotNull( service.getById( id ) ); }@RequestMapping( method = RequestMethod.POST ) @ResponseStatus( HttpStatus.CREATED ) @ResponseBody public Long create( @RequestBody Foo entity ){ RestPreconditions.checkNotNullFromRequest( entity ); return service.create( entity ); }@RequestMapping( method = RequestMethod.PUT ) @ResponseStatus( HttpStatus.OK ) public void update( @RequestBody Foo entity ){ RestPreconditions.checkNotNullFromRequest( entity ); RestPreconditions.checkNotNull( service.getById( entity.getId() ) ); service.update( entity ); }@RequestMapping( value = "/{id}", method = RequestMethod.DELETE ) @ResponseStatus( HttpStatus.OK ) public void delete( @PathVariable( "id" ) Long id ){ service.deleteById( id ); }} The Controller implementation is non-public – this is because there is no need for it to be. Usually the controller is the last in the chain of dependencies – it receives HTTP requests from the Spring front controller (the DispathcerServlet) and simply delegate them forward to a service layer. If there is no use case where the controller has to be injected or manipulated through a direct reference, then I prefer not to declare it as public. The request mappings are straightforward – as with any controller, the actual value of the mapping as well as the HTTP method are used to determine the target method for the request. @RequestBody will bind the parameters of the method to the body of the HTTP request, whereas @ResponseBody does the same for the response and return type. They also ensure that the resource will be marshalled and unmarshalled using the correct HTTP converter. Content negotiation will take place to choose which one of the active converters will be used, based mostly on the Accept header, although other HTTP headers may be used to determine the representation as well. 6. Mapping the HTTP response codes The status codes of the HTTP response are one of the most important parts of the REST service, and the subject can quickly become very complex. Getting these right can be what makes or breaks the service. 6.1. Unmapped requests If Spring MVC receives a request which doesn’t have a mapping, it considers the request not to be allowed and returns a 405 METHOD NOT ALLOWED back to the client. It is also good practice to include the Allow HTTP header when returning a 405 to the client, in order to specify which operations are allowed. This is the standard behavior of Spring MVC and does not require any additional configuration. 6.2. Valid, mapped requests For any request that does have a mapping, Spring MVC considers the request valid and responds with 200 OK if no other status code is specified otherwise. It is because of this that controller declares different @ResponseStatus for the create, update and delete actions but not for get, which should indeed return the default 200 OK. 6.3. Client error In case of a client error, custom exceptions are defined and mapped to the appropriate error codes. Simply throwing these exceptions from any of the layers of the web tier will ensure Spring maps the corresponding status code on the HTTP response. @ResponseStatus( value = HttpStatus.BAD_REQUEST ) public class BadRequestException extends RuntimeException{ // } @ResponseStatus( value = HttpStatus.NOT_FOUND ) public class ResourceNotFoundException extends RuntimeException{ // } These exceptions are part of the REST API and, as such, should only be used in the appropriate layers corresponding to REST; if for instance a DAO/DAL layer exist, it should not use the exceptions directly. Note also that these are not checked exceptions but runtime exceptions – in line with Spring practices and idioms. 6.4. Using @ExceptionHandler Another option to map custom exceptions on specific status codes is to use the @ExceptionHandler annotation in the controller. The problem with that approach is that the annotation only applies to the controller in which it is defined, not to the entire Spring Container, which means that it needs to be declared in each controller individually. This quickly becomes cumbersome, especially in more complex applications which many controllers. There are a few JIRA issues opened with Spring at this time to handle this and other related limitations: SPR-8124, SPR-7278, SPR-8406. 7. Additional Maven dependencies In addition to the spring-webmvc dependency required for the standard web application, we’ll need to set up content marshalling and unmarshalling for the REST API: <dependencies> <dependency>    <groupId>com.fasterxml.jackson.core</groupId>    <artifactId>jackson-databind</artifactId>    <version>${jackson.version}</version> </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>${jaxb-api.version}</version> <scope>runtime</scope> </dependency> </dependencies><properties> <jackson.version>2.2.2</jackson.version> <jaxb-api.version>2.2.9</jaxb-api.version> </properties> These are the libraries used to convert the representation of the REST resource to either JSON or XML. 8. Conclusion This post covered the configuration and implementation of a RESTful service using Spring 3.1 and Java based configuration, discussing HTTP response codes, basic content negotiation and marshaling. In the next articles of the series I will focus on Discoverability of the API, advanced content negotiation and working with additional representations of a resource. In the meantime, check out the github project.   Reference: Build a REST API with Spring 3 and Java Config from our JCG partner Eugen Paraschiv at the baeldung blog. ...
jcg-logo

Best Of The Week – 2011 – W46

Hello guys, Time for the “Best Of The Week” links for the week that just passed. Here are some links that drew JavaCodeGeeks attention: * Java is not the new COBOL: This article explains why Java should NOT be considered the new COBOL. Some of the reasons given:  Java7 addressing verbosity and Java8 pushing new paradigms (e.g. Functional Programming). Also check out Hate Java? You’re fighting the wrong battle. * Great developers should always be on the market: Here the author argues that great developers should be on the market (even this sounds unlikely)  because of one very specific and important trait of their personality: ambition! * List of Known Scalable Architecture Templates: This article briefly presents some of the most common scalability architectures providing the  corresponding references. Examples include LB (Load Balancing), Distributed Queues,  and Map/Reduce. In general, there are 3 way to scale: distribution, caching, and asynchronous processing. * You’re a developer, so why do you work for someone else?: An article suggesting that developers can and should pursuit the idea of building a product and going solo. It bustes some myths like lack of time, lack of ideas, lack of capital etc. * Testing and Mocking of Static Methods in Java: This tutorial shows how to write unit tests for units with static methods, whether the static unit  has dependencies or not. Additionally, with the PowerMock framework, it is shown how to write tests  that mock static methods. * Mobicents Media Server passes 100% JSR 309 Compliance: Mobicents Media Server gets to be the first Open Source (LGPL) 100% JSR 309 compliant implementation.  JSR 309 is the standard Java API that allows control of media server resources. It makes it possible to implement  in a standard and portable way, rich media applications (e.g. Conference Calling, Interactive Voice Response,  DTMF detection, Text To Speech, Video Playback etc.). * AMQP and the future of web messaging: This article discusses the latest advancements in AMQP, an open standard application layer protocol for  message-oriented middleware, more specifically the finalization of its specification. AMQP can contribute  to the Async/Reliable part of the web. Also check out Spring 3 HornetQ 2.1 Integration Tutorial for a JMS  approach on messaging. * What Facebook Can Teach Us About Making Software: A nice overview of the methodologies used by Facebook regarding they way they build their software. Highlights include:  engineers owing the specifications instead of PMs, automated testing and mandatory code reviews, staged rollout process etc. * Enabling and Sustaining High Performing Teams: In this article, some pointers on how to create, enable and sustain high performing teams are provided. Among them are:  recruiting the right players for the team, create an intrinsically motivating development culture and managing the team with  lean software techniques. * How Mature Is Your Continuous Integration?:In this article, the various level of CI maturity are presented, ranging from no CI at all to a state where the tools, the process and the right culture are all in place. According to the author, the hardest part to get right,  particularly in companies over a certain size, is the culture. Also check The Ten Minute Build. * 3 Mobile App Development Problems and Ways to Solve Them: In this presentation, 3 mobile application development problems are discussed: failing network connection,  multiple UIs, and bugs, while some strategies for solving them are presented. * Revisiting Google App Engine’s pricing changes: A real-life case where the author managed to cut down his App Engine application’s costs to zero. The result was a mixture of platform configuration (e.g. instance allocation, data storage), application configuration (e.g. use of Memcached), algorithm changes (e.g. use of asynchronous operations) and running Appstats on all application interfaces. * Premature Ramp-Up: Martin Fowler talks about adding people to a software team and more specifically about the rate at which  more people can be added to a team without disrupting their function. As one might expect, you don’t get  a linear benefit, mainly because of the communication and coordination costs that occur. * You only control 1/3 of your Page Load Performance!: In this article, the author argues that in most cases only control 1/3 of the time required to load a page is controlled by the  site owner, since the rest of the time is consumed by 3rd party content that are not under one’s control. So, using third party  content is often a tradeoff that has to be assessed. That’s all for this week. Stay tuned for more, here at Java Code Geeks. Cheers, Ilias Related Articles:Best Of The Week – 2011 – W45 Best Of The Week – 2011 – W44 Best Of The Week – 2011 – W43 Best Of The Week – 2011 – W42 Best Of The Week – 2011 – W41 Best Of The Week – 2011 – W40 Best Of The Week – 2011 – W39 Best Of The Week – 2011 – W38 Best Of The Week – 2011 – W37 Best Of The Week – 2011 – W36...
jetbrains-intellijidea-logo

What’s Cool In IntelliJIDEA. Part III: External Tools

Although there is almost any kind of functionality available in IntelliJIDEA, either as a base functionality or via plugins, there’s still a fraction of probability involved that you might want to do something that goes beyond the power of the IDE. For such rare cases you might want to take a look at External Tools in IntelliJ. Just recently I’ve encountered such a case myself – I wanted to use an utility from JDK, but in a more flexible way than just switching to command line and navigating to the correct location. My idea was that I should just press an arbitrary shortcut and get the result. So I decided to give External Tools a try. The utility I use a lot when studying Java is javap – the java class file disassembler. This is due I study the bytecode sometimes. And although there’s ASM plugin available for IntelliJ that basically can provide me the result I needed, I still prefer to read the raw javap output. To setup javap in Intellij as an External Tool go to Settings >> External Tools and press Add… . You can then define the location of the tool, the working directory, and the parameters.The nice part of it is that IntelliJ provides some basic macros in order to dynamically resolve the parameters for the tool. So for javap it was enough to set $FileClass$ for the parameter, and $OutputPath$ as the working directory. And that’s it – the tool is now ready for use.You can also define a “group” which is then used to group the external tools in the popup menu. I use “jdk” as a group name for javap so here’s what it looks after:So that’s cool but you might have noticed that it is not that comfortable to use – have to right-click the file, navigate to “jdk” group, expand it, and only then can execute javap. Well, shortcuts to the rescue! Browse to Settings >> Keymap, and there you can define any sortcut for the tool. The nice part of it is that IntelliJ detects if you select a conflicting shortcut and notifies you.One more tweak left to do. Once I press the shortcut that I’ve assigned to javap, the result of decompilation is printed out to the IDE console, which is just below the source code. But it would be more convenient to see it side by side. For that, it is possible to drag-and-drop the Run window to the side panel in IntelliJ so the result can be observed right next to the source I’m currently working with.The only thing that is probably missing is the syntax highlight for the javap output, but that is probably too much to wish. Reference: What’s Cool In IntelliJIDEA. Part III: External Tools from our JCG partner Anton Arhipov at the Code Impossible blog. Related Articles :What’s Cool In IntelliJIDEA Part I What’s Cool In IntelliJIDEA. Part II: Live Templates Eclipse 3.6 vs IntelliJ IDEA 10.5: Pros and Cons Eclipse Shortcuts for Increased Productivity Eclipse Memory Analyzer (MAT) What to do with IDE project files Eclipse: How attach Java source Java Tutorials and Android Tutorials list...
jetbrains-intellijidea-logo

What’s Cool In IntelliJIDEA. Part II: Live Templates

In IntelliJ, I use Live Templates quite heavily and still think that these are underused. It is not only the standard number of templates that can make your life easier while typing yet another piece of code, but it is also the ability to define new templates with all the bells and whistles that are available in IntelliJ standard template list. In the previous post I’ve covered the basics of Live Templates but I think that it would be cool to cover these in more details and to point out some less-known aspects of this functionality. First of all, Ctrl+J is the shortcut to use in order to get a list of the available by default. But if you had time to practice, most likely you can remember the abbreviations by heart, like psvm, iter, psfs, soutv, etc.One thing I do for sure before using Live Templates is that I change the default expansion key, which is Tab by default, to a Space key. It seems to me that it is more natural to use Space for this purpose as when you type you actually hit the Space key almost automatically.Another cool feature of Live Templates is to surround a capable statement with a block of code – also covered in the previous post.How do I define my own template? IntelliJ provides a number of templates in its default distribution but obviously it doesn’t cover all cases you might need. So here’s the main purpose of this post – how to define a custom live template in IntelliJ. First, let’s make up a use case – a situation where we’d like to have some means for typing faster but which isn’t defined in the IDE by default. For some reason, IntelliJ doesn’t provide try-catch template by default. It only suggests this option if you’d like to surround an existing statement with the try-catch block, but not when you just want to create an empty one. Here’s what we can do: open Settings window (Ctrl+Alt+S) and start typing ‘Live Templates’ – this will lead you to the templates’ settings – and hit the “Add..” button on the right. It is quite easy to create a simple template which just has to generate a defined text for the given keyword. For the empty try-catch block we just need to fill in the abbreviation and the code itself, and not to forget to bind it to Java context using the corresponding checkbox.This is quite a dumb template, nothing intelligent here. But what if we’d like to suggest the exception type in the catch block? What if we’d like to position the cursor in some particular place after the template is applied? Let’s make our brand new template a little smarter. To ask IntelliJ for a type of the throwable in the catch block we can add a variable ($EXCEPTION$) and define its value using a special function provided by IntelliJ. Say, I’d like the type to be a subtype of java.lang.Exception class, hence I’m using the subtype(<type>) function:You’ve probably noticed that I’ve used another variable, $END$, but there’s no value defined in the dialog window. This is a predefined variable, meaning where should the cursor be positioned after the last choice made within the templates. So now once I type ‘try’ and hit the space key, the template is expanded to the following:First the cursor will be positioned inside the catch block in order to choose the type of the exception to be handled. Right after I make my mind about the type and hit the Enter key, the cursor will be positioned back into the try block. We can go further and add an option to choose the method call on the exception instance by emulating the Ctrl+Space behavior using a special function again. This is a fictional example but let’s assume we want that :) For the purpose, I’ve defined a $METHOD$ variable which is assigned a complete() function in the template editor:Now, once the type of the exception is selected, the next thing to happen is the automatic auto-completion action on the instance of the exception within the catch block – the list of available methods will popup:There’s actually a fair number of functions that could be used in Live Templates for the variable assignment. The nice part is that these work not only for Java but also other languages – when writing JavaScript, HTML or Groovy code, for instance. Surround with template The other type of live templates available in IntelliJ is the surrounding templates. It means you can select a text block (or just position the cursor to a desired location) and hit the Ctrl+Alt+T shortcut – a popup with the templates list will be suggested. Defining a custom surround template isn’t any different from the normal templates besides that the selected block of code (or text) is assigned to a predefined $SELECTION$ variable. Also, if a template contains this variable it will not appear in the list of normal templates provided via Ctrl+J. Let’s make an example for defining a custon surrounding template. Assume we’d like to quote a selected text. This is a very simple template – just need to add the quotes around the $SELECTION$ variable in the template editor:Now if I select a text and hit Ctrl+Alt+T shortcut and then “Q” key the selected text will be put into quotes:Resume If you use IntelliJ, Live Templates should be your bread and butter for tying the code faster. There’s plenty of the standard templates defined in IntelliJ, but don’t be limited only to the standard template list – define your own templates according to your code specifics – you will not regret that! Reference: What’s Cool In IntelliJIDEA. Part II: Live Templates from our JCG partner Anton Arhipov at the Code Impossible blog. Related Articles :What’s Cool In IntelliJIDEA Part I What’s Cool In IntelliJIDEA. Part III: External Tools Eclipse 3.6 vs IntelliJ IDEA 10.5: Pros and Cons Eclipse Shortcuts for Increased Productivity Eclipse Memory Analyzer (MAT) What to do with IDE project files Eclipse: How attach Java source Java Tutorials and Android Tutorials list...
jetbrains-intellijidea-logo

What’s Cool In IntelliJIDEA Part I

Eclipse or IntelliJ? NetBeans or Eclipse? IntelliJ or NetBeans? The dispute about the IDEs is the most popular among the software developers and hardly will ever end. I consider myself being a big IntelliJ fan, but I do realize that there are a lot of things that IntelliJ could do better and that NetBeans and Eclipse are better in some ways. In this post I’d like to make an overview of IntelliJ’s features which I like the most, and and beyond that. Also I’d like point out some of the aspects in which IntelliJ could do better. One of my friends said once: I don’t like IDEs. They help to write verbose code. In real life 90% of time I spend on code reading. Verbose code kills my productivity I think he’s wrong. The reality is that IDEs are used not only for writing/generating code, but to a greater extent IDEs are used to read and analyze the code. You might be a hard-core Emacs/Vim ninja but still, there are things that you just cannot do with the text editors. Navigation Navigation through the source code is one of the activities that programmer executes on a regular basis. Basically, it is not hard to navigate the code with Emacs or Vim, but it would limit you only to a basic navigation options. IDEs take navigation abilities one step further. Let’s see what are the navigation features in IntelliJ. First of all, “Open Type” which is executed via Ctrl+N:The same can be achieved with Ctrl+Shift+T in Eclipse and the behavior is exactly the same. Ctrl+Shift+N will help you to open any resource. Eclipse does the same with Ctrl+Shift+R. And it could have been all but there’s more – Ctrl+Shift+Alt+N will find you all the appearances of a specific symbol, e.g. a method name:It doesn’t mean IntelliJ will scan the code for the occurrence of the specific symbols but it rather will match the code structure and look for the elements in your code so you will get a list of method declarations but not just any appearance of the method name in the code. This is quite useful if your classes are not sharing the same hierarchy.Often when you navigate the source code you jump over class hierarchies, browse different methods, open type declarations, etc. It is quite common that once in a while you would like to step several steps back in your navigation and proceed with some other direction. Ctrl+Alt+(left|right) arrow is a very useful shortcut for such purpose. Whenever a caret hits any place in the code this place is remembered and you can go back and forward in the your browsing history. This is quite cool as if you navigate a large code base you might not even remember which classes you actually opened just a second ago. Actually you can get a list of the recently visited files by pressing Ctrl+E – also quite often used to reopen the recently closed files. Navigating back in forward is the same in Eclipse (with Alt+(left|right)arrow shortcuts). But I failed to find a list of recently edited files there, while this can be done in IntelliJ by hitting Ctrl+Shift+E shortcut. There are plenty of other feature that make your code browsing experience more pleasant. For instance, both IntelliJ and Eclipse provide a feature to quickly browse the location of the currently opened class – Alt+Home will popup a navigation bar with the path to the class. The cool feature in IntelliJ for this navigation par is that it is possible to brows the content of any file with Ctrl+Shift+I without having to really open the file:In Eclipse a similar feature is called “Browse in Breadcrumb” called via Alt+Shift+B. The difference is that in Eclipse it works only if a Java type is opened and it acts only as a navigation bar – no quick preview available. Also, I didn’t find an easy way how to get rid of that “Breadcrumb” in Eclipse besides clicking a dedicated button on the toolbar. Ctrl+Shift+I also works in IntelliJ for any symbol that you’d probably like to inspect. For instance, you may press this shortcut on any method call, and it will raise a popup that displays the methods source code:Also, if you try to browse the code that maybe involved in the type hierarchy, it is possible to select the implementation by choosing the type in the very same quick view popup:Talking about navigation on the hierarchy of classes, IntelliJ implements that also quite nicely – quick hierarchy view is available the same way as in Eclipse. The feature that distinguishes IntelliJ is the ability to easily navigate to implementation. For instance, from interface method declaration to any of the implementations. If there are multiple implementations of an interface method Ctrl+Alt+B will call a popup dialog with the list of implementations:Find Usages “Find Usages” functionality is something that always made me nervous in Eclipse. Ctrl+Shift+G (find references in workspace) alone is ridiculously unusable. I mean, fine, you can find all the references to a method in the workspace with a single shortcut, but to do the same in a project scope you have to touch the mouse. Here’s what you have in IntelliJ. First of all Alt+F7 would give you almost the same as Gtrl+Shift+G in Eclipse besides that you don’t have to touch the mouse in order to define scope of the lookup. Arrow down will give you a choice of scopes available for the reference loopup, the hit Enter and you’re done. Even such simple feature is much usable in IntelliJ.Besides that a quick lookup is also available – with Ctrl+Alt+F7 you will get a popup with the list of the references for a method of interest and directly from there you can use the Ctrl+Shift+I (mentioned before) to view the sources code in which the method is used:Marking the occurrences of a variable works the same way in IntelliJ and Eclipse, besides that in Eclipse you can toggle the highligh and in IntelliJ you press a shortcut (Ctrl+Shift+F7) but no essential difference in the result for me. In IntelliJ, though, the highlight works on multiple variables while in Eclipse only on a single one.Bookmarks Navigating through the code is easier if there are means to bookmark some places in the code in order to be able return back to the location of interest. It seems that IntelliJ developers think of it as a priority as all the Ctrl+Shift+# and Ctrl+# shortcuts are reserved for bookmarking needs. Ctrl+Shift+# (e.g Ctrl+Shift+1) sets a quick bookmark on the line where the cursor is located. After that you can return back to the bookmarked location by pressing Ctrl+# (e.g. Ctrl+1). The character symbols can also be used for bookmarking the locations but without quick access to the location afterwards – a special menu must be used. The screencast below demonstrates this feature: In Eclipse, the bookmarking functionality is also available, but it lacks same level of usability as in IntelliJ – no shortcuts by default and not that simple to use without the mouse. Local History Both the IDEs, IntelliJ and Eclipse, keep track of local changes and provide local history view where you can browse the changes you’ve made. The feature is somewhat similar to using VCS, but without VCS. At first it seems that the feature is implemented the same way in IntelliJ and Eclipse but if you dig deeper and start really using it – you’ll notice the difference. Again, IntelliJ takes the feature a bit further in respect to usability (but I’m quite biased on this).Specially the diff-view, is quite intuitive for this feature – you can clearly see what are the changes and easily migrate ‘em. In Eclipse, the view is really similar but when I tested it – added new methods to a class, introduced new statements – I could not find those changes afterwards although an entry was created in the history view. In IntelliJ’s view you can create a patch or revert to a desired version.Smart Code Completion Typing is just tying, right? It is actually amazing how intelligent cat the IDE be for this purpose. Isn’t it cool when the IDE can autocomplete your statements just as you wanted? Here’s a simple example. I’d like to introduce a field in a class – I’ll type List<String> list = new .. and hit Ctrl+Space then. And what does Eclipse suggests me? List and a name of the class I’m declaring this field in. Not really intelligent, uh?In IntelliJ, after tying the same line of code, and pressing Ctrl+Space the popup gives me a list of List implementations available in classpath. Also, Ctrl+Shift+Space tries to be even smarter and proposes me ArrayList as a preferred choice.Another cool autocomplete behavior I discovered in IntelliJ is that if you try smart type completion twice (Ctrl+Shift+Space) then IntelliJ will search for chained expressions which have expected type.Live Templates Templates is the other feature that helps you to write code fast. Usually an IDE provides you a set of templates but you’re allowed to add new templates also. Let’s see how it is done in IntelliJ. Ctrl+J will popup a list of all the templates available and can be filtered by the template name. In case if you have just a few templates in the list it is not hard to find a correct one. But in case the list is too long it would be nice to have some other means for filtering the list. Just a coupe use cases for the templates: It is quite common to check the method parameter for null equality. The corresponding if-statement can be generated with inn template. So by typing “inn” in the editor and pressing the expansion key (TAB by default) we get the null-check-if-statement.Next, quite common piece of code, is iteration over a collection of elements. IntelliJ provides a number of iteration templates for various types of loops. The common thing among the iteration templates is that all they start with “it” – iter, itco, itar, etc. So for instance we have a collection of elements and by typing iter and the expansion key we’ll generate a foreach loop iterating the collection in context.Templates could also be used for surrounding statements in case it is applicable. Ctrl+Alt+T does the trick. For instance, id like to surround the objects retrieval with try/catch block but I’ve already managed to generate a loop iterating the resulting collection:Another template that I would mess in Eclipse by default is soutv that expands to a System.out.println(…) statement with a variable in context:Editing and creating the templates is quite straightforward and well-documented. Usually I define my own try/catch template as it is not provided out-of-the box (which is strange).The unique feature of the templates in IntelliJ is that you can define new templates that are backed with available features from the IDE, e.g smart code completion and other useful functions. Refactoring I think I’ll skip the refactoring part at large – this is just insane to compare the huge amount of refactorings available in the IDEs. Only one note on the usability for a simple refactoring use case – extract local variable/method/etc. In Eclipse you have to select the full statement before you press Alt+Shift+L (or position the cursor just after the expression), otherwise the IDE refused to understand what do you want to do popping up a message “An expression must be selected to activate this refactoring”. IntelliJ seems to be a bit more intelligent still detecting the context and providing you options for the same refactoring:More to come, stay tuned :) Reference: What’s Cool In IntelliJIDEA. Part I from our JCG partner Anton Arhipov at the Code Impossible blog. Related Articles :What’s Cool In IntelliJIDEA. Part II: Live Templates What’s Cool In IntelliJIDEA. Part III: External Tools Eclipse 3.6 vs IntelliJ IDEA 10.5: Pros and Cons Eclipse Shortcuts for Increased Productivity Eclipse Memory Analyzer (MAT) What to do with IDE project files Eclipse: How attach Java source Java Tutorials and Android Tutorials list...
software-development-2-logo

Book Review: The Passionate Programmer written by Chad Fowler

I just happened to get to know about this book while browsing through the books on Flipkart and the book immediately caught my attention. So here’s my review of the book: First things firstReally cool cover page of the book – [I know Chad Fowler's musical interest has some role to play in the designing of the cover page] 200 odd pages book- So you don’t feel its overdose of information Short chapters, lighter book. Each chapter followed by Act it! which guides you on how to implement the ideas explained. Nice and legible font used for the content.IntroductionAuthor speaks about Why the book was written- Really inspiring stuff there. Few aspects are highlighted just to give the reader an idea of what to expect in the next 200 odd pages. This will boost your urge to complete the book in one sitting.Just for the curious readers: The author tells about fighting the fear of failure and also owning one’s career growth just as a company owns its products and inspiring from this the book has been divided into 5 parts:Choosing market Investing in your product Executing Marketing yourself And Keeping the edge This sets the tone for the rest of the bookChoosing the market Author tries to address about:You were fascinated by that technology but didn’t try to read about it because it wasnt used at work? Influenced by your parents urge to play safe with the job even if you didn’t like it. You are not so excited to go to work and look for reasons to stay back home Still stuck with old technologies and not sure what to decide to learn Worried of losing your job to someone else Why should you care about the business domain you are working on.In short, this section is all about preparing your self for the change by identifying your current situation, assessing your interests, choosing or short listing the technologies you are planning to learn. Also there are 2 beautiful and inspiring case studies to help you get upbeat. Investing in Your Product Various lessons learnt in this section:Importance of learning to do things rather than getting it done from someone else Understanding the business working Importance of getting mentored by more experienced people- I really support this, i have seen how things change when you are mentored or interact with someone more experienced than you. Sharing improves one’s knowledge and so its useful to find someone whom you can mentor- The author has given few suggestions on how one can become a mentor. Importance of practice. Coming out of the comfort zone and trying out new technologies, different paradigms. Not depending on proprietary technologies and instead adopt open source community driven technologies.At times participating in Forum discussions can help you a lot in Finding a mentor and being a mentor. Also I would encourage participating in the open source communities and try reading the code and writing patches (This is something I didn’t do and I would encourage people to practice this right from their under-graduate studies). Executing Important section and explains how one can start executing the ideas and plans formulated in the previous 2 sections. Various strategies highlighted for executing ideas and plans are:Not procrastinating the work, doing it right now Monitoring the daily tasks performed Trying to predict the requirements or tasks – this is a tough activity but with practice one should become fairly good. Not trying to day dream about your promotions, hike or trying to target next levels without justifying the current position. Identifying the value added to the company Not fearing failure, taking risks and learning from failures. Keeping calm during tough situations. Judging one’s ability before taking up tasks- taking up all the tasks is not good and denying all the tasks is also not good.Marketing Its not enough to just analyze, invest and execute the plans, gain more expertise in different technical areas, but what’s more important is how you present/market yourself. The author tries to:Explain the need for presenting your skills. Throw light on how you can get under the focus of your teammates and manager- “Out of sight is out of mind” so one has to avoid that. Explain the importance of writing articles, speaking at conferences and also going to the extent of authoring books on your favorite technologies. Suggests to participate in open source technologies- write code, try to gain visibility in the community Setup a blog- and start writing, sharing your ideas, learning. But don’t try to make a fool of yourself in the process.Maintaining the Edge “Its easier to get to the top, but its difficult to stay there”- this section is written keeping this in mind.Keeping updated about the technologies – what’s promising, what’s going to be stale. Trying to incrementally change – keep getting better each day Planning the career – Being agile, welcome changes and adapt.Final thoughtsMust read book for any software developer Explained the ideas through sensible analogy Provides tips to actually implement the discussed idea. Simple language, short chaptersReference: Book Review: The Passionate Programmer written by Chad Fowler from our JCG partner Mohamed at the “Experiences Unlimited” blog. Related Articles :Top 10 Java Books you don’t want to miss Java Developer Most Useful Books The top 9+7 things every programmer or architect should know Things Every Programmer Should Know Programming Android Online Book Java Tutorials and Android Tutorials list...
apache-logo

Web-service learnings with Apache CXF

In my last couple of projects I worked with web-services, creating them at some places and consuming them at others. I felt that the standard tasks like creating a client, creating a web service etc are quite straight forward and there are enough resources if you get stuck. But with web services, it is some trivial task that can take a lot of your time and you feel quite frustrated when you can not get that simple thing right. Logging In one of the projects, we created web-services using Apache CXF and things were working fine. There was just one issue Apache CXF uses java.util logger for logging and used to print all sorts of logs. Our application was using Log4J, so task was simple make use of Log4J for Cxf and control logging. Configuring the logger to use Log4J is a starightfoward task as mentioned on Apache CXF site, here is what the page says: Add the file META-INF/cxf/org.apache.cxf.Logger to the classpath and make sure it contains the following content: org.apache.cxf.common.logging.Log4jLogger Simple you need add a file to the META-INF directory and it will be done. We were having a maven project to generate war, so I created the file in the META-INF folder that gets generated for the war i.e. at src/main/webapp/META-INF. Now, the file is there but the logging was still out of control, CXF was still using java logger. I spent some more time on it to figure out what I have done wrong. Some more effort was required to realize that I have missed and important instruction “in the classpath“. The META-INF folder that gets generated besides the WEB-INF is not in the classpath and a META-INF folder is required in the classes folder of the war. After words looking back at this issue, it was silly for me to miss the classpath part, but also I could not understand why the CXF guys choose the META-INF folder for their configuration files. META-INF is there on Java platform for services and class loaders. It becomes quite ambiguous when frameworks start using it for their configurations and then there are multiple folders to play around, which can make things quite unclear. Soap Handlers At another place we had a requirement where we need to intercept the incoming / outgoing soap requests and then do something with it. Apache CXF provides interceptors that can be used to accomplish this task. You can have some inbound and out bound and they will do as asked. But we were using the jaxws implementation that gets shipped with java. Not intending to shift our existing clients to CXF , as we were having quite a few clients, it took us quite some time to figure it out how you can accomplish this with the jaxws. Basically, according to the JAX-WS specification you can have some SoapHandlers that can be configured with the client. The handler will be called every time there is a SOAP message exchange. In the handler you can determine if this is an in-bound message or an out-bound and then do your logic. These are the steps required to configure a handler : Create a class extending the SoapHandler interface and implement the handle message method: class CustomHandler implements SOAPHandler<SOAPMessageContext>{ // TODO: implement other methods public boolean handleMessage(SOAPMessageContext context) { // Check for message status Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY); if (null == outboundProperty || !outboundProperty) { log.debug("not an outbound message"); return true; } } }Handlers are like servlet filters. They are in a chain and gets called one by one. So we need to create a XML file in which we can configure all the handlers we want. <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <javaee:handler-chains xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <javaee:handler-chain> <javaee:handler> <javaee:handler-class>pkg.CustomHandler</javaee:handler-class> </javaee:handler> </javaee:handler-chain> </javaee:handler-chains>Also the configuration file needs to be in the classpath as this will be imported in the web service clients that we create. After this is done, we need to enable this chain of handlers on a web service client. @WebServiceClient(.....) @HandlerChain(file="handlerFile.xml") public class SampleServiceImpl extends Service{ }The handler concept is from the jaxws specification and would work on all of its implementations like metro, CXF etc. Reference: Web-service learnings from our JCG partner Rahul Sharma at the “The road so far….” blog. Related Articles :Apache CXF Load Balancing And Failover Web Services in Ruby, Python and Java JAX–WS with Spring and Maven Tutorial Spring 3 RESTful Web Services Java Tutorials and Android Tutorials list...
java-logo

Java SE 7, 8, 9 – Moving Java Forward

Today (NOTE: October 4, 2011) was keynote day. JavaOne Keynote was happening this early morning from 8:30 to 10:30 am and one more time my press pass got me into it quite early. So I had the time taking some very personal pictures from all the key players while they were getting ready and probably nervous. Ballroom A+B is quite a big room. In contrast to last year they changed the arrangement and put the stage on the long side. That brought many people closer to the happenings and it was a great feeling at all. I also partly enjoyed the little warm-up movie. Even if there was a odd feel to it seeing all the diverse people running around. Even if I am slightly overweight, I would prefer to see some very cool kids running through such a video. Anyway: Nice work. Next time please try to get the Black Eyed Peas for that ;) Intel outside please The Keynote began with Doug Fisher, CVP Intel. He brought a number of colleagues onto stage together with their Oracle peers to reviewed Intel’s long association with Java and their optimization work for the Java platform on Intel hardware. it was all about performance gains and being x times faster than they were before. The guys seem to all read from the teleprompters and it really wasn’t a great joy to watch them making jokes they were obviously practicing before. What should I tell you? Nice slides. Next slide deck please!It was boring and would have made a reasonable Open World Keynote at all. Many commercial products in it and not a word about what they really brought forward in terms of Java. This was something I wouldn’t mind if it is missing next year. And this did not get better as Oracle’s Ashok Joshi came onstage to very very briefly introduce Oracle’s NoSQL solutions (hardly without naming it…). You can find out on the web about it. I guess all is out about this one since today. But I will skip the details here until I got my hands on it. Welcome to the Future – Java 7 After a little confusions about who and what is next, Mark Reinhold, Chief Architect of the Java Platform Group appeared on stage and took the attendees on a ride through the recent history of Java 7. All along the way with “Plan B” and the pragmatic approach of including Project Coin (JSR 334), InvokeDynamic (JSR 292), and the Fork/Join Framework. Special guest was Charles Oliver Nutter from Engine Yard. He gave a very brief overview about the performance advantages InvokeDynamic made possible for JRuby.Mark has a good way in presenting and he even got the hardest bits out with lightweight slides and fluent words so it was a pleasure to follow him along the benefits of these key features of Java 7. Most important for all developers is, that “Not only are these features available in Java 7 today,” noted Reinhold, “but as of last week, they are now supported in all three of the major Java IDEs.” Moving forward – Java SE 8 Followed by what was already known since some time Mark detailed the plans for Java 8 a bit. After having the evolutionary release with Java 7 this is going to be a revolutionary one with the features far beyond those introduced with Java 7. Project Lambda (JSR 335) will bring closures to the Java programming language.And Project Jigsaw (JSR TBD) aims to define a standard module system — not just for application code, but for the platform itself. Especially the latest makes it possible to only have the needed bits with your distribution of choice. As he states, there will be Java distributions available starting at 10 MB. A new Java Script Implementation called “Project Nashorn” will also be part of it. Followed by Type Annotations (JSR 308), the new Data/Time API (JSR 310) and Sensors which should be a way to natively connect to a device’s hardware sensors available. “Plus more to come …” is the last bullet point on this slide. So, we have to expect some more stuff beside the ones mentioned. General Availability of JavaFX 2.0 JavaFX was next. As many already expected it took quite some time away from the keynote. Richard Bair, Chief Architect, Client Java Platform, official announced JavaFX 2.0 and gave some stunning demos of the new facilities.According to him, JavaFX 2.0 was designed to offer: - Cross Platform - Leverage Java - Advanced Tooling - Developer Productivity - Amazing User Interfaces.No longer being eye-candy “user interfaces that look good and work well” are a requirement for the things we do, said Bair. The most important aspect of any UI technology are good visual development tools. Surprise was, that the early access for the JavaFX Scene Builder, which will first be made available to select partners, then expanded to a general beta, and then a full release. You can get your hands on and early build it at JavaOne at the DEMOgrounds. Most applause came from the fact, that the official demos and documentations are BSD licensed and part of the bundle, you can download. This simple stuff was followed by a series of stunning demos by Oracle’s Jasper Potts. He showed the possibilities of the new client platform including animated 2D and 3D, audio EQ mapping, and a navigable 3D virtual room that featured live video. Is that Rain? – Java EE 7 in the cloud! With all the rain going on in San Francisco some could think, Oracle did too much with all the cloud topics around. Anyway, Java EE.next as announced last year will be driven by the cloud. Linda DeMichiel, Java EE 7 SpecLead did a nice job explaining the upcoming Java EE 7 release. “We’re moving Java EE into the Cloud.” DeMichiel said. The focus on this release is providing support for Platform as a Service (PaaS). Java EE will provide ways for it’s users to leverage public, private and hybrid clouds.It will all be about the platform as a service itself, which will be leveraged in cloud environments. After a real short general introduction, which could lead to the impression, she is not knowing what she is talking about (which isn’t true btw!) Arun Gupta came on stage. You all know him as the GlassFish and Java EE Evangelist! He demonstrated the latest GlassFish 4.0 Bits with a Java EE 7 cloud deployment. You can do this yourself following the instructions provided at: http://glassfish.java.net/javaone2011/ JavaCard Finally Hinkmond Wong, of Oracle’s Java Embedded group gave an overview of the latest in JavaCard technologies. By that time attendees started moving out of the keynotes. It was a very long one with a lot of topics in general and so I can understand every single one moving out. Interpretation What does all this mean? Any surprises? Anything unclear or need further thoughts? Not really. Compared to last years excitement there are hardly any exciting things on the agenda. Nobody is complaining, no big surprises. This is good. It means we have calmed down a bit. The trust is building and Oracle is obviously doing more stuff in the open (especially the works around OpenJDK should be mentioned here) and we do see a lot of technical progress in the complete platform in general. Of course, we do miss some faces from last year. And knowing a little more than you out there, I can think of a few more things to come over the next few months. But this will not be negative surprises, so it’s easy for me to keep the secrets for some more time. Reference: Java SE 7, 8, 9 – Moving Java Forward from our JCG partner Markus Eisele at the “Enterprise Software Development with Java” blog. Related Articles :Java EE Past, Present, & Cloud 7 Developing and Testing in the Cloud The OpenJDK as the default Java on Linux Official Java 7 for Mac OS X – Status Grow Up Java! Proposing Java Desktop Edition Java Tutorials and Android Tutorials list...
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books