In Spring mvc application, #RequestBody is throwing java.io.EOFException - java

In the jsp i am passing the data as json,as in the controller method i am trying to map the data to Personbean object using #RequestMapping. But its throwing an exception.
#ResponseBody is working fine, if i remove the #ResponseBody code.
Please suggest what am i doing wrong?
I have pasted the code for reference.
//jsp (added the data as json and also content type)
<script>
function abc(){
alert('here!!');
$.ajax({
url:'anki',
type:'GET',
data:({name:"me"}),
dataType: 'json',
contentType: 'application/json',
success:function(data){
alert('here gain');
$('#time').html(data.name);
}
});
}
</script>
<input type="button" name="submit" title="submit" onclick="abc()"/>
<div id="time"></div>
//PersonBean (Bean class)
package com.controller;
public class Personbean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// controller method
//(Trying to use both #ResponseBody and #RequestBody in this method)
#RequestMapping(value="/anki",method=RequestMethod.GET)
public #ResponseBody EmployeeBean hhh(#RequestBody Personbean pb){
System.out.println(pb.getName());
System.out.println("new method");
EmployeeBean e=new EmployeeBean();
e.setId("1001");
e.setName("ankita");
return e;
}
//i have added the "jacksonMessageConverter" in the dispatcher servlet
//dispatcher servlet
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>
</list>
</property>
//Exception stacktrace(For reference)
java.io.EOFException: No content to map to Object due to end of input
at org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2444)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2396)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1662)
at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal(MappingJacksonHttpMessageConverter.java:124)
at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:154)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.readWithMessageConverters(HandlerMethodInvoker.java:633)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveRequestBody(HandlerMethodInvoker.java:597)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:346)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:574)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

Try this
$.ajax({
url:'anki',
type:'POST',
data:JSON.stringify(eval({"name":"me"})),
dataType: 'json',
contentType: 'application/json',
success:function(data){
alert('here gain');
// $('#time').html(data.name);
}
});
Dont forget to change the Method to POST in your controller
method=RequestMethod.POST

The GET method will not work because it will send the data in the URL and not in the request body.
#RequestBody expects data to be present in body of request. Changing the http method to POST will resolve the error.

Related

Type boolean, and MIME media type application/octet-stream was not found Java (Jersey)

I am using Jersey version 1.12 and i am facing the error that is
A message body writer for Java class java.lang.Boolean, and Java type boolean, and MIME media type application/octet-stream was not found
at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:285)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1451)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1363)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1353)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:414)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:708)
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:502)
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:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
my code is
#POST
#Path("/save/{Name}/{data}")
#Consumes("application/x-www-form-urlencoded")
public String saveDataMap(#QueryParam("number") String number,
#PathParam("data") String data,
#PathParam("Name") String appName
MultivaluedMap<String, String> formParam) throws Exception{
boolean response =false'
try{
// some business logic
response =true
}
return response;
}
After Googling this error i found that this is due to you are not specifying the content type of the data you are sending - so Jersey is not able to locate the right MessageBodyWritter to serialize
after this i added produces anotation to the method with the MediaType.TEXT_PLAIN but it doesn't work ,but when i changed return type of method to String it started working.
I simply wants to know whats problem with boolean ,why it is not working with boolean ? and how to solve this problem without changing boolean to String ?
any help will be greatly appreciated.
I usually code these methods like this:
#POST
#Path("/save/{Name}/{data}")
#Consumes("application/x-www-form-urlencoded")
#Produces(MediaType.TEXT_PLAIN)
public Response saveDataMap(#QueryParam("number") String number,
#PathParam("data") String data,
#PathParam("Name") String appName
MultivaluedMap<String, String> formParam) throws Exception{
boolean response =false
try{
// some business logic
response =true
}
return Response.ok().entity(String.valueOf(response)).build();
}
The only changes is that it returns a jersey HTTP response building it from a string from a boolean.
I hope it helps.
Regards,
Cris.

LinkedIn login integration with Spring MVC web Application

