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???
Related
I am trying to response with XML to a given call to the API.
Right now it works with JSON, I can send JSON or XML and return JSON.
But I cannot do the same with XML.
From now what I have is this:
RestVoterController class:
#RequestMapping("/rest")
#RestController
public class RESTVoterController {
#Autowired
private VoterService voterService;
#RequestMapping(value = {"/user.json","/user"},
method = RequestMethod.POST,
consumes = {"application/json","application/xml"},
produces = {"application/json"})
#Transactional(readOnly = true)
public Voter getVoterInfoJSON(#RequestBody VoterRequestGet voterRequestGet) {
return this.voterService.findByEmailAndPassword(voterRequestGet.getLogin(), voterRequestGet.getPassword());
}
#RequestMapping(value = "/user.xml",
method = RequestMethod.POST,
consumes = {"application/xml","application/json"},
produces = "application/xml")
#Transactional(readOnly = true)
public Voter getVoterInfoXML(#RequestBody VoterRequestGet voterRequestGet) {
return this.voterService.findByEmailAndPassword(voterRequestGet.getLogin(), voterRequestGet.getPassword());
}
#RequestMapping(value = "/changepassword",
method = RequestMethod.POST,
headers = "Accept=application/json",
produces = "application/json")
#Transactional(readOnly = true)
public void changePassword(#RequestBody VoterRequestChangePassword voterRequestChangePassword) {
this.voterService.changePassword(voterRequestChangePassword.getLogin(), voterRequestChangePassword.getOldPassword(), voterRequestChangePassword.getNewPassword());
}
}
VoterRequestGet class:
#XmlRootElement(name = "user")
#XmlAccessorType(XmlAccessType.FIELD)
public class VoterRequestGet {
#XmlElement
private String login;
#XmlElement
private String password;
public VoterRequestGet()
{
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
I tested your code and it works for me. Please look:
First I create mock for voterService.
package com.example;
import org.springframework.stereotype.Service;
#Service
public class VoterService {
public Voter findByEmailAndPassword(String login, String password) {
Voter voter = new Voter();
voter.setLogin(login);
voter.setPassword(password);
return voter;
}
}
Then I have to slightly modify your controller (remove Transaction annotation because I have no data source in my service mock).
package com.example;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
#RequestMapping("/rest")
#RestController
public class RESTVoterController {
#Autowired
private VoterService voterService;
#RequestMapping(value = {"/user.json","/user"},
method = RequestMethod.POST,
consumes = {"application/json","application/xml"},
produces = {"application/json"})
public Voter getVoterInfoJSON(#RequestBody VoterRequestGet voterRequestGet) {
return this.voterService.findByEmailAndPassword(voterRequestGet.getLogin(), voterRequestGet.getPassword());
}
#RequestMapping(value = "/user.xml",
method = RequestMethod.POST,
consumes = {"application/xml","application/json"},
produces = "application/xml")
public Voter getVoterInfoXML(#RequestBody VoterRequestGet voterRequestGet) {
return this.voterService.findByEmailAndPassword(voterRequestGet.getLogin(), voterRequestGet.getPassword());
}
}
Also I have to create mock for Voter because you don't share it.
package com.example;
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 = "voter")
#XmlAccessorType(XmlAccessType.FIELD)
public class Voter {
#XmlElement
private String login;
#XmlElement
private String password;
public Voter() {
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "Voter [login=" + login + ", password=" + password + "]";
}
}
And finally integration test.
package com.example;
import javax.annotation.Resource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.RestTemplate;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = TestApplication.class)
#WebIntegrationTest("server.port:0")
public class RESTVoterControllerTest {
private ServerProperties serverProperties;
private RestTemplate restTemplate = new RestTemplate();
#Resource
public void setServerProperties(ServerProperties serverProperties) {
this.serverProperties = serverProperties;
}
#Value("${local.server.port}")
private int serverPort;
private String serverUri;
#Before
public void setUp() throws Exception {
String contextPath = serverProperties.getContextPath();
serverUri = "http://localhost:" + serverPort + (contextPath == null ? "/" : contextPath);
}
#After
public void tearDown() throws Exception {
}
#Test
public void testCreate() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
VoterRequestGet voterRequest = new VoterRequestGet();
voterRequest.setLogin("email");
voterRequest.setPassword("secret");
HttpEntity<VoterRequestGet> request = new HttpEntity<>(voterRequest, headers);
System.out.println(restTemplate.postForEntity(
serverUri + "/rest/user.json", request, String.class).getBody());
System.out.println(restTemplate.postForEntity(
serverUri + "/rest/user.xml", request, String.class).getBody());
}
}
The result could be find in a output of the test and should contain two lines.
{"login":"email","password":"secret"}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><voter><login>email</login><password>secret</password></voter>
You need an XML mapping library like jackson, so adding this to your pom.xml will fix your problem:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
produces = { MediaType.APPLICATION_JSON_VALUE}
is the solution to me
I am using the Jersey Client of Sun Version 1.19...
When I send a put request with JSON (but every other request type probably as well) it serializes Number-typed variables with quotes, instead of as plain numbers.
Example:
User.java
package de.topazmedia.component.api.rest.client.ressource;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
#XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
public class User {
Long id;
String username;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return id;
}
public void setUsername(Long id) {
this.id = id;
}
}
Test.java
import javax.ws.rs.core.MediaType;
import org.json.JSONObject;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
public class Test {
public static void main(String[] args) {
User user = new User();
user.setId(1);
user.setUsername("Test");
ClientResponse response = null;
WebResource webResource = client.resource(http://192.168.23.56:9181/v1/users/" + user.getId());
Builder builder = webResource.header("Accept-Language", "de").type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON_TYPE);
response = builder.put(ClientResponse.class, user);
}
}
The "User JSON" I put as entity in the request is now translated to
{"id":"1","username":"Test"}
BUT it should be without the apostrphes at the id like this:
{"id":1,"username":"Test"}
What is wrong?
The solution of the problem ist quite simple.
Just define a POJO-Mapping in the ClientConfig when instantiating the Client Object:
ClientConfig cc = new DefaultClientConfig();
cc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
client = Client.create(cc);
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.
I have the following JPA entity (generated with Netbeans):
package com.tsystems.tf.db.models;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author johorvat
*/
#Entity
#Table(name = "TABLE1")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Testcase.findAll", query = "SELECT t FROM Testcase t")
})
public class Testcase implements Serializable {
private static final long serialVersionUID = 1L;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Id
#Basic(optional = false)
#Column(name = "TESTCASE_ID")
private BigDecimal testcaseId;
#Basic(optional = false)
#Column(name = "TESTCASE_NAME")
private String testcaseName;
#Basic(optional = false)
#Column(name = "CREATOR")
private String creator;
#Basic(optional = false)
#Column(name = "CREATED_AT")
#Temporal(TemporalType.TIMESTAMP)
private Date createdAt;
#Column(name = "LAST_RUN")
#Temporal(TemporalType.TIMESTAMP)
private Date lastRun;
#Column(name = "LAST_RUN_RESULT")
private Character lastRunResult;
#Column(name = "INPUT")
private String input;
#Column(name = "OUTPUT")
private String output;
public Testcase() {
}
public Testcase(BigDecimal testcaseId) {
this.testcaseId = testcaseId;
}
public Testcase(BigDecimal testcaseId, String testcaseName, String creator, Date createdAt) {
this.testcaseId = testcaseId;
this.testcaseName = testcaseName;
this.creator = creator;
this.createdAt = createdAt;
}
public BigDecimal getTestcaseId() {
return testcaseId;
}
public void setTestcaseId(BigDecimal testcaseId) {
this.testcaseId = testcaseId;
}
public String getTestcaseName() {
return testcaseName;
}
public void setTestcaseName(String testcaseName) {
this.testcaseName = testcaseName;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getLastRun() {
return lastRun;
}
public void setLastRun(Date lastRun) {
this.lastRun = lastRun;
}
public Character getLastRunResult() {
return lastRunResult;
}
public void setLastRunResult(Character lastRunResult) {
this.lastRunResult = lastRunResult;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public String getOutput() {
return output;
}
public void setOutput(String output) {
this.output = output;
}
#Override
public int hashCode() {
int hash = 0;
hash += (testcaseId != null ? testcaseId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Testcase)) {
return false;
}
Testcase other = (Testcase) object;
if ((this.testcaseId == null && other.testcaseId != null) || (this.testcaseId != null && !this.testcaseId.equals(other.testcaseId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.tsystems.tf.db.models.Testcase[ testcaseId=" + testcaseId + " ]";
}
}
I try to implement CRUD operations for this entity using Hibernate but I get LazyEvaluationException. There are NO references. Its only 1 table in the database... I can query but when I try to issue update the exception is being thrown. Now I have a really naive implementation that looks like the following:
package com.tsystems.tf.dao.impl;
import com.tsystems.tf.dao.ITestcaseDAO;
import com.tsystems.tf.db.models.Testcase;
import java.math.BigDecimal;
import java.util.Collection;
import javax.transaction.Transactional;
import org.apache.catalina.tribes.util.Arrays;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.jboss.logging.Logger;
public class TestcaseDAOImpl implements ITestcaseDAO {
private static final SessionFactory sessionFactory;
static {
Configuration configuration = new Configuration();
configuration = configuration.configure();
StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
registryBuilder = registryBuilder.applySettings(configuration.getProperties());
StandardServiceRegistry registry = registryBuilder.build();
sessionFactory = configuration.buildSessionFactory(registry);
}
#Override
public Collection<Testcase> getAllTestcase() {
Session session = sessionFactory.openSession();
Transaction transaction = null;
Collection<Testcase> testcaseCollection = null;
try {
transaction = session.beginTransaction();
Query query = session.getNamedQuery("Testcase.findAll");
testcaseCollection = query.list();
transaction.commit();
} catch (final HibernateException ex) {
Logger.getLogger(TestcaseDAOImpl.class)
.error(ex.getMessage() + "\n" + Arrays.toString(ex.getStackTrace()));
if (transaction != null)
transaction.rollback();
}
session.close();
return testcaseCollection;
}
#Override
public void createTestcase(Testcase testcase) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public Testcase readTestcase(BigDecimal id) {
Session session = sessionFactory.openSession();
Transaction transaction = null;
Testcase testcase = null;
try {
transaction = session.beginTransaction();
testcase = (Testcase) session.load(Testcase.class, id);
transaction.commit();
} catch (final HibernateException ex) {
Logger.getLogger(TestcaseDAOImpl.class)
.error(ex.getMessage() + "\n" + Arrays.toString(ex.getStackTrace()));
if (transaction != null)
transaction.rollback();
}
session.close();
return testcase;
}
#Override
public void updateTestcase(Testcase testcase) {
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.update(testcase);
transaction.commit();
} catch (final HibernateException ex) {
Logger.getLogger(TestcaseDAOImpl.class)
.error(ex.getMessage() + "\n" + Arrays.toString(ex.getStackTrace()));
if (transaction != null)
transaction.rollback();
}
session.close();
}
#Override
public void deleteTestcase(BigDecimal testcaseId) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
When the update is being called bamm No Session. Why is this happening? GetAll succeeds nice and smooth but that's all to it. Everything else returns in No Session error in my logs.
StackTrace:
14-Nov-2014 16:54:43.012 WARNING [http-apr-8080-exec-148] com.sun.faces.context.SessionMap.put JSF1063: WARNING! Setting non-serializable attribute value into HttpSession (key: testcaseProvider, value class: com.tsystems.tf.beans.TestcaseProvider).
14-Nov-2014 16:54:46.812 WARNING [http-apr-8080-exec-148] com.sun.faces.lifecycle.InvokeApplicationPhase.execute #{testcaseProvider.updateTestcase()}: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
javax.faces.FacesException: #{testcaseProvider.updateTestcase()}: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
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:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
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:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2403)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2392)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.el.EvaluationException: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 29 more
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at com.tsystems.tf.db.models.Testcase_$$_jvsta1c_0.setTestcaseName(Testcase_$$_jvsta1c_0.java)
at com.tsystems.tf.beans.TestcaseProvider.updateTestcase(TestcaseProvider.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 30 more
14-Nov-2014 16:54:46.832 SEVERE [http-apr-8080-exec-148] com.sun.faces.context.AjaxExceptionHandlerImpl.handlePartialResponseError javax.faces.el.EvaluationException: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
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:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
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:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2403)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2392)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at com.tsystems.tf.db.models.Testcase_$$_jvsta1c_0.setTestcaseName(Testcase_$$_jvsta1c_0.java)
at com.tsystems.tf.beans.TestcaseProvider.updateTestcase(TestcaseProvider.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 30 more
replace your static block by a before() method, and add the session creation at the end of it :
#Before
public void before() {
Configuration configuration = new Configuration();
configuration = configuration.configure();
StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
registryBuilder = registryBuilder.applySettings(configuration.getProperties());
StandardServiceRegistry registry = registryBuilder.build();
sessionFactory = configuration.buildSessionFactory(registry);
session = sessionFactory.openSession();
}
and an after() method :
#After
public void after {
session.close();
sessionFactory.close();
}
And of course, remove all open/close session in each test.
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.