I'm trying to call Birt report from a controller as following :
#RequestMapping(value = "/birtReport", method = RequestMethod.GET)
#ApiOperation("Download Report")
public void birtReport(HttpServletRequest request,HttpServletResponse response) throws ErrorExceptions, IOException{
HttpClient httpClient = HttpClients.createDefault();
HttpGet postRequest = new HttpGet("http://localhost:8080/birt/run?__report=MyFirstReport.rptdesign&id=211");
HttpResponse response1 = httpClient.execute(postRequest);
InputStream body = response1.getEntity().getContent();
IOUtils.copy(body, response.getOutputStream());
response.flushBuffer();
}
but i'm getting the following error :
Request method 'POST' not supported
Stack trace:
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
at org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.handleNoMatch(RequestMappingInfoHandlerMapping.java:207)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lookupHandlerMethod(AbstractHandlerMethodMapping.java:374)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:314)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:61)
at org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:352)
at org.springframework.web.servlet.DispatcherServlet.getHandler(DispatcherServlet.java:1160)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:940)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:728)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:469)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:392)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:311)
at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:395)
at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:254)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:177)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
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:748)
any idea how to fix it ?
Thank you in advance.
After inspecting the page generated in chrome the error is as the following :
Request URL:http://localhost:8080/MyWebApp/statReport/birtReport__sessionId=20180313_115522_490?__sessionId=20180313_115522_490&__dpi=96
Request Method:POST
Status Code:500
Remote Address:[::1]:8080
Referrer Policy:no-referrer-when-downgrade
try to change
HttpGet postRequest = new HttpGet("http://localhost:8080/birt/run?__report=MyFirstReport.rptdesign&id=211");
To
HttpPost postRequest = new HttpPost("http://localhost:8080/birt/run?__report=MyFirstReport.rptdesign&id=211");
See web.xml if it is configured like this.
if /* It causes post to no be unparsed .
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Change the method to RequestMethod.POST:
#RequestMapping(value = "/birtReport", method = RequestMethod.GET)
Related
I'm currently working on a plugin for Killbill, using Jooby for developing the servlet. The servlet will receive a notification from payment gateway and process the update into internal Killbill system
#Singleton
public class NotificationServlet {
private final InvoiceApi invoiceApi;
private static final Logger logger = LoggerFactory.getLogger(NotificationServlet .class);
#Inject
public NotificationServlet() {
// initiate InvoiceApi
this.invoiceApi = new InvoiceApi(new KillBillHttpClient());
}
#POST
#Path("/notify")
public Result notify(#Body String body) throws KillBillClientException {
logger.info(body);
JSONObject dataJson = new JSONObject(body);
if (dataJson.getString("status_code").equalsIgnoreCase("1")) {
String referenceId = dataJson.getString("reference_id");
String[] referenceIdArray = referenceId.split("\\|");
String apiKey = referenceIdArray[0];
String apiSecret = referenceIdArray[1];
String accountId = referenceIdArray[2];
String invoiceId = referenceIdArray[3];
String amount = referenceIdArray[4];
InvoicePayment invoicePayment = new InvoicePayment();
invoicePayment.setPurchasedAmount(new BigDecimal(amount));
invoicePayment.setAccountId(UUID.fromString(accountId));
invoicePayment.setTargetInvoiceId(UUID.fromString(invoiceId));
RequestOptions requestOptions = RequestOptions.builder()
.withCreatedBy("createdBy")
.withReason("reason")
.withComment("comment")
.withQueryParams(ArrayListMultimap.create())
.withTenantApiKey(apiKey)
.withTenantApiSecret(apiSecret)
.build();
InvoicePayment result = invoiceApi.createInstantPayment(UUID.fromString(invoiceId),
invoicePayment,
true,
null,
null,
requestOptions);
}
return Results.with("", Status.OK)
.type(MediaType.json);
}
When I tested this servlet using Postman, the servlet works fine. But when I tested this with the payment gateway, I got Jersey's ContainerException
2022-04-07T16:08:07,423+0000 lvl='ERROR', log='[default]', th='catalina-exec-10', xff='', rId='', tok='', aRId='', tRId='', Servlet.service() for servlet [default] in context with path [] threw exception [org.glassfish.jersey.server.ContainerException: java.io.IOException: Stream closed] with root cause
java.io.IOException: Stream closed
at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:367)
at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:152)
at com.google.common.io.ByteStreams.copy(ByteStreams.java:109)
at org.killbill.billing.jaxrs.resources.PluginResource.createInputStream(PluginResource.java:247)
at org.killbill.billing.jaxrs.resources.PluginResource.serviceViaOSGIPlugin(PluginResource.java:185)
at org.killbill.billing.jaxrs.resources.PluginResource.doFormPOST(PluginResource.java:140)
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:498)
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory.lambda$static$0(ResourceMethodInvocationHandlerFactory.java:52)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:124)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:167)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:176)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:79)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:475)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:397)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:81)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:255)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:248)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:244)
at org.glassfish.jersey.internal.Errors.process(Errors.java:292)
at org.glassfish.jersey.internal.Errors.process(Errors.java:274)
at org.glassfish.jersey.internal.Errors.process(Errors.java:244)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:265)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:234)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:680)
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:394)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:346)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:366)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:319)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:205)
at com.google.inject.servlet.ServletDefinition.doServiceImpl(ServletDefinition.java:290)
at com.google.inject.servlet.ServletDefinition.doService(ServletDefinition.java:280)
at com.google.inject.servlet.ServletDefinition.service(ServletDefinition.java:184)
at com.google.inject.servlet.ManagedServletPipeline.service(ManagedServletPipeline.java:89)
at org.killbill.billing.server.security.TenantFilter.handleAuthenticationError(TenantFilter.java:120)
at org.killbill.billing.server.security.TenantFilter.doFilter(TenantFilter.java:89)
at org.killbill.billing.server.filters.ResponseCorsFilter.doFilter(ResponseCorsFilter.java:75)
at ch.qos.logback.classic.helpers.MDCInsertingServletFilter.doFilter(MDCInsertingServletFilter.java:49)
at com.google.inject.servlet.ManagedFilterPipeline.dispatch(ManagedFilterPipeline.java:121)
at com.google.inject.servlet.GuiceFilter.doFilter(GuiceFilter.java:133)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.shiro.guice.web.SimpleFilterChain.doFilter(SimpleFilterChain.java:44)
at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108)
at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at org.apache.shiro.guice.web.SimpleFilterChain.doFilter(SimpleFilterChain.java:41)
at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108)
at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at org.apache.shiro.guice.web.SimpleFilterChain.doFilter(SimpleFilterChain.java:41)
at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383)
at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at com.codahale.metrics.servlet.AbstractInstrumentedFilter.doFilter(AbstractInstrumentedFilter.java:111)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:544)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.rewrite.RewriteValve.invoke(RewriteValve.java:305)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:747)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:616)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:818)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1626)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
I'm suspecting it might be because different type of body being sent, since I tested with Postman using raw data in JSON format meanwhile the gateway is sending x-www-form-urlencoded. I noticed this since there's a warning before this error appeared
2022-04-07T16:08:01,477+0000 lvl='WARN', log='WebComponent', th='catalina-exec-9', xff='', rId='', tok='', aRId='', tRId='',
A servlet request to the URI http://path/to/my/notify-servlet contains form parameters in
the request body but the request body has been consumed by the servlet or a servlet filter
accessing the request parameters. Only resource methods using #FormParam will work as
expected. Resource methods consuming the request body by other means will not work as expected.
I've tried adjusting the method according to Jooby's docs on form submission, but the issue still persists. So is the issue still in Jooby or it's in Jersey?
I'm trying to call Birt report from a controller as following:
#RequestMapping(value = "/birtReport", method = RequestMethod.GET)
#ApiOperation("Download Report")
public void birtReport(HttpServletRequest request,HttpServletResponse response) throws ErrorExceptions, IOException{
HttpClient httpClient = HttpClients.createDefault();
HttpPost postRequest = new HttpPost("http://localhost:8080/birt/run?__report=MyFirstReport.rptdesign&id=211");
HttpResponse response1 = httpClient.execute(postRequest);
InputStream body = response1.getEntity().getContent();
IOUtils.copy(body, response.getOutputStream());
response.flushBuffer();
}
What I'm really doing is calling a controller that call the birt report that exist on another Tomcat server but I'm getting the following error:
Stack Trace:
java.lang.IllegalStateException: The viewing session is not available or has expired.
at org.eclipse.birt.report.service.ReportEngineService.createRunAndRenderTask(ReportEngineService.java:1042)
at org.eclipse.birt.report.service.ReportEngineService.runAndRenderReport(ReportEngineService.java:911)
at org.eclipse.birt.report.service.BirtViewerReportService.runAndRenderReport(BirtViewerReportService.java:973)
at org.eclipse.birt.report.service.actionhandler.BirtGetPageAllActionHandler.__execute(BirtGetPageAllActionHandler.java:131)
at org.eclipse.birt.report.service.actionhandler.AbstractBaseActionHandler.execute(AbstractBaseActionHandler.java:90)
at org.eclipse.birt.report.soapengine.processor.AbstractBaseDocumentProcessor.__executeAction(AbstractBaseDocumentProcessor.java:47)
at org.eclipse.birt.report.soapengine.processor.AbstractBaseComponentProcessor.executeAction(AbstractBaseComponentProcessor.java:143)
at org.eclipse.birt.report.soapengine.processor.BirtDocumentProcessor.handleGetPageAll(BirtDocumentProcessor.java:183)
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:498)
at org.eclipse.birt.report.soapengine.processor.AbstractBaseComponentProcessor.process(AbstractBaseComponentProcessor.java:112)
at org.eclipse.birt.report.soapengine.endpoint.BirtSoapBindingImpl.getUpdatedObjects(BirtSoapBindingImpl.java:66)
at sun.reflect.GeneratedMethodAccessor577.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.axis.providers.java.RPCProvider.invokeMethod(RPCProvider.java:397)
at org.apache.axis.providers.java.RPCProvider.processMessage(RPCProvider.java:186)
at org.apache.axis.providers.java.JavaProvider.invoke(JavaProvider.java:323)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
at org.apache.axis.handlers.soap.SOAPService.invoke(SOAPService.java:454)
at org.apache.axis.server.AxisServer.invoke(AxisServer.java:281)
at org.apache.axis.transport.http.AxisServlet.doPost(AxisServlet.java:699)
at org.eclipse.birt.report.servlet.BirtSoapMessageDispatcherServlet.doPost(BirtSoapMessageDispatcherServlet.java:265)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.apache.axis.transport.http.AxisServletBase.service(AxisServletBase.java:327)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.eclipse.birt.report.servlet.BirtSoapMessageDispatcherServlet.service(BirtSoapMessageDispatcherServlet.java:122)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.eclipse.birt.report.filter.ViewerFilter.doFilter(ViewerFilter.java:68)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:500)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:754)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1376)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
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)
And is that the best way to call Birt reports from an API?
i was able to solve my problem by using report engine and that's the controller code:
#RequestMapping(value = "/birtReport1", method = RequestMethod.GET)
#ApiOperation("Download Report")
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//get report name and launch the engine
resp.setContentType("text/html");
// resp.setContentType( "application/pdf" );
//resp.setHeader ("Content-Disposition","inline; filename=test.pdf");
String reportName = "/Documents/workspace/Birt/MyFirstReport.rptdesign";
ServletContext sc = req.getSession().getServletContext();
this.birtReportEngine = BirtEngine.getBirtEngine(sc);
IReportRunnable design;
try
{
//Open report design
design = birtReportEngine.openReportDesign( reportName );
//create task to run and render report
IRunAndRenderTask task =
birtReportEngine.createRunAndRenderTask( design );
String[] values = {"10096", "10094"};
task.setParameterValue("idCatalogue",values);
HTMLRenderOption options = new HTMLRenderOption();
options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML);
options.setOutputStream(resp.getOutputStream());
task.setRenderOption(options);
//run report
task.run();
task.close();
}catch (Exception e){
e.printStackTrace();
throw new ServletException( e );
}
}
I am developing a Spring MVC + Apache Oltu + Instagram example. In this example I created an App on https://www.instagram.com/developer/ and I got the ClientId and Client_Secrete.
Uisng this clientId and Client Secret, calling the Instagram Rest EndPoints. But when calling either the REST EndPoint I am getting the below error:
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/apache-oltu] threw exception [Request processing failed; nested exception is OAuthProblemException{error='invalid_request', description='Missing parameters: access_token', uri='null', state='null', scope='null', redirectUri='null', responseStatus=0, parameters={}}] with root cause
OAuthProblemException{error='invalid_request', description='Missing parameters: access_token', uri='null', state='null', scope='null', redirectUri='null', responseStatus=0, parameters={}}
at org.apache.oltu.oauth2.common.exception.OAuthProblemException.error(OAuthProblemException.java:59)
at org.apache.oltu.oauth2.common.utils.OAuthUtils.handleOAuthProblemException(OAuthUtils.java:167)
at org.apache.oltu.oauth2.common.utils.OAuthUtils.handleMissingParameters(OAuthUtils.java:185)
at org.apache.oltu.oauth2.client.validator.OAuthClientValidator.validateRequiredParameters(OAuthClientValidator.java:90)
at org.apache.oltu.oauth2.client.validator.OAuthClientValidator.validateParameters(OAuthClientValidator.java:53)
at org.apache.oltu.oauth2.client.validator.OAuthClientValidator.validate(OAuthClientValidator.java:49)
at org.apache.oltu.oauth2.client.response.OAuthClientResponse.validate(OAuthClientResponse.java:127)
at org.apache.oltu.oauth2.client.response.OAuthClientResponse.init(OAuthClientResponse.java:96)
at org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse.init(OAuthAccessTokenResponse.java:65)
at org.apache.oltu.oauth2.client.response.OAuthClientResponse.init(OAuthClientResponse.java:101)
at org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse.init(OAuthAccessTokenResponse.java:60)
at org.apache.oltu.oauth2.client.response.OAuthClientResponse.init(OAuthClientResponse.java:120)
at org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory.createCustomResponse(OAuthClientResponseFactory.java:82)
at org.apache.oltu.oauth2.client.URLConnectionClient.execute(URLConnectionClient.java:111)
at org.apache.oltu.oauth2.client.OAuthClient.accessToken(OAuthClient.java:65)
at org.apache.oltu.oauth2.client.OAuthClient.accessToken(OAuthClient.java:55)
at com.apache.oltu.InstagramController.getAccessToken(InstagramController.java:76)
at com.apache.oltu.InstagramController.redirect(InstagramController.java:56)
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.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Following are the details I used:
AUTHORIZATION_URL = "https://api.instagram.com/oauth/authorize";
ACCESS_TOKEN_URL = "https://api.instagram.com/oauth/access_token";
The scopes which I used are:
public_content follower_list comments relationships likes basic
When code is executing, I am getting the authorizationCode successfully, but looks like token is missing.
I am calling the Rest Endpoint from URL: https://www.instagram.com/developer/endpoints/users/
The code which I used below for reference:
private String getAccessToken(String authorizationCode) throws OAuthSystemException, OAuthProblemException {
OAuthClientRequest request = OAuthClientRequest
.tokenLocation(ACCESS_TOKEN_URL)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setRedirectURI(REDIRECT_URL)
.setCode(authorizationCode)
.buildQueryMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
GitHubTokenResponse oAuthResponse = oAuthClient.accessToken(request, GitHubTokenResponse.class);
request= new OAuthBearerClientRequest("https://api.instagram.com/v1/users/self/").
setAccessToken(oAuthResponse.getAccessToken()).
buildQueryMessage();
System.out.println("REQUEST_BODY : "+request.getBody());
OAuthClient client = new OAuthClient(new URLConnectionClient());
OAuthResourceResponse resourceResponse= client.resource(request, "GET", OAuthResourceResponse.class);
if (resourceResponse.getResponseCode()==200){
logger.debug("HTTP OK");
System.out.println(resourceResponse.getBody());
return resourceResponse.getBody();
}
else{
System.out.println("Could not access resource: " + resourceResponse.getResponseCode()
+ " " + resourceResponse.getBody());
return null;
}
}
}
The following is the URL which is going ::
https://api.instagram.com/oauth/authorize?
scope=public_content+follower_list+comments+relationships+likes+basic&
response_type=code&
redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fapache-oltu%2Finstagram%2Fredirect&
client_id=40eb3e6047a249ddb7d9194765be9901
If I used ResponseType="token" then I get the
{"error_type": "OAuthForbiddenException", "code": 403, "error_message": "Implicit authentication is disabled"}
After lots of trial and error method, I was able to resolve this issue:
While making request for the access token I should be using the below:
OAuthClientRequest request = OAuthClientRequest
.authorizationLocation(AUTHORIZATION_URL)
.setClientId(CLIENT_ID)
.setRedirectURI(REDIRECT_URL)
.setResponseType(ResponseType.CODE.toString())
.setScope("public_content follower_list comments relationships likes basic")
.buildQueryMessage();
and with the subsequent request I will be using the below:
OAuthClientRequest request = OAuthClientRequest
//.authorizationProvider(OAuthProviderType.INSTAGRAM)
.tokenLocation(ACCESS_TOKEN_URL)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setRedirectURI(REDIRECT_URL)
.setCode(authorizationCode)
.buildBodyMessage();
and this gives me the solid Response:
{"data": {"id": "3159574895", "username": "Raj", "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/19367511_329283184160313_6318737005198966784_a.jpg", "full_name": "Raj", "bio": "Wish me on 25th-Dec\nLove to code !! \nEngineer by my choice !!\nLove to drive !! \ud83d\ude0b\ud83d\ude0a", "website": "", "is_business": false, "counts": {"media": 14, "follows": 18, "followed_by": 51}}, "meta": {"code": 200}}
After more google found : OAuthProblem, missing parameter access_token
I explain my problem. I send a Object who comes from my class User. I send it from my website to my restful service. But I try to have it and all types that I try in my params are not valide or null :
SEND Class:
public String update() {
try {
if(mdpVerification.equals(utilisateur.getMotDePasse())){
clientRest.setPath("user");
clientRest.putEntity(SessionBeanEFPlanning.getAdministrateur().getLogin()
, SessionBeanEFPlanning.getAdministrateur().getMotDePasse(), utilisateur, utilisateur.getId());
SessionBeanEFPlanning.displayFacesMessage(FacesMessage.SEVERITY_INFO, "L'utilisateur a été modifié avec succès!");
setUtilisateur(null);
setUtilisateurs(null);
super.getUtilisateurs();
return "/utilisateurs/index?faces-redirect=true";
}else{
SessionBeanEFPlanning.displayFacesMessage(FacesMessage.SEVERITY_INFO, "Les mot de passes ne concordent pas !");
return "/utilisateur/edit?faces-redirect=true";
}
} catch (serverIllegalStateException exception) {
String message = "";
if (exception.getMessage().toLowerCase().contains("erreur : pseudo identique")) {
message = "Ce pseudo est déjà attribué !";
} else if (exception.getMessage().toLowerCase().contains("erreur : email identique")) {
message = "Cet email est déjà attribué !";
} else {
message = exception.toString();
}
SessionBeanEFPlanning.displayFacesMessage(FacesMessage.SEVERITY_ERROR, message);
return "/utilisateurs/edit?faces-redirect=true";
}
}
I have already see if my Object was null and it was not ! I give you the class how send informations :
public Object putEntity(String login, String password, Utilisateur JsonObject, Long id) {
WebTarget webTarget = client.target(URI_REST_SERVICE)
.path(URI_PATH)
.path(Long.toString(id))
.queryParam("login", login)
.queryParam("password", password);
System.out.println(webTarget);
return super.<Utilisateur>putEntity(webTarget, JsonObject, new GenericType<Utilisateur>() {
});
}
And its interface :
protected <T> T putEntity(WebTarget webTarget, T entity, GenericType genericType) {
Response response = put(webTarget, entity);
checkStatus200(response);
return (T) response.readEntity(genericType);
}
Now I give you the receive class :
#PUT
#Path("/{id : \\d+}")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response updateUser(#QueryParam("login") String login,
#QueryParam("password") String password,#PathParam("id") long id, JsonArray utilisateur) {
try {
System.out.println(utilisateur);
if (utilisateur != null) {
// mapper.update(utilisateur);
return Response.status(Response.Status.OK).entity(utilisateur).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity(
new MessageServiceErreur("Erreur utilisateur NULL")).build();
}
} catch (IllegalStateMessage exception) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
new MessageServiceErreur(exception.toString())).build();
}
}
And like the title said I have this error from my tomcat log ::
javax.ws.rs.NotSupportedException: HTTP 415 Unsupported Media Type
at org.glassfish.jersey.server.spi.internal.ParameterValueHelper.getParameterValues(ParameterValueHelper.java:87)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$AbstractMethodParamInvoker.getParamValues(JavaResourceMethodDispatcherProvider.java:121)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:152)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:402)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:349)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:106)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:259)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:318)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:236)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1010)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:373)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:382)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:345)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:220)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
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.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=application/json, type=interface javax.json.JsonArray, genericType=interface javax.json.JsonArray.
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:207)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:139)
at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundReadFrom(MappableExceptionWrapperInterceptor.java:72)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:139)
at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1109)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:853)
at org.glassfish.jersey.server.ContainerRequest.readEntity(ContainerRequest.java:262)
at org.glassfish.jersey.server.internal.inject.EntityParamValueFactoryProvider$EntityValueFactory.provide(EntityParamValueFactoryProvider.java:96)
at org.glassfish.jersey.server.spi.internal.ParameterValueHelper.getParameterValues(ParameterValueHelper.java:81)
... 41 more
My question is : How can I receive the information correctly ?
NEW ERROR :
com.fasterxml.jackson.databind.JsonMappingException: Can not find a deserializer for non-concrete Map type [map type; class javax.json.JsonObject, [simple type, class java.lang.String] -> [simple type, class javax.json.JsonValue]]
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:268)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:243)
at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:144)
at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:381)
at com.fasterxml.jackson.databind.ObjectReader._findRootDeserializer(ObjectReader.java:1380)
at com.fasterxml.jackson.databind.ObjectReader._bind(ObjectReader.java:1228)
at com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:677)
at com.fasterxml.jackson.jaxrs.base.ProviderBase.readFrom(ProviderBase.java:777)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:233)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:211)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:139)
at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundReadFrom(MappableExceptionWrapperInterceptor.java:72)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:139)
at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1109)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:853)
at org.glassfish.jersey.server.ContainerRequest.readEntity(ContainerRequest.java:262)
at org.glassfish.jersey.server.internal.inject.EntityParamValueFactoryProvider$EntityValueFactory.provide(EntityParamValueFactoryProvider.java:96)
at org.glassfish.jersey.server.spi.internal.ParameterValueHelper.getParameterValues(ParameterValueHelper.java:81)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$AbstractMethodParamInvoker.getParamValues(JavaResourceMethodDispatcherProvider.java:121)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:152)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:402)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:349)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:106)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:259)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:318)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:236)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1010)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:373)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:382)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:345)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:220)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
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)
LOG JERSEY :
HTTP REQUEST : User: unknown - Path: /user - Header: {accept=[application/json], user-agent=[Jersey/2.10.4 (HttpUrlConnection 1.8.0_77)], host=[localhost:8082], connection=[keep-alive]} - Entity:
HTTP RESPONSE : Header: {Content-Type=[application/json]} - Entity: [EJPlanning.Models.Utilisateur#6a277cb, EJPlanning.Models.Utilisateur#1fe07c0b]
HTTP REQUEST : User: unknown - Path: /user - Header: {accept=[application/json], user-agent=[Jersey/2.10.4 (HttpUrlConnection 1.8.0_77)], host=[localhost:8082], connection=[keep-alive]} - Entity:
HTTP RESPONSE : Header: {Content-Type=[application/json]} - Entity: [EJPlanning.Models.Utilisateur#73fd68e9, EJPlanning.Models.Utilisateur#4d012aaf]
HTTP REQUEST : User: unknown - Path: /user/4601 - Header: {accept=[application/json], content-type=[application/json], user-agent=[Jersey/2.10.4 (HttpUrlConnection 1.8.0_77)], host=[localhost:8082], connection=[keep-alive], content-length=[109]} - Entity: {"id":4601,"login":"Scadra","motDePasse":"","nom":"Colart","prenom":"Pierre","typeUtilisateur":"RESPONSABLE"}
HTTP RESPONSE : Header: {Content-Type=[application/json]} - Entity: EJPlanning.Models.Utilisateur#1ac66ff1
HTTP REQUEST : User: unknown - Path: /user - Header: {accept=[application/json], user-agent=[Jersey/2.10.4 (HttpUrlConnection 1.8.0_77)], host=[localhost:8082], connection=[keep-alive]} - Entity:
HTTP RESPONSE : Header: {Content-Type=[application/json]} - Entity: [EJPlanning.Models.Utilisateur#617845f2, EJPlanning.Models.Utilisateur#70eb5f1a]
The error message is telling you that it can't deserialize the income JSON into a JsonArray.
"How can I receive the information correctly ?"
Use a POJO instead of JsonArray as the method parameter.
Make sure you have a Json Provider
Note: The previous link is for JSON/POJO support. If you want to stick with using the Javax.json classes (i.e. the JsonArray), you can also just include the following dependency (which has support for JSON-P)
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-processing</artifactId>
<version>${jersey2.version}</version>
</dependency>
This is all explained in Jersey docs: Support for Common Media Type Representations
I need to handle file from client using http. Server side is writen on Spring boot. This reqest controller side
#RequestMapping(value = "/upload", method = RequestMethod.POST)
#ResponseBody
public void uploadFile(#RequestParam("file") MultipartFile uploadfile) {
System.out.println("filename: " + uploadfile.getName());
}
And client side to path file is;
public static void main(String[] args) throws IOException {
URL url = new URL(UPLOAD_URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data");
File file = new File("test.txt");
//init array with file length
byte[] bytesArray = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytesArray); //read file into bytes[]
fis.close();
OutputStream os = conn.getOutputStream();
os.write(bytesArray);
os.flush();
conn.disconnect();
}
But i have the following error
org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
at org.apache.tomcat.util.http.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:840) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.tomcat.util.http.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:256) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:280) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.connector.Request.parseParts(Request.java:2843) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.connector.Request.parseParameters(Request.java:3219) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.connector.Request.getParameter(Request.java:1119) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.connector.RequestFacade.getParameter(RequestFacade.java:381) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:75) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455) [tomcat-embed-core-8.5.14.jar:8.5.14]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.14.jar:8.5.14]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_71]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_71]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.14.jar:8.5.14]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_71]
Pleas help me, i can't find the reason
I was also facing the same issue.
Dont put any value in "Header"tab of Postman. (Note: It is next to Body Tab)
This solved my problem
You are not writing your data to the connection in a multi-part structure.
You can use the answer to this question as a guide:
As the exception says your request is missing some information: Boundaries.
a multipart/form-data should be like this:
POST /upload HTTP/1.1
Host: myhost
User-Agent: uploader/1.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Content-Type: multipart/form-data; boundary=----------287032381131322
Content-Length: {sizeofcontent}
------------287032381131322
Content-Disposition: form-data; name="file"; filename="myfile.txt"
Content-Type: text/plain
My file content;
------------287032381131322--
See the boundary parameter in the content-type is used as a delimiter for each data (it can be any string).
Notice extra "--" at the end to notify data end. You need to write these to successfully upload a file.