Implementing basic REST API - ServletException - java

I'm trying to run a sample basic REST API on Eclipse but have been getting ServletException.
Here is the code:
Employee.java
package net.javabeat.articles.spring.rest.simple;
public class Employee {
private String id;
private String name;
private String department;
public Employee(){}
public Employee(String id, String name, String department){
this.id = id;
this.name = name;
this.department = department;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String toString(){
StringBuilder result = new StringBuilder();
result.append("[employee]");
result.append("[id]" + id + "[id]");
result.append("[name]" + name + "[name]");
result.append("[department]" + department + "[department]");
result.append("[employee]");
return result.toString();
}
public String toXmlString(){
StringBuilder result = new StringBuilder();
result.append("<employee>");
result.append("<id>" + id + "</id>");
result.append("<name>" + name + "</name>");
result.append("<department>" + department + "</department>");
result.append("</employee>");
return result.toString();
}
}
EmployeeManager.java
package net.javabeat.articles.spring.rest.simple;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("employee-manager")
public class EmployeeManager {
private static Set<Employee> employees;
#GET
#Produces(MediaType.TEXT_XML)
#Path("employeelist")
public String getEmployeesInXmlFormat(){
StringBuilder xmlResult = new StringBuilder();
xmlResult.append("<employees>");
Iterator<Employee> iterator = employees.iterator();
while (iterator.hasNext()){
Employee employee = iterator.next();
String employeeAsXml = employee.toXmlString();
xmlResult.append(employeeAsXml);
}
xmlResult.append("</employees>");
return xmlResult.toString();
}
#GET
#Produces(MediaType.TEXT_PLAIN)
#Path("employeelist")
public String getEmployeesInPlainFormat(){
StringBuilder plainResult = new StringBuilder();
plainResult.append("[employees]");
Iterator<Employee> iterator = employees.iterator();
while (iterator.hasNext()){
Employee employee = iterator.next();
String employeeAsXml = employee.toXmlString();
plainResult.append(employeeAsXml);
}
plainResult.append("[employees]");
return plainResult.toString();
}
static{
employees = new HashSet<Employee>();
employees.add(new Employee("1", "David", "IT"));
employees.add(new Employee("2", "John", "SALES"));
}
}
EMClient.java
package net.javabeat.articles.spring.rest.simple;
import java.net.URI;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
public class EMClient {
public static void main(String[] args) throws Exception{
ClientConfig clientConfig = new DefaultClientConfig();
Client clientObject = Client.create(clientConfig);
String uriPath = "http://localhost:8080/REST-Simple/rest-simple";
URI uriObject = UriBuilder.fromUri(uriPath).build();
WebResource employeeResource = clientObject.resource(uriObject);
xmlFormatTest(employeeResource);
plainFormatTest(employeeResource);
}
private static void xmlFormatTest(WebResource employeeResource){
WebResource innerResource = employeeResource.path("employee-manager").path("employeelist");
WebResource.Builder builderObject = innerResource.accept(MediaType.TEXT_XML);
String employeesAsXml = builderObject.get(String.class);
System.out.println(employeesAsXml);
}
private static void plainFormatTest(WebResource employeeResource){
WebResource innerResource = employeeResource.path("employee-manager").path("employeelist");
WebResource.Builder builderObject = innerResource.accept(MediaType.TEXT_PLAIN);
String employeesAsPlainText = builderObject.get(String.class);
System.out.println(employeesAsPlainText);
}
}
The deployment descriptor 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>REST-EmployeeManager</display-name>
<servlet>
<servlet-name>REST-Simple</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>net.javabeat.articles.spring.rest.simple</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>REST-Simple</servlet-name>
<url-pattern>/rest-simple/*</url-pattern>
</servlet-mapping>
</web-app>
On trying to access http://localhost:8080/Rest-EmployeeManager/rest-simple/employee-manager/employeelist the following is displayed:
HTTP Status 500 -
--------------------------------------------------------------------------------
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet.init() for servlet REST-Simple threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
root cause
java.lang.NoClassDefFoundError: Could not initialize class sun.proxy.$Proxy8
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
java.lang.reflect.Constructor.newInstance(Unknown Source)
java.lang.reflect.Proxy.newInstance(Unknown Source)
java.lang.reflect.Proxy.newProxyInstance(Unknown Source)
com.sun.jersey.server.impl.application.WebApplicationImpl$26.run(WebApplicationImpl.java:1626)
java.security.AccessController.doPrivileged(Native Method)
com.sun.jersey.server.impl.application.WebApplicationImpl.createProxy(WebApplicationImpl.java:1623)
com.sun.jersey.server.impl.application.WebApplicationImpl.<init>(WebApplicationImpl.java:335)
com.sun.jersey.server.impl.container.WebApplicationProviderImpl.createWebApplication(WebApplicationProviderImpl.java:55)
com.sun.jersey.spi.container.WebApplicationFactory.createWebApplication(WebApplicationFactory.java:66)
com.sun.jersey.spi.container.servlet.ServletContainer.create(ServletContainer.java:394)
com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.create(ServletContainer.java:309)
com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:603)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:376)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:559)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.27 logs.
--------------------------------------------------------------------------------
Apache Tomcat/7.0.27
Any help on what I'm possibly doing wrong?

I see you followed a tutorial. I can't find a Jersey version in it, but based on the date of the article, I don't think they use Jersey 2.x. If you do use the latest, try your project with Jersey 1.x. I got it working with 1.11.1 which is bundled with GlassFish 3.1.2.2.

You need to add "/" near
#GET
#Produces(MediaType.TEXT_PLAIN)
#Path("/employeelist")
public String getEmployeesInPlainFormat(){
and
#GET
#Produces(MediaType.TEXT_XML)
#Path("/employeelist")
public String getEmployeesInXmlFormat(){
EmployeeManager should be interface and implementation part should be separate one try like that.
Annotations are present in interface and implementation should be bean
like this
public interface EmployeeManager{
//declarations with annotations
}
public class EmployeeManagerImpl implements EmployeeManager{
// Implementation of methods
}
Use like that it will works

Try this :
package net.javabeat.articles.spring.rest.simple;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/employee-manager")
public class EmployeeManager {
private static Set<Employee> employees;
#GET
#Produces(MediaType.TEXT_XML)
#Path("/employeelist")
public String getEmployeesInXmlFormat(){
StringBuilder xmlResult = new StringBuilder();
xmlResult.append("<employees>");
Iterator<Employee> iterator = employees.iterator();
while (iterator.hasNext()){
Employee employee = iterator.next();
String employeeAsXml = employee.toXmlString();
xmlResult.append(employeeAsXml);
}
xmlResult.append("</employees>");
return xmlResult.toString();
}
#GET
#Produces(MediaType.TEXT_PLAIN)
#Path("/employeelist")
public String getEmployeesInPlainFormat(){
StringBuilder plainResult = new StringBuilder();
plainResult.append("[employees]");
Iterator<Employee> iterator = employees.iterator();
while (iterator.hasNext()){
Employee employee = iterator.next();
String employeeAsXml = employee.toXmlString();
plainResult.append(employeeAsXml);
}
plainResult.append("[employees]");
return plainResult.toString();
}
static{
employees = new HashSet<Employee>();
employees.add(new Employee("1", "David", "IT"));
employees.add(new Employee("2", "John", "SALES"));
}
}
And then deploy it and you can use any rest client like Advanced REST Client in Google Chrome or REST Client extensioon in Firefox to test the service.

Related

HTTP Status 500 javax.servlet.ServletException: Servlet.init() for servlet [Jersey RESTful App] threw exception java.lang.IllegalArgumentException

I am writing my first Java REST application.
I was following this tutorial:
https://www.tutorialspoint.com/restful/restful_first_application.htm
but I am getting this error:
HTTP Status 500 – Internal Server Error
Type Exception Report
Message Servlet.init() for servlet [Jersey RESTful Application] threw exception
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
javax.servlet.ServletException: Servlet.init() for servlet [Jersey RESTful Application] threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:830)
Root Cause
java.lang.IllegalArgumentException
jersey.repackaged.org.objectweb.asm.ClassReader.<init>(ClassReader.java:171)
jersey.repackaged.org.objectweb.asm.ClassReader.<init>(ClassReader.java:153)
jersey.repackaged.org.objectweb.asm.ClassReader.<init>(ClassReader.java:425)
org.glassfish.jersey.server.internal.scanning.AnnotationAcceptingListener.process(AnnotationAcceptingListener.java:170)
org.glassfish.jersey.server.ResourceConfig.scanClasses(ResourceConfig.java:915)
org.glassfish.jersey.server.ResourceConfig._getClasses(ResourceConfig.java:869)
org.glassfish.jersey.server.ResourceConfig.getClasses(ResourceConfig.java:775)
org.glassfish.jersey.server.ResourceConfig$RuntimeConfig.<init>(ResourceConfig.java:1206)
org.glassfish.jersey.server.ResourceConfig$RuntimeConfig.<init>(ResourceConfig.java:1178)
org.glassfish.jersey.server.ResourceConfig.createRuntimeConfig(ResourceConfig.java:1174)
org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:345)
org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:392)
org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:177)
org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:369)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Thread.java:830)
Could you help me?
I checked with many similiar topics and articles also here on Stack Overflow but nothing helped me.
My specification:
OS: Windows 10
IDE: Eclipse Version: 2020-06 (4.16.0)
Application server: apache-tomcat-9.0.38
jaxrs-ri-2.25.1
I copied code from tutorial website to my project to make sure I made no mistake.
Java files:
UserService.java
package com.tutorialspoint;
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("/UserService")
public class UserService {
UserDao userDao = new UserDao();
#GET
#Path("/users")
#Produces(MediaType.APPLICATION_XML)
public List<User> getUsers(){
return userDao.getAllUsers();
}
}
User.java
package com.tutorialspoint;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String profession;
public User(){}
public User(int id, String name, String profession){
this.id = id;
this.name = name;
this.profession = profession;
}
public int getId() {
return id;
}
#XmlElement
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
#XmlElement
public void setName(String name) {
this.name = name;
}
public String getProfession() {
return profession;
}
#XmlElement
public void setProfession(String profession) {
this.profession = profession;
}
}
UserDao.java
package com.tutorialspoint;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class UserDao {
public List<User> getAllUsers(){
List<User> userList = null;
try {
File file = new File("Users.dat");
if (!file.exists()) {
User user = new User(1, "Mahesh", "Teacher");
userList = new ArrayList<User>();
userList.add(user);
saveUserList(userList);
}
else{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
userList = (List<User>) ois.readObject();
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return userList;
}
private void saveUserList(List<User> userList){
try {
File file = new File("Users.dat");
FileOutputStream fos;
fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(userList);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
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>User Management</display-name>
<servlet>
<servlet-name>Jersey RESTful 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.tutorialspoint</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Jersey RESTful Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
I got it working by using apache-tomcat-9.0.38 and Jersey 2.16

Getting 404 error while accessing a restful web service

I have created a simple UserManagement restful web service. in which I have created 3 classes. The source codes are as following.
User class
package com.tutorialspoint;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "user")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String profession;
public User(){}
public User(int id, String name, String profession){
this.id = id;
this.name = name;
this.profession = profession;
}
public int getId() {
return id;
}
#XmlElement
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
#XmlElement
public void setName(String name) {
this.name = name;
}
public String getProfession() {
return profession;
}
#XmlElement
public void setProfession(String profession) {
this.profession = profession;
}
}
UserDao class
package com.tutorialspoint;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class UserDao {
public List<User> getAllUsers(){
List<User> userList = null;
try {
File file = new File("Users.dat");
if (!file.exists()) {
User user = new User(1, "Mahesh", "Teacher");
userList = new ArrayList<User>();
userList.add(user);
saveUserList(userList);
}
else{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
userList = (List<User>) ois.readObject();
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return userList;
}
private void saveUserList(List<User> userList){
try {
File file = new File("Users.dat");
FileOutputStream fos;
fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(userList);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
UserService class
package com.tutorialspoint;
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("/UserService")
public class UserService {
UserDao userDao = new UserDao();
#GET
#Path("/users")
#Produces(MediaType.APPLICATION_XML)
public List<User> getUsers(){
return userDao.getAllUsers();
}
}
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>User Management</display-name>
<servlet>
<servlet-name>Jersey RESTful 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.tutorialspoint</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Jersey RESTful Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Then I have created its war and deployed in Tomcat and start the Tomcat
But when I am accessing this restfull web service by hitting the url http://localhost:8080/UserManagement/rest/UserService/users
using Postman it gives 404 error.
Please some one help me out on this.
Try change servlet class with com.sun.jersey.spi.container.servlet.ServletContainer .

Rest Webservice returning http status 404

I am using Apache Tomcat 6 and the Jersey 2.0 libraries. I am running this service on 8088 port. While trying to access it, getting 404 not found error. This is my service:
User Class
package com.tutorialspoint;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String profession;
public User(){}
public User(int id, String name, String profession){
this.id = id;
this.name = name;
this.profession = profession;
}
public int getId() {
return id;
}
#XmlElement
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
#XmlElement
public void setName(String name) {
this.name = name;
}
public String getProfession() {
return profession;
}
#XmlElement
public void setProfession(String profession) {
this.profession = profession;
}
}
UserDao Class
package com.tutorialspoint;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class UserDao {
public List<User> getAllUsers(int id){
List<User> userList = null;
try {
User user = null;
if(id == 1){
user = new User(1, "Mahesh", "Teacher");
}
if(id == 2){
user = new User(2, "Manish", "Doctor");
}
userList = new ArrayList<User>();
userList.add(user);
} catch (Exception e) {
e.printStackTrace();
}
return userList;
}
}
UserService class
package com.tutorialspoint;
import java.util.List;
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;
#Path("/UserService")
public class UserService {
UserDao userDao = new UserDao();
#GET
#Path("{id}")
#Produces(MediaType.APPLICATION_XML)
public List<User> getUsers(#PathParam("id") int id){
return userDao.getAllUsers(id);
}
}
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>UserManagement</display-name>
<servlet>
<servlet-name>Jersey RESTful Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Jersey RESTful Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
My project Stucture is like this
Getting this error

How to delete record using primarykey in dynamodb

I get the record using primarykey id in amazon dynamodb using java.
AccountController.java
package com.dynamodb.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.account.json.AccountJson;
import com.account.service.AccountService;
#Controller
public class AccountController extends AbstractServiceController {
#Autowired
private AccountService accountService;
#RequestMapping(value = "/deleteAccountByAccountId", method = RequestMethod.POST)
public #ResponseBody String deleteAccountByAccountId(#RequestBody AccountJson accountJson) {
try {
Boolean bool = accountService.deleteAccountByAccountId(accountJson.getAccountId());
if (bool) {
return "Record deleted Successfully";
} else {
return "Record not deleted";
}
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
AccountService.java
package com.account.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.account.dao.AccountRepository;
#Service
public class AccountService {
#Autowired
private AccountRepository accountRepository;
public Boolean deleteAccountByAccountId(String accountId) {
return accountRepository.deleteAccountByAccountId(accountId);
}
}
AccountRepository.java
package com.account.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ComparisonOperator;
import com.amazonaws.services.dynamodbv2.model.Condition;
import com.account.datastore.Account;
#Repository
public class AccountRepository extends BaseRepository {
public Account getAccountByAccountId(String accountId) {
Account account = null;
try {
DynamoDBMapper mapper = getDynameDbMapper();
DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
scanExpression.addFilterCondition("accountId", new Condition().withComparisonOperator(ComparisonOperator.EQ).withAttributeValueList(new AttributeValue().withS(accountId)));
List<Account> accounts = mapper.scan(Account.class, scanExpression);
if (accounts != null && accounts.size() > 0) {
account = accounts.get(0);
}
} catch (Exception e) {
e.printStackTrace();
}
return account;
}
public Boolean deleteAccountByAccountId(String accountId) {
try {
Account account = getAccountByAccountId(accountId);
if (account != null) {
DynamoDBMapper mapper = getDynameDbMapper();
mapper.delete(account);
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
Account.java
package com.account.datastore;
import java.io.Serializable;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
#DynamoDBTable(tableName = "cd_accounts")
public class Account implements Serializable {
private static final long serialVersionUID = 244669855912873613L;
#DynamoDBAutoGeneratedKey
#DynamoDBHashKey
private String accountId;
private String documentTypeId;
private String accountName;
private Long isActive;
private Long isBill;
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getDocumentTypeId() {
return documentTypeId;
}
public void setDocumentTypeId(String documentTypeId) {
this.documentTypeId = documentTypeId;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public Long getIsActive() {
return isActive;
}
public void setIsActive(Long isActive) {
this.isActive = isActive;
}
public Long getIsBill() {
return isBill;
}
public void setIsBill(Long isBill) {
this.isBill = isBill;
}
}
Error is occurred while deleting the record. How to delete the record in amazon dynamodb using java.
com.amazonaws.AmazonServiceException: The provided key element does not match the schema (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: NR1SVIM98PVPFNHUOL49EI4JPFVV4KQNSO5AEMVJF66Q9ASUAAJG)
10:02:18,739 ERROR [AccountRepository] deleteAccountByAccountId Error:The provided key element does not match the schema (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: NR1SVIM98PVPFNHUOL49EI4JPFVV4KQNSO5AEMVJF66Q9ASUAAJG)
10:02:18,739 DEBUG [AccountController] --------------deleteAccountByAccountId----------------END------------------
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1077)
at com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:725)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:460)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:295)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:3106)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.deleteItem(AmazonDynamoDBClient.java:967)
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.delete(DynamoDBMapper.java:1364)
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.delete(DynamoDBMapper.java:1272)
at com.account.dao.AccountRepository.deleteAccountByAccountId(AccountRepository.java:110)
at com.account.service.AccountService.deleteAccountByAccountId(AccountService.java:40)
at com.account.controller.AccountController.deleteAccountByAccountId(AccountController.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
documentTypeId is primarykey for cd_documentTypes table, this primarykey is used in cd_accounts table as a foreignkey.
If the table having foreignkey relation we must mention the #DynamoDBRangeKey annotation above documentTypeId attribute in Account class. Problem is solved after declared the #DynamoDBRangeKey on top of the attribute documentTypeId.
#DynamoDBRangeKey
private String documentTypeId;
If we want to save or update or delete records in amazon dynamodb using java we must mention the
annotation #DynamoDBHashKey on top of the primarykey column.
#DynamoDBAutoGeneratedKey
#DynamoDBHashKey
private String accountId;
Below is the image shown for foreignkey relation exists in cd_accounts table.
Note:Range key attribute field is displayed if the table is mapping to another table primarykey in amaozong dynamodb.

java.lang.NoSuchMethodException: [Lcom.dn.vo.User;.<init>()

I am using Spring MVC to build a web application. I created a new VO named User and created a POST method to process the VO. The VO is having default constructor, yet I am getting
java.lang.NoSuchMethodException: [Lcom.dn.vo.User;.<init>().
The code involved is as follows:
User VO
package com.dn.vo;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.beans.factory.annotation.Autowired;
import com.dn.enums.Salutation;
#Entity
#Table(name = "PHONE_USER")
public class User implements Serializable {
long userId;
String firstName;
String surName;
Salutation salutation;
public User() {
super();
}
public User(long userId, String firstName, String surName, Salutation salutation) {
super();
this.userId = userId;
this.firstName = firstName;
this.surName = surName;
this.salutation = salutation;
}
#Id
#GeneratedValue
#Column(name = "USER_ID", unique = true, nullable = false, precision = 5, scale = 0)
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
#Column(name = "FIRST_NAME", nullable = false, length = 20)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "SURNAME", nullable = false, length = 20)
public String getSurName() {
return surName;
}
public void setSurName(String surName) {
this.surName = surName;
}
#Column(name = "SALUTATION", nullable = false, length = 20)
public Salutation getSalutation() {
return salutation;
}
public void setSalutation(Salutation salutation) {
this.salutation = salutation;
}
#Override
public String toString() {
return firstName+" "+surName;
}
}
MVC Controller
package com.dn.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.dn.db.DBConnectionProvider;
import com.dn.vo.User;
#Controller
public class UserRegistrationController {
#Autowired
private DBConnectionProvider dbConnectionProvider;
#ResponseBody #RequestMapping(value= "/createUser", method = RequestMethod.POST, headers="Accept=application/json")
public void createUser( User user) {
System.out.println(user.toString());
}
#ResponseBody #RequestMapping(value= "/createUsers", method = RequestMethod.POST, headers="Accept=application/json")
public void createUser( User[] user) {
System.out.println(user.toString());
}
}
HTTP Client Test
package com.dn.controller;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.codehaus.jackson.map.ObjectMapper;
import com.dn.enums.Salutation;
import com.dn.vo.User;
public class UserRegistrationControllerTest {
public static void main(String[] args) {
UserRegistrationControllerTest test = new UserRegistrationControllerTest();
test.testUserArrayInput();
}
private void testSingleUserInput(){
HttpClient httpClient = null;
try {
httpClient = new DefaultHttpClient();
String url = "http://localhost:8080/DNServer/createUser";
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(new BasicHeader("Accept", "application/json"));
User region = new User();
region.setFirstName("ABC");
region.setSurName("XYZ");
region.setSalutation(Salutation.Mr);
ObjectMapper mapper = new ObjectMapper();
System.out.println( mapper.writeValueAsString(region));
List nameValuePairs = new ArrayList();
nameValuePairs.add(new BasicNameValuePair("user", mapper.writeValueAsString(region)));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
System.out.println("test Single User Input done"+response);
} catch (Exception e) {
e.printStackTrace();
}
}
private void testUserArrayInput(){
HttpClient httpClient = null;
try {
httpClient = new DefaultHttpClient();
String url = "http://localhost:8080/DNServer/createUsers";
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(new BasicHeader("Accept", "application/json"));
User[] regions = new User[1];
User region = new User();
region.setFirstName("XYZ");
region.setSurName("ABC");
region.setSalutation(Salutation.Mr);
regions[0] = region;
ObjectMapper mapper = new ObjectMapper();
System.out.println( mapper.writeValueAsString(regions));
List nameValuePairs = new ArrayList();
nameValuePairs.add(new BasicNameValuePair("users", mapper.writeValueAsString(regions)));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
System.out.println("done");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Full Stack Trace
SEVERE: Servlet.service() for servlet [DNServlet] in context with path [/DNServer] threw exception [Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [[Lcom.dn.vo.User;]: No default constructor found; nested exception is java.lang.NoSuchMethodException: [Lcom.dn.vo.User;.<init>()] with root cause
java.lang.NoSuchMethodException: [Lcom.dn.vo.User;.<init>()
at java.lang.Class.getConstructor0(Class.java:2721)
at java.lang.Class.getDeclaredConstructor(Class.java:2002)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:105)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:81)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:104)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:79)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:157)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:124)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:301)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:74)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1017)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:652)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1575)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1533)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)`enter code here`
I think that the clue is in the method name:
[Lcom.dn.vo.User;.<init>()
When we deconstruct that, Spring appears to be trying to invoke a no-args constructor (the <init>() "method") on the type [Lcom.dn.vo.User;. But that type means "array of com.dn.vo.User". And array classes don't have constructors.
I can see some code in your unit test that creates a User[] and appears to pass it as an argment in a POST request to "/createUsers". But the MVC class doesn't have a method that binds to "/createUsers".
Is that right???

Categories