XML example with RESTEasy + JAXB

RESTEasy, is required JAXB to support XML file. In this tutorial, we show you how to create an “user” object, convert it into XML file, and return it back to the client. 1. RESTEasy + JAXB To use JAXB in RESTEasy, you need to include the “resteasy-jaxb-provider.jar” dependency. File : pom.xml <repositories> <repository> <id>JBoss repository</id> …

Read more

RESTEasy – Could not find MessageBodyWriter for response object of type:xx of media type: application/xml

Problem Developing RESTEasy + JAXB provider to support XML, when return it back to client, it prompts following error message : org.jboss.resteasy.core.NoMessageBodyWriterFoundFailure: Could not find MessageBodyWriter for response object of type: com.mkyong.rest.User of media type: application/xml at org.jboss.resteasy.core.ServerResponse.writeTo(ServerResponse.java:216) at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:500) at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:119) //… Solution To use JAXB in RESTEasy, you need to include “resteasy-jaxb-provider.jar“. <repositories> …

Read more

File upload example in RESTEasy

Not many complete file upload example in JAX-RS, especially RESTEasy. Here, we show you two complete RESTEasy examples to handle file upload from HTML form. Normal way to handle uploaded file via MultipartFormDataInput Map uploaded file to a POJO class via @MultipartForm 1. RESTEasy Multipart Dependency In RESTEasy, you need “resteasy-multipart-provider.jar” to handle multipart file …

Read more

Download excel file from JAX-RS

In JAX-RS, for excel file, annotate the method with @Produces(“application/vnd.ms-excel”) : Put @Produces(“application/vnd.ms-excel”) on service method. Set “Content-Disposition” in Response header to prompt a download box. 1. Download Excel file in JAX-RS Full example to download an excel file from JAX-RS. import java.io.File; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; @Path("/excel") public …

Read more

RESTEasy – Could not find message body reader for type: multipart/form-data

Note Tested with Eclipse 3.6, Maven 3 and RESTEasy 2.2.1.GA Question Developing file upload feature with RESTEasy, see following RESTEasy multipart file upload example : public class FileUploadForm { private byte[] data; @FormParam("file") public void setData(byte[] data) { this.data = data; } //…code omitted } @Path("/file") public class UploadFileService { @POST @Path("/upload") @Consumes("multipart/form-data") public Response …

Read more

RESTEasy Unable to scan WEB-INF for JAX-RS annotations ?

Question Developing REST service, with file upload function with resteasy, after added resteasy multipart dependency, following strange error message prompt during the application start up? P.S Using resteasy-jaxrs and resteasy-multipart version 2.2.1.GA. SEVERE: Exception sending context initialized event to listener instance of class org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap java.lang.RuntimeException: Unable to scan WEB-INF for JAX-RS annotations, you must manually …

Read more

Download image file from JAX-RS

In JAX-RS, for user to download an image file, annotate the method with @Produces(“image/image-type”) : Put @Produces(“image/png”) on service method, for “png” image. Set “Content-Disposition” in Response header to prompt a download box. Note For other image types, refer to this list of the image types 1. Download Image in JAX-RS Full example to download …

Read more

Download text file from JAX-RS

In JAX-RS, for user to download a file, annotate the method with @Produces(“text/plain”) : Put @Produces(“text/plain”) on service method, with a Response return type. It means the output is a text file. Set “Content-Disposition” in Response header to tell browser pop up a download box for user to download. 1. Download File in JAX-RS See …

Read more

ClassNotFoundException : com.sun.jersey.spi.container.servlet.ServletContainer

Problem In Jersey development, hit following error message on Tomcat. SEVERE: Servlet /RESTfulExample threw load() exception java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1516) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1361) //… Here’s the Maven pom.xml <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-core</artifactId> <version>1.8</version> </dependency> Solution The “com.sun.jersey.spi.container.servlet.ServletContainer” is included in “jersey-server.jar“, not “jersey-core.jar“. Actually, to develop REST service with Jersey, you just need to include “jersey-server.jar“, it …

Read more

Get HTTP header in JAX-RS

In this tutorial, we show you two ways to get HTTP request header in JAX-RS : Inject directly with @HeaderParam Pragmatically via @Context Note Refer to this wiki page for list of the HTTP header fields. 1. @HeaderParam Example In this example, it gets the browser “user-agent” from request header. import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import …

Read more

JAX-RS @FormParam example

In JAX-RS, you can use @FormParam annotation to bind HTML form parameters value to a Java method. The following example show you how to do it : 1. HTML Form See a simple HTML form with “post” method. <html> <body> <h1>JAX-RS @FormQuery Testing</h1> <form action="rest/user/add" method="post"> <p> Name : <input type="text" name="name" /> </p> <p> …

Read more

Download pdf file from JAX-RS

In JAX-RS, for pdf file, annotate the method with @Produces(“application/pdf”) : Put @Produces(“application/pdf”) on service method. Set “Content-Disposition” in Response header to prompt a download box. 1. Download Pdf file in JAX-RS Full example to download a pdf file from JAX-RS. import java.io.File; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; @Path("/pdf") public …