I am New to Spring ,and I want to log into a Spring MVC app. With LinkedIn ,
I use SCRIBE for login , but when I run the application, it throws an exception.
My controller code for linkedin in MVC is like:
#RequestMapping(value="/loginlinkedin", method=RequestMethod.GET)
public String callback(WebRequest request){
OAuthService service=linkedInServiceProvider.getService();
System.out.println("above request token");
//request token
Token requestToken=service.getRequestToken();
System.out.println(requestToken);
System.out.println("below request token");
//getting authorized url
String oauth_verif= service.getAuthorizationUrl(requestToken);
System.out.println(oauth_verif);
//verifing the requested token
Verifier verifier=new Verifier(in.nextLine());
System.out.println("below verifier"+verifier);
//get AccessToken
Token accessToken=service.getAccessToken(requestToken, verifier);
System.out.println("access tolen"+accessToken);
OAuthRequest oauthRequest=new OAuthRequest(Verb.GET, "http://api.linkedin.com/v1/people/~:(id,first-name,last-name,industry,headline)");
System.out.println("outhrequest"+oauthRequest);
service.signRequest(accessToken, oauthRequest);
Response outhResponse=oauthRequest.send();
System.out.println(outhResponse.getBody());
//ModelAndView mav=new ModelAndView("redirect:loginPage");
return "result";
}
and beans for linked login:
<bean id="linkedInServiceProvider" class="com.spring.handler.OAuthServiceProvider">
<constructor-arg name="oauthServiceConfig" ref="linkedInServiceConfig" />
</bean
And OAuthServiceConfig class for configuration of service:
package com.spring.handler;
import org.scribe.builder.api.Api;
public class OAuthServiceConfig {
private String apiKey;
private String apiSecret;
private String callback;
private Class apiClass;
public OAuthServiceConfig(String apiKey,String apiSecret,String callback,Class apiClass){
super();
this.apiKey=apiKey;
this.apiSecret=apiSecret;
this.callback=callback;
this.apiClass=apiClass;
System.out.println(apiKey+apiSecret+callback+apiClass);
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getApiSecret() {
return apiSecret;
}
public void setApiSecret(String apiSecret) {
this.apiSecret = apiSecret;
}
public String getCallback() {
return callback;
}
public void setCallback(String callback) {
this.callback = callback;
}
public Class getApiClass() {
return apiClass;
}
public void setApiClass(Class apiClass) {
this.apiClass = apiClass;
}
}
and OAuthServiceProvider class for providing the service to OAuthService using linkedInServiceProvider.getService() method:
package com.spring.handler;
import org.scribe.builder.ServiceBuilder;
import org.scribe.oauth.OAuthService;
public class OAuthServiceProvider {
OAuthServiceConfig oauthServiceConfig;
public OAuthServiceProvider() {
}
public OAuthServiceProvider(OAuthServiceConfig oauthServiceConfig) {
this.oauthServiceConfig = oauthServiceConfig;
}
public OAuthService getService() {
System.out.println(oauthServiceConfig);
return new ServiceBuilder().provider(oauthServiceConfig.getApiClass())
.apiKey(oauthServiceConfig.getApiKey())
.apiSecret(oauthServiceConfig.getApiSecret())
.callback(oauthServiceConfig.getCallback()).build();
}
}
But when I log into the application, the exception thrown is:
May 28, 2015 5:42:17 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [HelloWebHandler] in context with path [/SpringHandler] threw exception [Request processing failed; nested exception is org.scribe.exceptions.OAuthException: Response body is incorrect. Can't extract token and secret from this: 'oauth_problem=permission_unknown'] with root cause
org.scribe.exceptions.OAuthException: Response body is incorrect. Can't extract token and secret from this: 'oauth_problem=permission_unknown'
at org.scribe.extractors.TokenExtractorImpl.extract(TokenExtractorImpl.java:41)
at org.scribe.extractors.TokenExtractorImpl.extract(TokenExtractorImpl.java:27)
at org.scribe.oauth.OAuth10aServiceImpl.getAccessToken(OAuth10aServiceImpl.java:104)
at org.scribe.oauth.OAuth10aServiceImpl.getAccessToken(OAuth10aServiceImpl.java:85)
at org.scribe.oauth.OAuth10aServiceImpl.getAccessToken(OAuth10aServiceImpl.java:90)
at com.spring.handler.UserController.callback(UserController.java:109)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
permission_unknown: The User hasn't decided whether to permit
this Consumer to access Protected Resources. Usually happens when the
Consumer requests Access Token before the user completes authorization
process.
To trace and solve your problem :
Turn the scribe debug mode on executing debug() method on ServiceBuilder.
Read carefully the Getting started guide from scribe-java
Review your code for inconsistences:
//verifing the requested token
Verifier verifier=new Verifier(in.nextLine());
System.out.println("below verifier"+verifier);
What's in? you have to verify the request token, seems like you copied that line from the scribe examples, anyway it's hard to believe that your code works because in is not declared.
Rebuild your controller: implement the start authentication method first, get or store the request token attribute and redirect to the authorization url (linkedin url) if its required (service.getAuthorizationUrl()); implement your callback method, (after the user has approved the access to his profile, he is redirected to our callback endpoint defined in your OAuthServiceConfig class) and get the oauth_verifier and the request token to verify and obtain the accessToken, store it, sign the request... etc... etc

Spring MVC - Get non-mulitpart form/data in Multipart HTTP Post

Form my client application (AngularJS), I am uploading a file and some other data as FormData.
var formData=new FormData();
formData.append("file",file.files[0]); //files
formData.append("docData", angular.toJson($scope.docdata)); //invoice
Value of angular.toJson($scope.docdata) is like {"configuration":20,"title":"invoicedata"}
This is my HTTP post
$http({
method: 'POST',
url: uploadurl,
headers: {'Content-Type': false},
data: formData,
transformRequest: function(data, headersGetterFunction) {
return data;
}
})
.success(function(data, status) {
alert("Error");
})
.error(function(data, status) {
alert("Error");
});
The request is getting in my Spring MVC controller and I am able to process with the file. But the other data (docData), I am not able to get.
Here is my UploadController.java
#Controller
public class UploadController {
#RequestMapping(value="/newDocument", method = RequestMethod.POST)
public void UploadFile(HttpServletRequest request, HttpServletResponse response) {
MultipartHttpServletRequest mRequest=(MultipartHttpServletRequest)request;
Iterator<String> itr=mRequest.getFileNames();
while(itr.hasNext()){
MultipartFile file=mRequest.getFile(itr.next());
String fileName=file.getOriginalFilename();
try {
File newFile = new File("/home/myHome/file-uploaded/"+fileName);
// if the directory does not exist, create it
if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdirs();
}
FileCopyUtils.copy(file.getBytes(), newFile);
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
Enumeration<String> parametrs = request.getParameterNames();
while(parametrs.hasMoreElements()) {
String param=parametrs.nextElement();
System.out.println("Param : " + param);
Object object=request.getAttribute(param);
System.out.println("Param Instance" + object.getClass().getName());
}
}
}
The first part is working perfectly. (Copying file to the directory). But the second part giving me an exception. First it prints the value of param which is docData the one I send form client app in FormData. Then it throws the exception
java.lang.NullPointerException
at com.serverapp.demoapp.web.UploadController.UploadFile(UploadController.java:63)
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:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
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:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:920)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801)
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:502)
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)
Line 63 refers to System.out.println("Param Instance" + object.getClass().getName());
which means the object is null
How to get the values?
When you use multipart then your form fields are included in request Stream. So you have to check whether they are form fields or not.
This is what I use in a servlet, you can make appropriate changes in it to work in Spring-MVC.
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart)
{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext())
{
FileItem item = (FileItem) iterator.next();
if (item.isFormField()) //your code for getting form fields
{
String name = item.getFieldName();
String value = item.getString();
System.out.println(name+value);
}
if (!item.isFormField())
{
//your code for getting multipart
}
}
}

