I am getting a 404 error when I test my REST Spring WebService in Postman.
Can anyone suggest a solution??
My code :
src/main/resources/spring/application-config.xml
-------------------------------------------------------------------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="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">
<!-- Uncomment and add your base-package here:
<context:component-scan
base-package="org.springframework.samples.service"/> -->
</beans>
-------------------------------------------------------------------------------------------------------------------------------------------
src/main/resources/logback.xml
-------------------------------------------------------------------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!-- configuration file for LogBack (slf4J implementation)
See here for more details: http://gordondickens.com/wordpress/2013/03/27/sawing-through-the-java-loggers/ -->
<configuration scan="true" scanPeriod="30 seconds">
<contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
<resetJUL>true</resetJUL>
</contextListener>
<!-- To enable JMX Management -->
<jmxConfigurator/>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%-5level %logger{0} - %msg%n</pattern>
</encoder>
</appender>
<!--<logger name="org.hibernate" level="debug"/> -->
<!-- Uncomment and add your logger here:
<logger name="org.springframework.samples.service.service" level="debug"/> -->
<root level="info">
<appender-ref ref="console"/>
</root>
</configuration>
---------------------------------------------------------------------------------------------------------------------------------------------
src/main/webapp/WEB-INF/mvc-config.xml
---------------------------------------------------------------------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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">
<!-- Uncomment and your base-package here:
<context:component-scan
base-package="org.springframework.samples.web"/> -->
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
---------------------------------------------------------------------------------------------------------------------------------------------
src/main/webapp/WEB-INF/web.xml
---------------------------------------------------------------------------------------------------------------------------------------------
<?xml version="1.0" encoding="ISO-8859-1"?>
<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_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>ManageUserRoles</display-name>
<!--
- Location of the XML file that defines the root application context.
- Applied by ContextLoaderListener.
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/application-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
- Servlet that dispatches request to registered handlers (Controller implementations).
-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
//////////////////////////Controller///////////////////////////////
package com.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.model.Role;
#Controller
public class RoleController {
private static final Logger logger = LoggerFactory.getLogger(RoleController.class);
Map<String, Role> roleData = new HashMap<String, Role>();
#RequestMapping(value = "/role/{role_name}", method = RequestMethod.GET,headers="Accept=application/json")
public #ResponseBody Role findRole(#PathVariable("role_name") String role_name)
{
logger.info("Get a single role with name="+role_name);
return roleData.get(role_name);
}
#RequestMapping(value = "/roles", method = RequestMethod.GET)
public #ResponseBody List<Role> getAllRoles()
{
logger.info("Start getAllRoles.");
List<Role> list_roles = new ArrayList<Role>();
list_roles = createRoleList();
return list_roles;
}
public List<Role> createRoleList()
{
Role role1 = new Role("NP Sherm Test", "NP Test", "Active");
Role role2 = new Role("Sherm Employee Test", "Employee access test role", "Active");
Role role3 = new Role("Sherm Manager Test", "Manager test user role", "Active");
List<Role> list_roles = new ArrayList<Role>();
list_roles.add(role1);
list_roles.add(role2);
list_roles.add(role3);
return list_roles;
}
#RequestMapping(value="/roles/new/",method=RequestMethod.POST,headers="Accept=application/json")
public #ResponseBody Role addRole(#RequestBody Role role)
{
logger.info("Start Add Role");
Role roleGet = roleData.put(role.getRole_name(), role);
return roleGet;
}
#RequestMapping(value="/roles/new/",method=RequestMethod.PUT,headers="Accept=application/json")
public #ResponseBody Role editRole(#RequestBody Role role)
{
Role role_update = new Role();
role.setRole_name(role.getRole_name());
role.setRole_desc(role.getRole_desc());
role.setRole_status(role.getRole_status());
return role_update;
}
}
/////////////////////////////////////Model///////////////////////////////
package com.model;
public class Role {
private String role_name;
private String role_desc;
private String role_status;
public Role(){}
public Role(String role_name, String role_desc, String role_status) {
super();
this.role_name = role_name;
this.role_desc = role_desc;
this.role_status = role_status;
}
public String getRole_name() {
return role_name;
}
public void setRole_name(String role_name) {
this.role_name = role_name;
}
public String getRole_desc() {
return role_desc;
}
public void setRole_desc(String role_desc) {
this.role_desc = role_desc;
}
public String getRole_status() {
return role_status;
}
public void setRole_status(String role_status) {
this.role_status = role_status;
}
}
//////////////////////////////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>org.springframework.samples.service.service</groupId>
<artifactId>ManageUserRoles</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!-- Generic properties -->
<java.version>1.6</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Web -->
<jsp.version>2.2</jsp.version>
<jstl.version>1.2</jstl.version>
<servlet.version>2.5</servlet.version>
<!-- Spring -->
<spring-framework.version>3.2.3.RELEASE</spring-framework.version>
<!-- Hibernate / JPA -->
<hibernate.version>4.2.1.Final</hibernate.version>
<!-- Logging -->
<logback.version>1.0.13</logback.version>
<slf4j.version>1.7.5</slf4j.version>
<!-- Test -->
<junit.version>4.11</junit.version>
</properties>
<dependencies>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Other Web dependencies -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<!-- Spring and Transactions -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Test Artifacts -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
As you don't have any specific application context, the problem is with the current URL mapping i.e., the URI ManageUserRoles did not map to the controller, so change the code as below:
#Controller("ManageUserRoles")
public class RoleController {
// Add all you existing handler methods
}
After your UPDATE 1:
Also, your componentscan is not correct in mvc-config.xml because of which controller can't be detected:
base-package="org.springframework.samples.web" change it to base-package="com.controller"
Related
I'm creating a REST Service with Apache Camel and CXF-RS, using the following tutorial: https://www.javainuse.com/camel/apache_camel_rest_cxfrs
I've set up the code as shown in the tutorial and followed the steps correctly. After building the Maven project, I have successfully been able to install the bundle on Apache Karaf, using the SNAPSHOT file created. (A new Bundle ID was created).
When I run the command to 'start' the newly created bundle, it seemingly works with no errors being shown. However, when I access http://localhost:8181/cxf as mentioned towards the end of the tutorial, it says 'No services have been found':
Can you please advise me on what could be causing this problem?
Thank you.
My Project Structure:
My Code:
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fuseproject</groupId>
<artifactId>camel-cxfrs-core</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>bundle</packaging>
<repositories>
<repository>
<id>Central2</id>
<name>Central2</name>
<url>https://repo.maven.org/maven2</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-cxf</artifactId>
<version>2.12.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<version>2.4.0</version>
</plugin>
</plugins>
</build>
</project>
CamelProcessor.java:
package com.fuseproject.beans;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
public class CamelProcessor implements Processor {
public void process(Exchange exchange) throws Exception {
// Get input from exchange
String msg = exchange.getIn().getBody(String.class);
// set output in exchange
exchange.getOut().setBody("Hello World " + msg);
}
}
EmployeeServiceResource.java:
package com.fuseproject.beans;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
#Path("/")
public class EmployeeServiceResource {
public EmployeeServiceResource() {
}
#GET
#Path("/employees/{name}/")
public String getCustomer(#PathParam("name") String name) {
return null;
}
}
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://camel.apache.org/schema/cxf"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/cxf http://camel.apache.org/schema/cxf/camel-cxf.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<cxf:rsServer id="restService" address="http://localhost:9000/employeeservice"
serviceClass="com.fuseproject.beans.EmployeeServiceResource">
</cxf:rsServer>
<bean id="processor" class="com.fuseproject.beans.CamelProcessor" />
<camelContext id="camelId" xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="cxfrs://bean://restService" />
<process ref="processor" />
</route>
</camelContext>
</beans>
Problem
I have a simple rest application with low complexity built using jersey 2. I use maven for dependency management. I was getting cors issue with post request(JSON) from angular app. It was working fine with other content type except for json payloads. requests with json data was working fine in postman. Then I created a CORSFilter. Now the error is changed and everything is stopped working.
I need
to find whether my project setup is correct or not
to find what the blunder I have done
send post request from angular app with json data and get response
Project deployment assembly
https://imgur.com/a/TolLvEJ
Project facets
https://imgur.com/a/Eqga93Z
My project structure
https://imgur.com/a/VZMP5Vu
I have followed so many suggestions and workarounds. Maybe I was wrongly following them.
My 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>OnlineOrganicMarket</groupId>
<artifactId>OnlineOrganicMarket</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.1</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<jersey2.version>2.27</jersey2.version>
<jaxrs.version>2.1</jaxrs.version>
</properties>
<dependencies>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>6.2.1</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<!-- JAX-RS -->
<dependency> <groupId>javax.ws.rs</groupId> <artifactId>javax.ws.rs-api</artifactId>
<version>${jaxrs.version}</version> </dependency>
<!-- Jersey 2.19 -->
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey2.version}</version>
</dependency>
<!-- <dependency> <groupId>org.glassfish.jersey.core</groupId> <artifactId>jersey-server</artifactId>
<version>${jersey2.version}</version> </dependency> <dependency> <groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId> <version>${jersey2.version}</version>
</dependency> -->
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey2.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>2.26-b03</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.27</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.27</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-json-org</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
</dependencies>
</project>
My web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>OnlineOrganicMarket</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.oom.services</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<!-- <servlet>
<description>JAX-RS Tools Generated - Do not modify</description>
<servlet-name>JAX-RS Servlet</servlet-name>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JAX-RS Servlet</servlet-name>
<url-pattern>/jaxrs/*</url-pattern>
</servlet-mapping> -->
</web-app>
CORS filter
package com.oom.services.filter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Priority;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import org.glassfish.jersey.server.ExtendedUriInfo;
#Provider
#Priority(Priorities.HEADER_DECORATOR)
public class CORSFilter implements ContainerRequestFilter, ContainerResponseFilter {
private static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
private static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
private static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
private static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
private static final String ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers";
private static final String AUTHORIZATION = "authorization";
private static final String ORIGIN = "Origin";
private static String extractAllowedMethods(final ExtendedUriInfo extendedUriInfo) {
final Optional<Class<?>> optional = extendedUriInfo.getMatchedRuntimeResources().stream()
.flatMap(r -> r.getResources().stream()).flatMap(r -> r.getHandlerClasses().stream())
.filter(r -> r.getPackage().getName().startsWith("com.oom.services")).findFirst();
if (optional.isPresent()) {
return Arrays.stream(optional.get().getDeclaredMethods())//
.flatMap(m -> Arrays.stream(m.getAnnotations()))//
.map(a -> a.annotationType().getAnnotation(javax.ws.rs.HttpMethod.class))//
.filter(Objects::nonNull)//
.map(HttpMethod::value)//
.distinct()//
.collect(Collectors.joining(", "));
}
// Returning OPTIONS is a bit shady, as ACAM is about *real*, actual methods only.
return "OPTIONS";
}
#Context
private HttpServletRequest request;
#Context
private ExtendedUriInfo extendedUriInfo;
#Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
final String origin = requestContext.getHeaderString(ORIGIN);
if (origin != null && "OPTIONS".equals(requestContext.getMethod())) {
request.setAttribute(this.getClass().getName(), true);
requestContext.abortWith(Response.ok("CORS OK, carry on.", MediaType.TEXT_PLAIN_TYPE).build());
}
}
/**
* #see https://www.w3.org/TR/cors/
* #see https://jmchung.github.io/blog/2013/08/11/cross-domain-on-jersey-restful-web-services/
* #see https://solutionsisee.wordpress.com/2016/06/30/adding-cors-support-in-jersey-server/
*/
#Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext)
throws IOException {
final MultivaluedMap<String, Object> responseHeaders = responseContext.getHeaders();
final String origin = requestContext.getHeaderString(ORIGIN);
if (origin != null) {
// The presence of the Origin header marks a CORS request.
responseHeaders.add(ACCESS_CONTROL_ALLOW_ORIGIN, origin);
responseHeaders.add(ACCESS_CONTROL_ALLOW_METHODS, extractAllowedMethods(extendedUriInfo));
responseHeaders.add(ACCESS_CONTROL_ALLOW_HEADERS, AUTHORIZATION + ", X-Requested-With, Content-Type");
if (requestContext.getHeaderString(ACCESS_CONTROL_REQUEST_HEADERS) != null) {
responseHeaders.add(ACCESS_CONTROL_ALLOW_CREDENTIALS, requestContext
.getHeaderString(ACCESS_CONTROL_REQUEST_HEADERS).toLowerCase().contains(AUTHORIZATION));
}
}
if (request.getAttribute(this.getClass().getName()) != null) {
// We are in a CORS Preflight answer, fast tracked. The entity (== response body) is not
// relevant.
}
}
}
Currently getting this error
<!doctype html><html lang="en"><head><title>HTTP Status 500 – Internal Server Error</title><style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 500 – Internal Server Error</h1><hr class="line" /><p><b>Type</b> Exception Report</p><p><b>Message</b> org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/filter/TokenFilter</p><p><b>Description</b> The server encountered an unexpected condition that prevented it from fulfilling the request.</p><p><b>Exception</b></p><pre>javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/filter/TokenFilter
org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:432)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:370)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:389)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:342)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:229)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
</pre><p><b>Root Cause</b></p><pre>org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/filter/TokenFilter
org.glassfish.jersey.servlet.internal.ResponseWriter.rethrow(ResponseWriter.java:278)
org.glassfish.jersey.servlet.internal.ResponseWriter.failure(ResponseWriter.java:260)
org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:460)
org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:285)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:272)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:268)
org.glassfish.jersey.internal.Errors.process(Errors.java:316)
org.glassfish.jersey.internal.Errors.process(Errors.java:298)
org.glassfish.jersey.internal.Errors.process(Errors.java:268)
org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:289)
org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:256)
org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:703)
org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:416)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:370)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:389)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:342)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:229)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
</pre><p><b>Root Cause</b></p><pre>java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/filter/TokenFilter
com.fasterxml.jackson.databind.ObjectMapper._newReader(ObjectMapper.java:640)
com.fasterxml.jackson.databind.ObjectMapper.reader(ObjectMapper.java:3323)
org.glassfish.jersey.jackson.internal.jackson.jaxrs.base.ProviderBase._configForReading(ProviderBase.java:489)
org.glassfish.jersey.jackson.internal.jackson.jaxrs.base.ProviderBase._endpointForReading(ProviderBase.java:882)
org.glassfish.jersey.jackson.internal.jackson.jaxrs.base.ProviderBase.readFrom(ProviderBase.java:789)
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:257)
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:236)
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:156)
org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundReadFrom(MappableExceptionWrapperInterceptor.java:73)
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:156)
org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1091)
org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:874)
org.glassfish.jersey.server.ContainerRequest.readEntity(ContainerRequest.java:271)
org.glassfish.jersey.server.internal.inject.EntityParamValueParamProvider$EntityValueSupplier.apply(EntityParamValueParamProvider.java:97)
org.glassfish.jersey.server.internal.inject.EntityParamValueParamProvider$EntityValueSupplier.apply(EntityParamValueParamProvider.java:80)
org.glassfish.jersey.server.spi.internal.ParamValueFactoryWithSource.apply(ParamValueFactoryWithSource.java:74)
org.glassfish.jersey.server.spi.internal.ParameterValueHelper.getParameterValues(ParameterValueHelper.java:92)
org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$AbstractMethodParamInvoker.getParamValues(JavaResourceMethodDispatcherProvider.java:133)
org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:200)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:103)
org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:493)
org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:415)
org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:104)
org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:277)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:272)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:268)
org.glassfish.jersey.internal.Errors.process(Errors.java:316)
org.glassfish.jersey.internal.Errors.process(Errors.java:298)
org.glassfish.jersey.internal.Errors.process(Errors.java:268)
org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:289)
org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:256)
org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:703)
org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:416)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:370)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:389)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:342)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:229)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
</pre><p><b>Root Cause</b></p><pre>java.lang.ClassNotFoundException: com.fasterxml.jackson.core.filter.TokenFilter
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1363)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1186)
com.fasterxml.jackson.databind.ObjectMapper._newReader(ObjectMapper.java:640)
com.fasterxml.jackson.databind.ObjectMapper.reader(ObjectMapper.java:3323)
org.glassfish.jersey.jackson.internal.jackson.jaxrs.base.ProviderBase._configForReading(ProviderBase.java:489)
org.glassfish.jersey.jackson.internal.jackson.jaxrs.base.ProviderBase._endpointForReading(ProviderBase.java:882)
org.glassfish.jersey.jackson.internal.jackson.jaxrs.base.ProviderBase.readFrom(ProviderBase.java:789)
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:257)
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:236)
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:156)
org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundReadFrom(MappableExceptionWrapperInterceptor.java:73)
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:156)
org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1091)
org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:874)
org.glassfish.jersey.server.ContainerRequest.readEntity(ContainerRequest.java:271)
org.glassfish.jersey.server.internal.inject.EntityParamValueParamProvider$EntityValueSupplier.apply(EntityParamValueParamProvider.java:97)
org.glassfish.jersey.server.internal.inject.EntityParamValueParamProvider$EntityValueSupplier.apply(EntityParamValueParamProvider.java:80)
org.glassfish.jersey.server.spi.internal.ParamValueFactoryWithSource.apply(ParamValueFactoryWithSource.java:74)
org.glassfish.jersey.server.spi.internal.ParameterValueHelper.getParameterValues(ParameterValueHelper.java:92)
org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$AbstractMethodParamInvoker.getParamValues(JavaResourceMethodDispatcherProvider.java:133)
org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:200)
org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:103)
org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:493)
org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:415)
org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:104)
org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:277)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:272)
org.glassfish.jersey.internal.Errors$1.call(Errors.java:268)
org.glassfish.jersey.internal.Errors.process(Errors.java:316)
org.glassfish.jersey.internal.Errors.process(Errors.java:298)
org.glassfish.jersey.internal.Errors.process(Errors.java:268)
org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:289)
org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:256)
org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:703)
org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:416)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:370)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:389)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:342)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:229)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
</pre><p><b>Note</b> The full stack trace of the root cause is available in the server logs.</p><hr class="line" /><h3>Apache Tomcat/9.0.20</h3></body></html>
I am new to FUSE. I am trying to start a simple REST service.
I am using Jboss Fuse 6.3.
The bundle installs but i cannot start it without the error.
After installing the bundle, it appears as "Active", but with the tag "Failure".
The log prints the following error:
12:29:17,046 | ERROR | Thread-53 | BlueprintContainerImpl | 23 - org.apache.aries.blueprint.core - 1.4.5 | Unable to start blueprint container for bundle null/0.0.0
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)[:1.8.0_151]
at java.util.ArrayList.get(Unknown Source)[:1.8.0_151]
at org.apache.aries.blueprint.container.BlueprintContainerImpl.readDirectives(BlueprintContainerImpl.java:214)
at org.apache.aries.blueprint.container.BlueprintContainerImpl.doRun(BlueprintContainerImpl.java:296)
at org.apache.aries.blueprint.container.BlueprintContainerImpl.run(BlueprintContainerImpl.java:270)
at org.apache.aries.blueprint.container.BlueprintExtender.createContainer(BlueprintExtender.java:294)
at org.apache.aries.blueprint.container.BlueprintExtender.createContainer(BlueprintExtender.java:263)
This is my code:
Picture of project structure
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>org.fusesource.example</groupId>
<artifactId>rest-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>rest-service</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.servicemix.specs</groupId>
<artifactId>org.apache.servicemix.specs.jsr311-api-1.1.1</artifactId>
<version>1.9.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.servicemix</groupId>
<artifactId>servicemix-http</artifactId>
<version>2013.01</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
</dependencies>
<build>
<defaultGoal>install</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>2.3.6</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Import-Package>* </Import-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>
Blueprint.xml:
<?xml version = "1.0" encoding = "UTF-8"?>
<blueprint xmlns = "http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs = "http://cxf.apache.org/blueprint/jaxrs"
xmlns:cxf="http://cxf.apache.org/blueprint/core"
xsi:schemaLocation = "http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
http://cxf.apache.org/blueprint/jaxrs http://cxf.apache.org/schemas/blueprint/jaxrs.xsd
http://cxf.apache.org/blueprint/core http://cxf.apache.org/schemas/blueprint/core.xsd">
<jaxrs:server id="servicios" address="/serviciosPrueba">
<jaxrs:serviceBeans>
<ref component-id="miServicio" />
</jaxrs:serviceBeans>
</jaxrs:server>
<bean id="miServicio" class="com.rest.Servicio" />
</blueprint>
Java:
package com.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/servicioPrueba")
public class Servicio {
#GET
#Path("/getData")
#Produces(MediaType.APPLICATION_JSON)
public String getUser() {
String reponse = "This is standard response from REST";
return reponse;
}
}
Thank you very much.
In pom.xml
Please change
<packaging>jar</packaging>
to
<packaging>bundle</packaging>
otherwise it will miss the necessary OSGi headers
I resolved the second error adding specific versions of dependencies in pom.xml:
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Import-Package>
javax.ws.rs;version="[2.0,3)",
javax.ws.rs.core;version="[2.0,3)",
*
</Import-Package>
</instructions>
</configuration>
I am using Spring MVC 4.1.5 with its REST support trying to get a web service working with google protocol buffers message format. I have seen a lot of posts that are mentioning this issue with JSON format but none with google protocol buffers format.
Also I don't see Spring framework docs have a MediaType for protobufs (more on that below) My code is posted here on github
Here's my controller code (using or not using produces="application-xprotobuf" makes no difference - same 406 not acceptable error)
#RestController
#RequestMapping("/ws")
#EnableWebMvc
public class CustomerRestController {
#Autowired
private CustomerRepository customerRepository;
//#RequestMapping(value="/customers/{id}", method = RequestMethod.GET, produces="application/x-protobuf")
#RequestMapping(value="/customers/{id}", method = RequestMethod.GET)
public CustomerProtos.Customer customer(#PathVariable Integer id) {
return this.customerRepository.findById(id);
}
#Bean
ProtobufHttpMessageConverter protobufHttpMessageConverter() {
return new ProtobufHttpMessageConverter();
}
private CustomerProtos.Customer customer(int id, String f, String l, Collection<String> emails) {
String emailAddressString = "defaultEmail#address.com";
for (String email : emails) {
emailAddressString = email;
break;
}
EmailAddress emailAddress = CustomerProtos.Customer.EmailAddress.newBuilder()
.setType(CustomerProtos.Customer.EmailType.PROFESSIONAL).setEmail(emailAddressString).build();
return CustomerProtos.Customer.newBuilder().setFirstName(f).setLastName(l).setId(id).addEmail(emailAddress)
// .addAllEmail(emailAddresses)
.build();
}
#Bean
CustomerRepository customerRepository() {
return new CustomerRepositoryImpl();
}
}
here's my 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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>demo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/rest-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
Here's my pom.xml, please note that i do have google protobuf libaries added here and they do end up in WEB-INF/lib folder of the deployed .war file.
<?xml version="1.0" encoding="UTF-8"?>
<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>org.test</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<start-class>demo.DemoApplication</start-class>
<java.version>1.8</java.version>
<jackson.version>2.5.3</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.googlecode.protobuf-java-format</groupId>
<artifactId>protobuf-java-format</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</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-legacy</artifactId>
<version>1.0.0.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Here's my test client
package demo;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.RestTemplate;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration
public class DemoApplicationTests {
#Configuration
public static class RestClientConfiguration {
#Bean
RestTemplate restTemplate(ProtobufHttpMessageConverter hmc) {
return new RestTemplate(Arrays.asList(hmc));
}
#Bean
ProtobufHttpMessageConverter protobufHttpMessageConverter() {
return new ProtobufHttpMessageConverter();
}
}
#Autowired
private RestTemplate restTemplate;
#Test
public void contextLoaded() {
ResponseEntity<CustomerProtos.Customer> customer = restTemplate.getForEntity(
"http://localhost:7001/demo-0.0.1-SNAPSHOT/ws/customers/2", CustomerProtos.Customer.class);
System.out.println("customer retrieved: " + customer.toString());
}
}
When I run the client from command line using mvn test
I get the following error
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.697 sec <<< FAILURE! - in demo.DemoApplicationTests
contextLoaded(demo.DemoApplicationTests) Time elapsed: 0.037 sec <<< ERROR!
org.springframework.web.client.HttpClientErrorException: 406 Not Acceptable
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:641)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557)
at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:289)
at demo.DemoApplicationTests.contextLoaded(DemoApplicationTests.java:42)
I saw people suggesting using a contentNegotiationManager
In my rest-servlet.xml I have mvc:annotation-driven tag
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="demo" />
<mvc:annotation-driven />
</beans>
Also I have dropped in a webConfig.java in demo package
package demo;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
/**
* Total customization - see below for explanation.
*/
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false).
favorParameter(true).
parameterName("mediaType").
ignoreAcceptHeader(true).
useJaf(false).
defaultContentType(MediaType.TEXT_PLAIN).
mediaType("xml", MediaType.APPLICATION_XML).
mediaType("json", MediaType.APPLICATION_JSON).
mediaType("x-protobuf", MediaType.ALL)
;
}
}
I get the 406 not acceptable error with and without the webconfig.java (which is doing the work of contentNegotationManager).
I haven't been able to find a MediaType.APPLICATION_XPROTOBUF in Spring 4.1.3 or even 4.2.3 jars .
So I have left that value to MediaType.ALL ( I think that should work ?)
When I run the test client I get this message before actually running the test..
09:27:26.198 [main] DEBUG o.s.web.client.RestTemplate - Created GET request for "http://localhost:7001/demo-0.0.1-SNAPSHOT/ws/customers/2"
09:27:26.199 [main] DEBUG o.s.web.client.RestTemplate - Setting request Accept header to [application/x-protobuf, text/plain, application/xml, application/json]
09:27:26.245 [main] DEBUG o.s.web.client.RestTemplate - GET request for "http://localhost:7001/demo-0.0.1-SNAPSHOT/ws/customers/2" resulted in 406 (Not Acceptable); invoking error
handler
It clearly shows its setting the accept headers to include "application-xprotobuf" value as well.
Not sure what I am missing in this case.
I had the same issue with the controller failing with 406: Not Acceptable. After a lot of tracing I figured out the statement in the example:
Spring Boot automatically registers HttpMessageConverter beans so we need only define the ProtobufHttpMessageConverter bean and it gets configured appropriately.
is to be understood literally, since without Spring Boot no converter registration happens. The bean is instantiated, but it's never registered in the list of HttpMessageConverters.
I've solved it by explicitly registering a ProtobufHttpMessageConverter instance:
#Configuration
#EnableWebMvc
#ComponentScan
public class AppConfig extends WebMvcConfigurerAdapter {
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new ProtobufHttpMessageConverter());
super.configureMessageConverters(converters);
}
}
You don't need to declare a separate bean for it (unless you plan to call it explicitly).
Also note that overriding configureMessageConverters() disables all standard converters; if you mean to extend the list of stock converters rather than replace it, override extendMessageConverters() instead.
One of my partners needs a SOAP interface and so I thought: lets move to an Application server. I chose Glassfish and it works great out of the box. There is just one thing I can not make it do: inject a #SessionScoped ManagedBean into the #Webservice annotated EJB.
The only way I can acces the EJB is over JNDI. I read about it here
My question is: is there a bug in Glassfish and it will work in a future version or should it work and I did something wrong.
I would like to be able to inject the property DataAccess session with the #EJB annotation but it does not work.
Below are all the files in the test project
Here is my WebService class:
#LocalBean
#Stateless
#WebService()
public class MySOAP implements Serializable {
private DataAccess session;
#WebMethod
public String getUsername() {
javax.naming.Context ctx = null;
try {
ctx = new javax.naming.InitialContext();
session = ( DataAccess ) ctx.lookup( "java:comp/env/DataAccess" );
return "user is " + session.getData();
} catch ( NamingException e ) {
e.printStackTrace();
}
return "exception occured";
}
}
The EJB I would like to inject:
public abstract class AbstractDataBean {
#Inject /* this just returns some text*/
private MySessionBean session;
public MySessionBean getSession() {
return session;
}
}
#LocalBean
#Stateless
public class DataAccess extends AbstractDataBean implements Serializable {
public String getData() {
return " data " + getSession();
}
#Override
public String toString() {
return getData();
}
}
#Named
#SessionScoped
public class MySessionBean implements Serializable {
static private int classCounter = 0;
private String user;
#PostConstruct
public void initMySessionBean( ) {
user = "Micha " + (++classCounter) ; //to check how many times it was called
}
public String getUser() {
return user;
}
public void setUser( String user ) {
this.user = user;
}
#Override
public String toString() {
return user;
}
}
I have a web.xml to define the JNDI:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<session-config>
<session-timeout>1</session-timeout>
</session-config>
<ejb-local-ref>
<ejb-ref-name>DataAccess</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<local>ch.sertal.server.services.ejb.DataAccess</local>
</ejb-local-ref>
</web-app>
a sun-jaxws.xml to define the SOAP WebService:
<?xml version="1.0" encoding="UTF-8"?>
<endpoints xmlns='http://java.sun.com/xml/ns/jax-ws/ri/runtime' version='2.0'>
<endpoint
name='Mysoap'
implementation='ch.sertal.server.services.MySOAP'
url-pattern='/soap/Mysoap '/>
</endpoints>
and an empty beans.xml in order to have CDI functioning:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>
and finally the pom.xml It is very long because I copied it from the existing project. But there should be nothing missing.
<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>ch.sertal</groupId>
<artifactId>VisionWeb</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>VisionWeb Jersey Webapp</name>
<build>
<finalName>VisionWeb</finalName>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
<targetPath>META-INF</targetPath>
<includes>
<include>*.xml</include>
</includes>
</resource>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
<targetPath>.</targetPath>
<includes>
<include>*.properties</include>
</includes>
</resource>
<resource>
<filtering>true</filtering>
<directory>src/main/resources/i18n</directory>
<targetPath>.</targetPath>
<includes>
<include>*.properties</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<inherited>true</inherited>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.glassfish.maven.plugin</groupId>
<artifactId>maven-glassfish-plugin</artifactId>
<version>2.1</version>
<configuration>
<glassfishDirectory>/Development/glassfish3</glassfishDirectory>
<user>admin</user>
<adminPassword>U36c9AqVf5Ppk4DX</adminPassword>
<autoCreate>true</autoCreate>
<debug>true</debug>
<echo>false</echo>
<terse>true</terse>
<skip>false</skip>
<domain>
<host>${glassfish.host}</host>>
<name>domain1</name>
<adminPort>4848</adminPort>
<httpPort>9080</httpPort>
<httpsPort>8181</httpsPort>
<iiopPort>3700</iiopPort>
<jmsPort>7676</jmsPort>
</domain>
<components>
<component>
<name>VisionWeb</name>
<artifact>${project.build.directory}/${project.build.finalName}.war</artifact>
</component>
</components>
</configuration>
</plugin>
<!--surefire-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<parallel>test</parallel>
<threadCount>1</threadCount>
<groups>${test.groups}</groups>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-api</artifactId>
<version>1.1.Final</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
</dependency>
<!--jersey for RESTful services-->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>${jersey-version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>${jersey-version}</version>
</dependency>
<!--GlassFish libraries-->
<dependency>
<groupId>org.glassfish.distributions</groupId>
<artifactId>web-all</artifactId>
<version>10.0-build-20080430</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.embedded</groupId>
<artifactId>gf-embedded-api</artifactId>
<version>1.0-alpha-4</version>
<scope>test</scope>
</dependency>
<!--peristence & database-->
<!-- hsqldb -->
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.2.6</version>
</dependency>
<!-- persistence -->
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>${eclipselink.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>${eclipselink.jpa.version}</version>
<scope>compile</scope>
</dependency>
<!--SHIRO Authentication-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.1.0</version>
</dependency>
<!--POI components-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.7</version>
</dependency>
<!--PDF Box-->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>1.6.0</version>
</dependency>
<!--XML processing-->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<!--testing-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.0.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<!--properties-->
<properties>
<jersey-version>1.8</jersey-version>
<jpa.unit>hsqldb.server</jpa.unit>
<test.jpa.unit>hsqldb.testr</test.jpa.unit>
<eclipselink.version>2.3.0</eclipselink.version>
<eclipselink.jpa.version>2.0.3</eclipselink.jpa.version>
</properties>
<!--profiles-->
<profiles>
<profile>
<id>mode.alpha.dev</id>
<activation>
<activeByDefault>false</activeByDefault>
<property>
<name>environment</name>
<value>server</value>
</property>
</activation>
<properties>
<delete.files>true</delete.files>
<log.level>FINER</log.level>
<jersey.log.level>WARNING</jersey.log.level>
<jpa.log.level>INFO</jpa.log.level>
<test.groups>server-tests</test.groups>
<db.server.name>localhost</db.server.name>
<img-basedir>/opt/sertal/data</img-basedir>
<!--the url for tomcat 7 has changed. this is why /html has been appended to the below URL-->
<tomcat.manager>http://dev.sertal.net:7070/manager/html</tomcat.manager>
<tomcat.username>sertaladmin</tomcat.username>
<tomcat.password>29VeK0Ul</tomcat.password>
<tomcat.context>/VisionWeb</tomcat.context>
<test.groups>none</test.groups>
<!-- the date at the end marks the version of the data model -->
<hsqldb.data.path>/opt/sertal/data/hsqldb-dev-20110813</hsqldb.data.path>
</properties>
</profile>
</profiles>
<!--repositories and plugin repos-->
<repositories>
<!--glass fish-->
<repository>
<id>glassfish.java.net</id>
<name>GlassFish Maven Repository</name>
<url>http://download.java.net/maven/glassfish</url>
<layout>default</layout>
</repository>
<repository>
<id>m2.java.net</id>
<name>Java.net Maven 2 Repository</name>
<url>http://download.java.net/maven/2</url>
<layout>default</layout>
</repository>
<!--eclipse link-->
<repository>
<id>eclipselink.repo</id>
<name>eclipselink maven repository</name>
<url>http://download.eclipse.org/rt/eclipselink/maven.repo</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>m2.java.net</id>
<name>Java.net Maven 2 Repository</name>
<url>http://download.java.net/maven/2</url>
<layout>default</layout>
</pluginRepository>
<pluginRepository>
<id>jboss-public-repository-group</id>
<name>JBoss Public Maven Repository Group</name>
<url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url>
<layout>default</layout>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
Spare yourself the advice, I will not switch to JBoss :-)
The Session Scope isn't active for web derives per section 6.7.2 of JSR 299, it's not a bug. If you think about it, there isn't much point as the session doesn't really follow from one web service request to the next.
Also, you said you won't switch to JBoss, out of curiosity, what are your reasons?