Read more

JAX-RS @QueryParam example

In JAX-RS, you can use @QueryParam annotation to inject URI query parameter into Java method. for example, /users/query?url=mkyong.com In above URI pattern, query parameter is “url=mkyong.com“, and you can get the url value with @QueryParam(“url”). 1. @QueryParam example See a full example of using @QueryParam in JAX-RS. import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; …

Read more

ClassNotFoundException : org.jboss.resteasy.plugins.providers.multipart.MultipartInput

Question Working REST + file upload, using resteasy 2.2.1.GA and Eclipse 3.6. And the reseteasy multipart dependency is declared in maven pom.xml file. In compile mode, class “MultipartInput” is able to compile, but Eclipse prompts following error message during deployment or debugging mode? java.lang.NoClassDefFoundError: org/jboss/resteasy/plugins/providers/multipart/MultipartInput at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Class.java:2427) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414) Caused by: java.lang.ClassNotFoundException: …

Read more

JAX-RS @MatrixParam example

Matrix parameters are a set of “name=value” in URI path, for example, /books/2011;author=mkyong In above URI, the matrix parameter is “author=mkyong“, separate by a semi colon “;“. 1. @MatrixParam example See a full example of using @MatrixParam in JAX-RS. import javax.ws.rs.GET; import javax.ws.rs.MatrixParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; @Path("/books") public class BookService { @GET …

Read more

JAX-RS @PathParam example

In JAX-RS, you can use @PathParem to inject the value of URI parameter that defined in @Path expression, into Java method. 1. @PathParam – Single Parameter A simple and normal way to use @PathParam. import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; @Path("/users") public class UserRestService { @GET @Path("{id}") public Response getUserById(@PathParam("id") String id) { …

Read more

JAX-RS @Path URI matching example

In JAX-RS, you can use @Path to bind URI pattern to a Java method. See following examples to show you how it works. 1. Normal URI Matching See normal URI matching with @Path annotation. import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; @Path("/users") public class UserRestService { @GET public Response getUser() { return Response.status(200).entity("getUser is called").build(); } …

Read more

RESTEasy hello world example

RESTEasy, JBoss project, implementation of the JAX-RS specification. In this tutorial, we show you how to use RESTEasy framework to create a simple REST style web application. Technologies and Tools used in this article: RESTEasy 2.2.1.GA JDK 1.6 Maven 3.0.3 Eclipse 3.6 What’s REST? Read this, this and this to understand what’s REST. 1. Directory …

Read more

Top 5 free Java ebooks

There are many free Java eBooks, but most are outdated or not accurate. Here’s the best 5 free Java eBooks in my collection, they are well-known, complete, updated and detailed coverage of using Java programming language. Best for Java beginners and might also good reference for experienced programmers. P.S The order is based on my …

Read more

Spring Object/XML mapping example

The Spring’s Object/XML Mapping, is converting Object to XML or vice verse. This process is also known as XML Marshalling – Convert Object to XML. XML UnMarshalling – Convert XML to Object. In this tutorial, we show you how to use Spring’s oxm to do the conversion, Object XML. Note No nonsense, for why and …

Read more

ClassNotFoundException: org.apache.xml.serialize.XMLSerializer

Problem With Spring OXM + Castor binding, the Castor library is added, but still hit the following error message? Exception in thread "main" java.lang.RuntimeException: Could not instantiate serializer org.apache.xml.serialize.XMLSerializer: java.lang.ClassNotFoundException: org.apache.xml.serialize.XMLSerializer at org.exolab.castor.xml.XercesSerializer.<init>(XercesSerializer.java:50) //… Castor dependency in Maven. <dependency> <groupId>org.codehaus.castor</groupId> <artifactId>castor</artifactId> <version>1.2</version> </dependency> Solution If not mistake, Castor need Xerces to work, so, you need …

Read more

ClassNotFoundException : org.exolab.castor.xml.XMLException

Problem In Spring OXM (object XML mapping), when converting an object to XML file, it hits following error message : Caused by: java.lang.ClassNotFoundException: org.exolab.castor.xml.XMLException at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:252) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) … 29 more Is castor data binding framework included in Spring oxm? Solution The castor is …

Read more

Spring AOP + AspectJ annotation example

In this tutorial, we show you how to integrate AspectJ annotation with Spring AOP framework. In simple, Spring AOP + AspectJ allow you to intercept method easily. Common AspectJ annotations : @Before – Run before the method execution @After – Run after the method returned a result @AfterReturning – Run after the method returned a …

Read more

Spring 3 JavaConfig @Import example

Normally, you will split a large Spring XML bean files into multiple small files, group by module or category, to make things more maintainable and modular. For example, <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <import resource="config/customer.xml"/> <import resource="config/scheduler.xml"/> </beans> In Spring3 JavaConfig, the equivalent functionality is @Import. package com.mkyong.config; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @Import({ CustomerConfig.class, …

Read more

Spring 3 JavaConfig example

Since Spring 3, JavaConfig features are included in core Spring module, it allow developer to move bean definition and Spring configuration out of XML file into Java class. But, you are still allow to use the classic XML way to define beans and configuration, the JavaConfig is just another alternative solution. See the different between …

Read more

CGLIB is required to process @Configuration classes

Problem Using Spring3 @Configuration to create an application configuration file like below : import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean //… } However, when run it, it hits following error message : org.springframework.context.support.AbstractApplicationContext prepareRefresh //… Exception in thread "main" java.lang.IllegalStateException: CGLIB is required to process @Configuration classes. Either add CGLIB to the classpath or …

Read more

Spring EL Lists, Maps example

In this article, we show you how to use Spring EL to get value from Map and List. Actually, the way of SpEL works with Map and List is exactly same with Java. See example : //get map whete key = ‘MapA’ @Value("#{testBean.map[‘MapA’]}") private String mapA; //get first value from list, list is 0-based. @Value("#{testBean.list[0]}") …

Read more

Spring EL Operators example

Spring EL supports most of the standard mathematical, logical or relational operators. For example, Relational operators – equal (==, eq), not equal (!=, ne), less than (<, lt), less than or equal (<= , le), greater than (>, gt), and greater than or equal (>=, ge). Logical operators – and, or, and not (!). Mathematical …

Read more

Spring EL bean reference example

In Spring EL, you can reference a bean, and nested properties using a ‘dot (.)‘ symbol. For example, “bean.property_name“. public class Customer { @Value("#{addressBean.country}") private String country; In above code snippet, it inject the value of “country” property from “addressBean” bean into current “customer” class, “country” property. Spring EL in Annotation See following example, show …

Read more

Spring EL regular expression example

Spring EL supports regular expression using a simple keyword “matches“, which is really awesome! For examples, @Value("#{‘100’ matches ‘\\d+’ }") private boolean isDigit; It test whether ‘100‘ is a valid digit via regular expression ‘\\d+‘. Spring EL in Annotation See following Spring EL regular expression examples, some mixed with ternary operator, which makes Spring EL …

Read more

Spring EL ternary operator (if-then-else) example

Spring EL supports ternary operator , perform “if then else” conditional checking. For example, condition ? true : false Spring EL in Annotation Spring EL ternary operator with @Value annotation. In this example, if “itemBean.qtyOnHand” is less than 100, then set “customerBean.warning” to true, else set it to false. package com.mkyong.core; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; …

Read more

Spring EL method invocation example

Spring expression language (SpEL) allow developer uses expression to execute method and inject the method returned value into property, or so called “SpEL method invocation“. Spring EL in Annotation See how to do Spring EL method invocation with @Value annotation. package com.mkyong.core; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component("customerBean") public class Customer { @Value("#{‘mkyong’.toUpperCase()}") private String name; …

Read more

Test Spring el with ExpressionParser

Spring expression language (SpEL) supports many functionality, and you can test those expression features with this special “ExpressionParser” interface. Here’s two code snippets, show the basic usage of using Spring EL. SpEL to evaluate the literal string expression. ExpressionParser parser = new SpelExpressionParser(); Expression exp = parser.parseExpression("’put spel expression here’"); String msg = exp.getValue(String.class); SpEL …

Read more

Spring EL hello world example

The Spring EL is similar with OGNL and JSF EL, and evaluated or executed during the bean creation time. In addition, all Spring expressions are available via XML or annotation. In this tutorial, we show you how to use Spring Expression Language(SpEL), to inject String, integer and bean into property, both in XML and annotation. …

Read more

Spring Autowiring @Qualifier example

In Spring, @Qualifier means, which bean is qualify to autowired on a field. See following scenario : Autowiring Example See below example, it will autowired a “person” bean into customer’s person property. package com.mkyong.common; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; public class Customer { @Autowired private Person person; //… } But, two similar beans “com.mkyong.common.Person” are declared …

Read more

Spring Autowiring by AutoDetect

In Spring, “Autowiring by AutoDetect“, means chooses “autowire by constructor” if default constructor (argument with any data type), otherwise uses “autowire by type“. See an example of Spring “auto wiring by autodetect”. Auto wiring the “kungfu” bean into “panda”, via constructor or type (base on the implementation of panda bean). <bean id="panda" class="com.mkyong.common.Panda" autowire="autodetect" /> …

Read more

Spring Autowiring by Constructor

In Spring, “Autowiring by Constructor” is actually autowiring by Type in constructor argument. It means, if data type of a bean is same as the data type of other bean constructor argument, auto wire it. See a full example of Spring auto wiring by constructor. 1. Beans Two beans, developer and language. package com.mkyong.common; public …

Read more

Spring DI via constructor

Uses Spring to dependency inject a bean via constructor. 1. IOutputGenerator An interface and implementation class of it. package com.mkyong.output; public interface IOutputGenerator { public void generateOutput(); } package com.mkyong.output.impl; import com.mkyong.output.IOutputGenerator; public class JsonOutputGenerator implements IOutputGenerator { public void generateOutput(){ System.out.println("This is Json Output Generator"); } } 2. Helper class A helper class, later …

Read more