java.lang.IllegalArgumentException: java.text.ParseException: End of header

I encounter IllegalArgumentException while sending a post request to the restful web-service.
If i comment the method for post request(getEmplByPostReqParam()) then, code works fine for get request but with getEmplByPostReqParam(), all request throws IllegalArgumentException.
Can you please help in identifying the problem.
Web service code:
#Path("/employee")
public class EmployeeInfoService {
// This method is called if TEXT_PLAIN is request
#GET
#Path("/get/{id}")
#Produces(MediaType.APPLICATION_ATOM_XML)
public Employee getEmplById(#PathParam("id") String id) {
System.out.println("sayPlainTextHello");
EmployeeDAO dbHandler = new EmployeeDAOImpl();
Employee fetchedEmployee = dbHandler.findEmployee(Integer.parseInt(id));
return fetchedEmployee;
}
#GET
#Path("/get")
#Produces(MediaType.APPLICATION_ATOM_XML)
public Employee getEmplByGetReqParam(#QueryParam("param1") String id) {
System.out.println("getEmplByGetReqParam");
EmployeeDAO dbHandler = new EmployeeDAOImpl();
Employee fetchedEmployee = dbHandler.findEmployee(Integer.parseInt(id));
return fetchedEmployee;
}
#POST
#Path("/get")
#Produces("MediaType.TEXT_PLAIN")
public String getEmplByPostReqParam(#FormParam("param1") String id) {
System.out.println("getEmplByPostReqParam");
EmployeeDAO dbHandler = new EmployeeDAOImpl();
Employee fetchedEmployee = dbHandler.findEmployee(Integer.parseInt(id));
return fetchedEmployee.toString();
}
}
I used two client to test the service:
1. Google chrome's Advance Rest client
url - http://myhost:14443/de.vogella.jersey.first/rest/employee/get
payload - [param1: 1]
method type - [post]
core java code
String url = "http://myhost:14443/de.vogella.jersey.first/rest/employee/get";
String charset = "UTF-8";
String param1 = "1";
String query = String.format("param1=%s",
URLEncoder.encode(param1, charset));
URL service = new URL(url);
URLConnection connection = service.openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=" + charset);
OutputStream output = connection.getOutputStream();
try {
output.write(query.getBytes(charset));
} catch (Exception e) {
// TODO: handle exception
}
Stacktrace:
</pre></p><p><b>root cause</b> <pre>java.lang.IllegalArgumentException: java.text.ParseException: End of header
com.sun.jersey.core.header.MediaTypes.createQualitySourceMediaTypes(MediaTypes.java:289)
com.sun.jersey.core.header.MediaTypes.createQualitySourceMediaTypes(MediaTypes.java:274)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.addProduces(IntrospectionModeller.java:171)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.workOutSubResourceMethodsList(IntrospectionModeller.java:342)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.createResource(IntrospectionModeller.java:126)
com.sun.jersey.server.impl.application.WebApplicationImpl.getAbstractResource(WebApplicationImpl.java:744)
com.sun.jersey.server.impl.application.WebApplicationImpl.createAbstractResourceModelStructures(WebApplicationImpl.java:1564)
com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1328)
com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:168)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:774)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:770)
com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:770)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:765)
com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:489)
com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:319)
com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:374)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:557)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
</pre></p><p><b>root cause</b> <pre>java.text.ParseException: End of header
com.sun.jersey.core.header.reader.HttpHeaderReaderImpl.getNextCharacter(HttpHeaderReaderImpl.java:168)
com.sun.jersey.core.header.reader.HttpHeaderReaderImpl.next(HttpHeaderReaderImpl.java:129)
com.sun.jersey.core.header.reader.HttpHeaderListAdapter.next(HttpHeaderListAdapter.java:111)
com.sun.jersey.core.header.reader.HttpHeaderListAdapter.next(HttpHeaderListAdapter.java:98)
com.sun.jersey.core.header.reader.HttpHeaderReader.nextSeparator(HttpHeaderReader.java:116)
com.sun.jersey.core.header.QualitySourceMediaType.valueOf(QualitySourceMediaType.java:85)
com.sun.jersey.core.header.reader.HttpHeaderReader$5.create(HttpHeaderReader.java:360)
com.sun.jersey.core.header.reader.HttpHeaderReader$5.create(HttpHeaderReader.java:358)
com.sun.jersey.core.header.reader.HttpHeaderReader.readList(HttpHeaderReader.java:481)
com.sun.jersey.core.header.reader.HttpHeaderReader.readList(HttpHeaderReader.java:473)
com.sun.jersey.core.header.reader.HttpHeaderReader.readAcceptableList(HttpHeaderReader.java:461)
com.sun.jersey.core.header.reader.HttpHeaderReader.readQualitySourceMediaType(HttpHeaderReader.java:365)
com.sun.jersey.core.header.reader.HttpHeaderReader.readQualitySourceMediaType(HttpHeaderReader.java:373)
com.sun.jersey.core.header.MediaTypes.createQualitySourceMediaTypes(MediaTypes.java:287)
com.sun.jersey.core.header.MediaTypes.createQualitySourceMediaTypes(MediaTypes.java:274)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.addProduces(IntrospectionModeller.java:171)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.workOutSubResourceMethodsList(IntrospectionModeller.java:342)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.createResource(IntrospectionModeller.java:126)
com.sun.jersey.server.impl.application.WebApplicationImpl.getAbstractResource(WebApplicationImpl.java:744)
com.sun.jersey.server.impl.application.WebApplicationImpl.createAbstractResourceModelStructures(WebApplicationImpl.java:1564)
com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1328)
com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:168)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:774)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:770)
com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:770)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:765)
com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:489)
com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:319)
com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:374)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:557)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
If you notice your annotation (#Produces) argument is passed in double quotes. remove the double quotes and it should work
#Produces("MediaType.TEXT_PLAIN")
should look like below
#Produces(MediaType.TEXT_PLAIN)
I resolved the issue by changing the getEmplByPostReqParam() as follows:
#POST
#Path("/get")
public Response getEmplByPostReqParam(#FormParam("param1") String id) {
EmployeeDAO dbHandler = new EmployeeDAOImpl();
System.out.println("getEmplByPostReqParam");
Employee fetchedEmployee = dbHandler.findEmployee(Integer.parseInt(id));
ResponseBuilder rb = new ResponseBuilderImpl();
rb.type(MediaType.APPLICATION_ATOM_XML);
rb.entity(fetchedEmployee);
return rb.build();
}
This is working fine for me, if there is some better approach or there is something wrong with this approach, please post a comment.

Multipart Http Request

How can i initialized Multipart request..? I am uploading file using multipart/form-data content type but i can't get multipart request in my controller.So how can i get multipart request in my controller ..
Thanks in Advance.
I am getting error like this..
Jun 13, 2012 2:01:05 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/Login] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Multipart request not initialized] with root cause
java.lang.IllegalStateException: Multipart request not initialized
at org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest.initializeMultipart(AbstractMultipartHttpServletRequest.java:107)
at org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest.getMultipartFiles(AbstractMultipartHttpServletRequest.java:97)
at org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest.getFile(AbstractMultipartHttpServletRequest.java:60)
at com.mpm.common.controller.FileUploadController.create(FileUploadController.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:601)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:585)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:279)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)
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)
And my JSP code is :
<body>
<h1>Please upload a file</h1>
<form method="post" action="upload.action" enctype="multipart/form-data">
<input type="text" name="name"/></br>
<input type="file" name="file"/></br>
<input type="submit"/>
</form>
</body>
and my servlet-context.xml code is :
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
</bean>
<bean id="fileUploadController" class="com.mpm.common.controller.FileUploadController" ></bean>
You seem to use Spring. In that case, I usually manage multipart requests like this:
#RequestMapping("/url")
public String method(HttpServletRequest request) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// do stuff with multipartRequest
return "/jsp";
}
You simply need to cast your HttpServletRequest request.
public void upload(HttpServletRequest request) {
File up = new File("C:\\temp"); // path where u need to upload
// Create object of MultipartRequest to upload file
MultipartRequest m;
try {
m = new MultipartRequest(request, up.toString());
Enumeration files = m.getFileNames();
// Get the files to be uploaded from enumeration
while (files.hasMoreElements()) {
String upload = (String) files.nextElement();
filename = m.getFilesystemName(upload);
// out.println("<br/><br/><br/><br/>");
}
} catch (IOException e) {
System.out.println("Error in Uploading files...");
}
xsdName = filename.substring(0, filename.lastIndexOf('.'));
}
it was my code to do the same in servlet. Hope it helps.

Categories