HTTP 500 error when trying to produce JSON using REST - java

Trying to produce JSON code from database entries using rest but I am getting a HTTP 500 error code
#Path("product")
public class ProductResource {
#GET
#Produces({ MediaType.APPLICATION_XML })
public List<Product> getProductInformation() {
return ProductDAO.instance.getProductInformation();
}
}
^^ This is the class I have mapped to the resource I am trying to access
It then accesses the ProductDAO class which gets the info from the database and adds it to a HashMap (This part seems to work fine)
public enum ProductDAO {
instance;
private Map<Integer, Product> productMap = new HashMap<Integer, Product>();
private ProductDAO() {
loadFromDb();
}
public Map<Integer, Product> loadFromDb() {
productMap.clear();
try {
Connection conn = Utils.getConnection();
PreparedStatement psmt = conn.prepareStatement("SELECT * FROM products");
ResultSet rs = psmt.executeQuery();
while (rs.next()) {
Product p = new Product(rs.getInt("id"), rs.getString("description"), rs.getInt("CategoryId"),
rs.getDouble("price"), rs.getInt("QuantitySold"), rs.getString("image"));
productMap.put(productMap.size() + 1, p);
System.out.println(productMap);
}
} catch (Exception e) {
e.printStackTrace();
}
return productMap;
}
public List<Product> getProductInformation() {
List<Product> product = new ArrayList<Product>();
product.addAll(productMap.values());
return product;
}
I have 4 test entries in the database currently.
When I add a system.out.println() for the HashMap I get the following output to the console:
Database connection established
{1=myApp.Product#20c427e5}
{1=myApp.Product#20c427e5, 2=myApp.Product#610e026a}
{1=myApp.Product#20c427e5, 2=myApp.Product#610e026a, 3=myApp.Product#2e0456eb}
{1=myApp.Product#20c427e5, 2=myApp.Product#610e026a, 3=myApp.Product#2e0456eb, 4=myApp.Product#5241c547}`
My pom.xml is as follows:
<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.framesinmind</groupId>
<artifactId>FramesIM</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>FramesIM</name>
<build>
<finalName>FramesIM</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>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
<scope>compile</scope>
</dependency>
</dependencies>
<properties>
<jersey.version>2.16</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
Web.xml as follows:
<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" 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_2_5.xsd">
<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>myApp</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
The Java classes are all part of the 'myApp' package
When trying to access the url 'http://localhost:8080/FramesIM/rest/product' I get the HTTP 500 error. Any ideas?

The internal server error is because you need to code the Product class with the annotations and cannot directly pass the list as response. Please follow the code below.
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessType;
#XmlRootElement(name = "product")
#XmlAccessorType (XmlAccessType.FIELD)
public class Product {
String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "products")
#XmlAccessorType (XmlAccessType.FIELD)
public class Products
{
#XmlElement(name="product")
private List<Product> products;
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("product")
public class ProductResource {
#GET
#Produces(MediaType.APPLICATION_XML)
public Products getProductInformation() {
List<Product> product = ProductDAO.instance.getProductInformation();
Products products = new Products();
products.setProducts(product);
return products;
}
}
The response below is the sample output
<products>
<product>
<id>12</id>
</product>
</products>

Related

HTTP Status 500 – Internal Server Error MediaType.APPLICATION_XML in Maven Dependencies

Actually , I'm struggling with this issue from two days . I am not able to output in console and I do not know what the problem is?
I am hitting this URL on my local machine, http://localhost:8080/Last/webapi/employee/p2
Below is the Screenshot of my issue :
https://i.stack.imgur.com/vubwA.png
Code is as below.
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.webservices</groupId>
<artifactId>Last</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Last</name>
<build>
<finalName>Last</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>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<!-- Thanks for using https://jar-download.com -->
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-binding</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-jaxb -->
<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-bundle -->
<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-core -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.19.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-jaxb -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-jaxb</artifactId>
<version>2.31</version>
</dependency>
</dependencies>
<properties>
<jersey.version>2.31</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" 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_2_5.xsd">
<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.webservices.Last</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
</web-app>
EmployeesList.java
package com.webservices.Last;
import java.util.ArrayList;
import java.util.List;
import javax.print.attribute.standard.Media;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path(value = "employee")
public class EmployeesList {
List<StaffInformation> st = null;
public EmployeesList() {
st = new ArrayList<>();
st.add(new StaffInformation("Kerem", "Kağan","123"));
st.add(new StaffInformation("Java", "Oracle","321"));
}
#GET
#Produces(MediaType.APPLICATION_XML)
#Path("/p2")
public Response listXML()
{
List<StaffInformation> list = new ArrayList<StaffInformation>();
list.add(new StaffInformation("kerem", "ss", "123"));
GenericEntity<List<StaffInformation>> entity = new GenericEntity<List<StaffInformation>>(list) {};
Response response = Response.ok(entity).build();
return response;
}
}
StaffInformation.java
package com.webservices.Last;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class StaffInformation {
#XmlElement
private String name;
#XmlElement
private String surname;
#XmlElement
private String tcNo;
public String getTcNo() {
return tcNo;
}
public void setTcNo(String tcNo) {
this.tcNo = tcNo;
}
public StaffInformation() {
super();
}
public StaffInformation(String name, String surname, String tcNo) {
super();
this.name = name;
this.surname = surname;
this.tcNo = tcNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
you are hitting http://localhost:8080/Last/webapi/employee/p2 url
try with
http://localhost:8080/webapi/employee/p2
or
add '/last' in your web.xml, url pattern field
The path you are requesting is not found by the server, hence you are seeing the 500 internal server error.
You have mentioned as #Path(value = "employee") for your main path whereas that should be
#Path(value = "/employee")
and changing that to "/employee" should work fine. I tried your code in my local machine and it just worked fine after changing to "/employee".
This means the URL starts with /employee (after Application path) and remaining methods to follow this URL. Forex in your case http://localhost:8080/Last/webapi/employee/p2

Maven, Jersey, JSON, Tomcat, Error MessageBodyWriter not found for media type=application/json

I get this error when I try to see JSON response in my browser. I read a lot of posts on stack witch are similar but nothing work. Browser return "Error 500". Intellij IDEA return error "Error MessageBodyWriter not found for media type=application/json". Here is my code:
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>groupId</groupId>
<artifactId>app</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-entity-filtering</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<properties>
<jersey.version>2.23.2</jersey.version>
</properties>
</project>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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">
<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>app</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
MessageService:
package app.resource;
import app.model.Message;
import app.service.MessageService;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
#Path("messages")
public class MessageResource {
MessageService messageService = new MessageService();
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<Message> getMessages()
{
return messageService.getAllMessages();
}
#GET
#Path("/{messageId}")
#Produces(MediaType.APPLICATION_JSON)
public Message test(#PathParam("messageId") long id)
{
return messageService.getMessage(id);
}
}
Message class:
package app.model;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Date;
#XmlRootElement
public class Message {
private long id;
private String message;
private Date created;
private String author;
public Message()
{
}
public Message(long id, String message, String author) {
this.id = id;
this.message = message;
this.created = new Date();
this.author = author;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
Old post, but I figured it could help someone. I can across the same issue playing around with Apache Tomcat 9.0.36 and Jersey. This error is due to a missing media dependency. Here are my Jersey POM dependencies that worked for me:
<!-- Jersey dependencies -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.29.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.29.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>2.29.1</version>
</dependency>
<!-- Jersey media type files, including XML -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-jaxb</artifactId>
<version>2.29.1</version>
</dependency>
<!-- Jersey JSON entity providers -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.29.1</version>
</dependency>
You can read more about Jersey supported media types in their documentation.

Swagger2feature CXF xml configuration

I am trying to configure CXF nonSpring with Swagger to see the json documentation generated, but I can not see where the url that was generated from Swagger is.
Here is my code:
pom.xml
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-service-description-swagger</artifactId>
<version>3.1.11</version>
</dependency>
web.xml
<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<display-name>CXFServlet</display-name>
<servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value> com.bank.AdminApplication </param-value>
</init-param>
<init-param>
<param-name>jaxrs.application.address.ignore</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>jaxrs.features</param-name>
<param-value>
org.apache.cxf.jaxrs.swagger.Swagger2Feature
(basePath=/swagger/api​docs)
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
main interface with definitions and annotations:
#Path("/")
#Api(value="/swagger/apidocs")
public interface ApiClient {
#GET
#Path("endpoint/consult")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#ApiOperation(value = "Consult test Endpoint", response = Response.class)
public Response consultEndpoint() throws ServiceException;
}
I go to: http://localhost:8080/webapp/swagger/apidocs
but nothing appears
Any recommendation?
Well, finally I found how to integrate CXF non spring with swagger; here is the 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>coop.bancocredicoop.test</groupId>
<artifactId>test-api-cxfnonspring-swagger</artifactId>
<version>1.0.0</version>
<name>test-api-cxfnonspring-swagger</name>
<description>Servicios test api rest</description>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>swagger-ui</artifactId>
<version>3.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-service-description-swagger</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.9.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
web.xml
<?xml version="1.0"?><!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"><web-app><servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.AdminApplication</param-value>
</init-param>
<init-param>
<param-name>jaxrs.address</param-name>
<param-value>/</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping></web-app>
AdminAplication.java
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
import org.apache.cxf.jaxrs.swagger.Swagger2Feature;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
public class AdminApplication extends Application {
HashSet<Object> singletons = new HashSet<Object>();
public AdminApplication() {
singletons.add(new PersonService());
}
#Override
public Set<Class<?>> getClasses() {
HashSet<Class<?>> set = new HashSet<Class<?>>();
return set;
}
#Override
public Set<Object> getSingletons() {
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
mapper.setAnnotationIntrospectors(primary, secondary);
JacksonJsonProvider jaxbProvider = new JacksonJsonProvider();
jaxbProvider.setMapper(mapper);
singletons.add(jaxbProvider);
Swagger2Feature feature = new Swagger2Feature();
feature.setContact("Pablo Garcia");
feature.setDescription("api Description");
feature.setPrettyPrint(true);
feature.setTitle("api title");
singletons.add(feature);
return singletons;
}
}
PersonService.java
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("/people")
#Produces(MediaType.APPLICATION_JSON)
#Api(value = "/people")
public class PersonService {
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/person/{id}/")
#ApiOperation(
value = "api value",
notes = "api notes "
)
public Response getPerson(#PathParam("id") String personId) throws Exception {
PersonResponse p = new PersonResponse();
return Response.ok(p).build();
}
}
And finally, a simple POJO PersonResponse:
public class PersonResponse {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Application at context path can't start Tomcat 7 Ubuntu

I am trying to run a webapp called TestServer2 in the Tomcat 7 running Ubuntu 14.04 but it gave failed as FAIL - Application at context path /TestServer2-0.0.1-SNAPSHOT could not be started. I followed an example online here and I tested it on my local Tomcat server instance running with Eclipse and it works just fine but when I deployed it into the server Ubuntu 14.04 with Tomcat 7 it gave me that error. Below are the codes I used:
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_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>TestServer2</display-name>
<context-param>
<param-name>resteasy.resources</param-name>
<param-value>com.heyho.rest.JSONService</param-value>
</context-param>
<listener>
<listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
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>TestServer2</groupId>
<artifactId>TestServer2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<repositories>
<repository>
<id>JBoss repository</id>
<url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>2.2.1.GA</version>
</dependency>
<!-- <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jaxb-provider</artifactId>
<version>2.2.0.GA</version> </dependency> -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>2.2.1.GA</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
JSONService.java
package com.heyho.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
#Path("/service")
public class JSONService {
#POST
#Path("/post")
#Consumes("application/json")
public Response createProductInJSON(UserInput input) {
String result = "User input submitted : " + input;
return Response.status(201).entity(result).build();
}
}
UserInput.java
package com.heyho.rest;
public class UserInput {
int counter;
String attribute;
String publicKey;
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
#Override
public String toString() {
return "User Input = counter " + counter + " attribute = " + attribute + " public key = " + publicKey ;
}
}
ClientPost.java
package com.heyho.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import com.google.gson.Gson;
public class ClientPost {
public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
try {
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (certificate, authType) -> true).build();
CloseableHttpClient client = HttpClients.custom()
.setSslcontext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
HttpPost postRequest = new HttpPost(
"http://somewebsite.de:50064/TestServer2/service/post");
Gson gson = new Gson();
Map<String,Object> test = new HashMap<String,Object>();
test.put("counter", 1000);
test.put("attribute", "user attribute");
test.put("publicKey", "user public key");
String json = gson.toJson(test);
StringEntity input = new StringEntity(json);
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = client.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Is there something wrong with my code? Also how do I debug the Tomcat 7 running on the server so that it could give me some logs or error?
UPDATE
I have found the error in log something like this:
SEVERE: Exception sending context initialized event to listener instance of class org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
java.lang.UnsupportedClassVersionError: com/heyho/rest/JSONService : Unsupported major.minor version 52.0 (unable to load class com.heyho.rest.JSONService)
I'm not sure what is the problem here. I have declared JSONService on my web.xml but it still gives me error
"Unsupported major.minor version 52.0" means that the class com.heyho.rest.JSONService has been compiled for a newer version of Java as you try to run it with. Upgrade the JVM to 1.8 and it should work. Alternatively, you can make sure to compile the class for the version of the JVM.

No mapping found for HTTP request with URI with java based configuration [duplicate]

This question already has answers here:
Why does Spring MVC respond with a 404 and report "No mapping found for HTTP request with URI [...] in DispatcherServlet"?
(13 answers)
Closed 6 years ago.
While learning spring i was trying to run code examples of Spring in Action
but it is showing me the below mentioned error in tomcat logs:
11-Aug-2016 12:15:57.561 WARNING [http-nio-8080-exec-1] org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/RestTester-0.0.1-SNAPSHOT/] in DispatcherServlet with name 'dispatcher'
I am trying to configure spring by the help of java based configuration only.
Code for the same is mentioned below:
TestProjectInitializer.java
package test.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class TestProjectInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return new Class<?>[]{RootConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return new Class<?>[]{WebConfig.class};
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[]{"/"};
}
}
WebConfig.java
package test.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("test.webconf")
public class WebConfig extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver getViewResolver()
{
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".html");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
{
configurer.enable();
}
}
RootConfig.java
package test.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#ComponentScan(basePackages={"test"}, excludeFilters={#Filter(type=FilterType.ANNOTATION,value=EnableWebMvc.class)})
public class RootConfig {
}
HomeController.java
package test.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
/*#RequestMapping("/")*/
public class HomeController
{
#RequestMapping(value="/",method=RequestMethod.GET)
public String home()
{
return "home";
}
}
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>test</groupId>
<artifactId>RestTester</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.7</source>
<target>1.7</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>test</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>
</web-app>
Directory Structure
Please help me understanding what i am doing wrong.
The name of base package on Webmvc was wrong and should be test.controller.

Categories

Resources