No bean named 'cxf' is defined even after importing cxf.xml - apache

I tried to expose one of my method as REST webservice using Apache CXF. When I try to access the webservice at http://localhost:7080/CXFwithMaven/services/book/abc i get the following error.
javax.servlet.ServletException: Servlet.init() for servlet CXFServlet threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:745)
root cause
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'cxf' is defined
org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:694)
org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1168)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:281)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:962)
org.apache.cxf.transport.servlet.CXFServlet.loadBus(CXFServlet.java:75)
org.apache.cxf.transport.servlet.CXFNonSpringServlet.init(CXFNonSpringServlet.java:76)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:745)
I tried searching on the internet and found that this usually happens when you don't import cxf files such as
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
Although i have imported the files, i am still getting the same error.
Please see the below VO.
package sample.cxfwithspring;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="Book")
public class BookVO {
private String name;
private String author;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
And here is my service.
package sample.cxfwithspring;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
#Path("/book")
public interface BookService {
#GET
#Produces("application/xml")
#Path("/{name}")
public BookVO getBook(#PathParam("{name}") String name);
}
And serviceImpl
package sample.cxfwithspring;
public class BookServiceImpl implements BookService {
public BookVO getBook(String name) {
BookVO bookVO = new BookVO();
bookVO.setAuthor("abc");
bookVO.setName("Rest with CXF");
return bookVO;
}
}
Web.xml
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:cxf.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
</web-app>
and cxf.xml
<beans xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.0.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<jaxrs:server address="/" id="connectionService">
<jaxrs:serviceBeans>
<ref bean="book" />
</jaxrs:serviceBeans>
<jaxrs:extensionMappings>
<entry key="xml" value="application/xml">
</entry>
</jaxrs:extensionMappings>
</jaxrs:server>
<bean class="sample.cxfwithspring.BookServiceImpl" id="book">
</bean>
</beans>
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.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Sample</groupId>
<artifactId>CXFwithMaven</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>CXFwithMaven Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>2.7.8</version>
</dependency>
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.3.4</version>
</dependency>
<dependency>
<groupId>org.apache.neethi</groupId>
<artifactId>neethi</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>com.sun.xml.fastinfoset</groupId>
<artifactId>FastInfoset</artifactId>
<version>1.2.13</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.1</version>
</dependency>
</dependencies>
<build>
<finalName>CXFwithMaven</finalName>
</build>
</project>
Please help me out as I am a newbie to Apche CXF and tried searching everywhere but wasn't able to find a solution for this.

Turns out, adding these two lines was the problem
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
Removing them did the trick.
:D

Related

File Upload with JAX-RS gives Bad arguments passed error

I want to upload file with jax-rs. I start tomcat,then send request from postman but, I got exception the below. I ve tried to change resteasy dependencies but didn't solve my problem.
Failed executing POST files/upload
org.jboss.resteasy.spi.InternalServerErrorException: Bad arguments passed to public javax.ws.rs.core.Response
The below is my upload class.
#Path("/files")
public class FileUpload {
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) {
String fileLocation = "/home/" + fileDetail.getFileName();
//saving file
try {
FileOutputStream out = new FileOutputStream(new File(fileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(fileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {e.printStackTrace();}
String output = "File successfully uploaded to : " + fileLocation;
return Response.status(200).entity(output).build();
}
}
The pom.xml file is the below. I'm confused that is the problem about dependencies.
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<repositories>
<repository>
<id>JBoss repository</id>
<url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url>
</repository>
</repositories>
<dependencies>
<!--resteasy-->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>3.1.4.Final</version>
</dependency>
<!--rest-easy client-->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.1.4.Final</version>
</dependency>
<!--unit test-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.17.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.17.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.17.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.jersey.contribs/jersey-multipart -->
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>1.17.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.containers/jersey-container-servlet-core -->
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-multipart-provider</artifactId>
<version>3.0.24.Final</version>
</dependency>
</dependencies>
<packaging>war</packaging>
</project>
The below is my web.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<!--Prefix for the endpoints-->
<param-value>/</param-value>
</context-param>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.fileServer.app.HelloApplication</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<!--Prefix for endpoint-->
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>

Spring + RESTEasy subresource is not injected with the dependencies

I'm using Spring for IoC and Data JPA support and JAX-RS support is provided by RESTEasy implementation.
I have the following pom.xml dependencies:
<dependencies>
<!-- Database Dependencies -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<!-- Integration with RESTEasy -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-spring</artifactId>
<version>4.2.0.Final</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-servlet-initializer</artifactId>
<version>4.4.1.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>4.4.1.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson2-provider</artifactId>
<version>4.4.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
</dependency>
</dependencies>
web.xml :
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<listener>
<listener-class>org.jboss.resteasy.plugins.spring.SpringContextLoaderListener</listener-class>
</listener>
</web-app>
appContext.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.test" />
</beans:beans>
I have two resources:
Parent:
#Component
#Path("/parent")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public class ParentResource {
#Context
ResourceContext resourceContext;
#GET
#Path("sub")
public ChildResource getSub() {
return resourceContext.getResource(ChildResource.class);
}
}
Child:
#Component
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public class ChildResource {
#Autowired
Repository1 repository1;
}
This example is totally working with Jersey implementation and I can get repository from the sub resource, but in RESTEasy implementation it does not work and instead of repository instance there is null.
There is a workaround, like this:
ChildResource resource = resourceContext.getResource(ChildResource.class);
resource.setRep(repositoryFromParent);
return resource;
But it is ugly and it should not be in that way (also parent should know about all dependencies of the sub resource which is also not good).
Has anyone encountered the same issue working with subresources using Spring and RESTEasy together?

Simple POC for authorization only using Apache Shiro

I am new for Apache shiro and rest web service. Based on my requirement i am creating simple POC using Shiro and rest service.
In my application i do not use any login page. simply only one TestService.java with 4 webs service method
I want to control each web service method with different role through invoke the rest client. means
insertNewData() method required 'insert' role, otherwise show some error message
updateNewData() method required 'update' role , otherwise show some error message
deleteNewData() method required 'delete' role, otherwise show some error message
searchAllData() method required 'admin' role, otherwise show some error message
I have no idea about how to configure shiro.ini file for my requirement and rest configuration.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>SimpleRest</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>
<filter>
<filter-name>ShiroFilter</filter-name>
<filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ShiroFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping> </web-app>
/WEB-INF/shiro.ini Here how to configure the different role for web service hit
[main]
[users]
[roles]
[urls]
/index.html = anon
TestService.java
package com.simple.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.json.JSONException;
#Path("/testservice")
public class TestService {
#Path("/insert")
#GET
#Produces("application/json")
#RequiresRoles( "insert" )
public Response insertNewData() throws JSONException {
/**
* Here insert logic
*/
String result = "Insert data method called";
return Response.status(200).entity(result).build();
}
#Path("/update")
#GET
#Produces("application/json")
#RequiresRoles( "update" )
public Response updateNewData() throws JSONException {
/**
* Here Update logic
*/
String result = "Updated data method called";
return Response.status(200).entity(result).build();
}
#Path("/delete")
#GET
#Produces("application/json")
#RequiresRoles( "delete" )
public Response deleteNewData() throws JSONException {
/**
* Here delete logic
*/
String result = "Delete data method called";
return Response.status(200).entity(result).build();
}
#Path("/searchall")
#GET
#Produces("application/json")
#RequiresRoles( "admin" )
public Response searchNewData() throws JSONException {
/**
* Here Search logic
*/
String result = "User have admin rights. So only disply all data";
return Response.status(200).entity(result).build();
} }
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.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SimpleRest</groupId>
<artifactId>SimpleRest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<jdk.version>1.7</jdk.version>
<shiro.version>1.2.4</shiro.version>
<commons-logging.version>1.2</commons-logging.version>
<logback-classic.version>1.1.3</logback-classic.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>${commons-logging.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback-classic.version}</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.19</version>
</dependency>
</dependencies>
<build>
<finalName>SimpleRest</finalName>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build></project>
Please help me on this.
thanks in advance
Take a look at Shiro's official JAX-RS example.

java.lang.ClassCastException: org.glassfish.jersey.jackson.internal.JacksonAutoDiscoverable cannot be cast to spi.AutoDiscoverable

I am new to implementing REST API services. I have tried the simple resources to implement. unfortunately I stuck with this exception. I have googled and tried many options but no luck. I am unsure what am doing wrong. Please help me.
Created a Dynamic Web project "JersyJson"
Created a resouce named - JSONService.java (source is from googling)
Created a Java Bean class - Track.java (source is from googling)
Converted the project into Maven project
Created a Application file - JersyJson.java file for Application Annotation
using the latest Jersy Jars (version: 2.22.2)
Imported & configured jersey-media-json-jackson and jersey-media-moxy jars (2.22.2) in pom.xml
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.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>JersyJson</groupId>
<artifactId>JersyJson</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<!-- if your container implements Servlet API older than 3.0, use "jersey-container-servlet-core" -->
<artifactId>jersey-container-servlet</artifactId>
<version>2.22.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.22.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.22.2</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>JersyJson</display-name>
<servlet>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<url-pattern>/json/metallica/*</url-pattern>
</servlet-mapping>
</web-app>
JersyJson.java (ApplicationAnnotation file)
#ApplicationPath("json")
public class JersyJson extends ResourceConfig {
public JersyJson() {
packages("com.sai.jersyjson");
}
}
JSONservice.java:
package com.sai.jersyjson;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("/json/metallica")
public class JSONService {
#GET
#Path("/get")
#Produces(MediaType.APPLICATION_JSON)
public Track getTrackInJSON() {
Track track = new Track();
track.setTitle("Enter Sandman");
track.setSinger("Metallica");
return track;
}
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
public Response createTrackInJSON(Track track) {
String result = "Track saved : " + track;
return Response.status(201).entity(result).build();
}
}
Track.java (simple bean class)
package com.sai.jersyjson;
public class Track {
String title;
String singer;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSinger() {
return singer;
}
public void setSinger(String singer) {
this.singer = singer;
}
#Override
public String toString() {
return "Track [title=" + title + ", singer=" + singer + "]";
}
}
After I run this project in Eclispe using Tomcat webserver, I get the following
error with 404-Error Status
SEVERE: StandardWrapper.Throwable
java.lang.ClassCastException: org.glassfish.jersey.jackson.internal.JacksonAutoDiscoverable cannot be cast to org.glassfish.jersey.internal.spi.AutoDiscoverable
at org.glassfish.jersey.model.internal.CommonConfig$2.compare(CommonConfig.java:594)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at java.util.AbstractCollection.addAll(Unknown Source)
at java.util.TreeSet.addAll(Unknown Source)
at org.glassfish.jersey.model.internal.CommonConfig.configureAutoDiscoverableProviders(CommonConfig.java:616)
at org.glassfish.jersey.server.ResourceConfig.configureAutoDiscoverableProviders(ResourceConfig.java:811)
at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:447)
at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:184)
at org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:350)
at org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:347)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:255)
at org.glassfish.jersey.server.ApplicationHandler.(ApplicationHandler.java:347)
at org.glassfish.jersey.servlet.WebComponent.(WebComponent.java:392)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:177)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:369)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1238)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1041)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4996)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I had the exact same problem in Weblogic. It seems to be that the JacksonAutoDiscoverable and AutoDiscoverable came from different class loaders and therefore different versions. AutoDiscoverable exists in jersey-common and JacksonAutoDiscoverable exists in jersey-media-json-jackson.
I got around this by letting Weblogic have all the discoverable classes and instead specifying 'com.fasterxml.jackson.*' as prefer-application-packages/resources to have my own version of jackson.
I had this same problem, but I got a fix. There's an issue with conflicting dependencies. You've included the jersey-media-json-jackson dependency, but the Tomcat web container already provides those classes.
Just add the scope tag to your dependency:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.27</version>
<scope>provided</scope>
</dependency>
Refer to the link for more information: https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#
In my case I worked with Glassfish and I had the Glassfish descriptor (glassfish-web.xml) in the project as follow:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app error-url="">
<class-loader delegate="false"/>
<parameter-encoding default-charset="UTF-8"/>
<jsp-config>
<property name="keepgenerated" value="true">
<description>Keep a copy of the generated servlet class' java code.</description>
</property>
</jsp-config>
</glassfish-web-app>
The class-loader property was marked with the attribute
delegate=false
, I think that was my mistake, because as Glassfish Deployment Guide say, this attribute must be true when you are exposing services.
https://javaee.github.io/glassfish/doc/4.0/application-deployment-guide.pdf#G11.1006531
The solution that worked for me was remove that file and keep only the Standard Deployment Descriptor(web.xml).
Hope this help.
I had this same problem with JBOSS6 server. After adding jersey-media-moxy dependency to pom file, it was worked.
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.25.1</version>
</dependency>
I solved the issue by adding both jersey-common and jersey-media-json-jackson. Removed jersey-bean-validation.
<dependency>
<artifactId>jersey-common</artifactId>
<groupId>org.glassfish.jersey.core</groupId>
<version>2.29.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.29.1</version>
</dependency>
<!--<dependency>
<artifactId>jersey-bean-validation</artifactId>
<groupId>org.glassfish.jersey.ext</groupId>
<version>2.29.1</version>
</dependency>-->

Jersey MessageBodyWriter not found for media type=text/html

I am going to display html using "Thymeleaf", but the following errors are given.
The server using is tomcat8.
My code looks like.
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.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.abc.def</groupId>
<artifactId>jersey_de</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>jersey_de</name>
<build>
<finalName>jersey_de</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<inherited>true</inherited>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- my setting -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.21</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.21</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.connectors</groupId>
<artifactId>jersey-apache-connector</artifactId>
<version>2.21</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.21</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-mvc</artifactId>
<version>2.21</version>
</dependency>
<!--
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-mvc-jsp</artifactId>
<version>2.21</version>
</dependency>
-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
Jersey Web Application
org.glassfish.jersey.servlet.ServletContainer
jersey.config.server.provider.packages
com.abc.def.jersey_de
com.abc.def.jersey_de.ThymeleafViewProcessor
/WEB-INF/view/
1
Jersey Web Application
/webapi/*
javacode
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.glassfish.jersey.server.mvc.Viewable;
import com.abc.def.jersey_de.domain.TestPOJO;
#Path("top")
#Produces(MediaType.TEXT_PLAIN)
public class DemoCtrl {
#GET
#Produces(MediaType.TEXT_HTML)
public Viewable getIt() {
Viewable vb = new Viewable("test",new TestPOJO());
System.out.println("top end");
return vb;
}
}
ThymeleafViewProcessor
#Provider
public class ThymeleafViewProcessor implements TemplateProcessor<String> {
#Context
private HttpServletRequest request;
#Context
private HttpServletResponse response;
#Context
private ServletContext servletContext;
private final TemplateEngine templateEngine;
/**
* コンストラクタ
*/
public ThymeleafViewProcessor() {
TemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".html");
resolver.setTemplateMode("HTML5");
resolver.setCacheTTLMs(3600000L);
templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(resolver);
System.out.println("ThymeleafViewProcessor end");
}
/**
* 参照させるファイル名を解決する。
*/
#Override
public String resolve(String name, MediaType mediaType) {
return name;
}
#Override
public void writeTo(String templateReference, Viewable viewable, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream out) throws IOException {
WebContext context = new WebContext(request, response, servletContext);
//HTML内でモデルオブジェクトを使用できるようにしている。
//ここはモデル名をそのまま使用できるようにした方が良い。
context.setVariable("item", viewable.getModel());
Writer writer = new OutputStreamWriter(out);
templateEngine.process(templateReference, context, writer);
writer.flush();
}
}
ApplicationSetting
#ApplicationPath("/service")
public class ApplicationSetting extends ResourceConfig {
public ApplicationSetting() {
packages(this.getClass().getPackage().getName());
register(ThymeleafViewProcessor.class);
register(MvcFeature.class);
register(LoggingFilter.class);
System.out.println("ApplicationSetting ");
}
}
It was settled.
The points that I revised are as follows.
web.xml
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.abc.def.jersey_de.MyApplication</param-value>
</init-param>
pom
<dependencies>
<dependency>
<groupId>javax</groupId><!-- 動きが変わらないので不要? -->
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>8.0.15</version>
</dependency>
<dependency><!-- 不要? -->
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-mvc</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
</dependencies>
<properties>
<jersey.version>2.21</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>