I am trying to upload a file to server using trinidad fileupload (tr:inputFile) component but i get a
NullPointerException at setCharacterEncoding(UploadRequestWrapper.java:83)
on pressing the commandButton.
My XHTML file contains:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:tr="http://myfaces.apache.org/trinidad" >
<ui:composition template="/WEB-INF/templates/BasicTemplate.xhtml">
<ui:define name="content">
<tr:form usesUpload="true">
<tr:inputFile label="Upload:" valueChangeListener="#{myBackingBean.fileUploaded}"/>
<tr:commandButton text="Begin"/>
</tr:form>
</ui:define>
</ui:define>
</ui:composition>
</html>
the Backing Bean:
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import org.apache.myfaces.trinidad.model.UploadedFile;
public class MyBackingBean{
...
public void fileUploaded(ValueChangeEvent event){
UploadedFile file = (UploadedFile) event.getNewValue();
if (file != null){
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage message = new FacesMessage(
"Successfully uploaded file " + file.getFilename() +
" (" + file.getLength() + " bytes)");
context.addMessage(event.getComponent().getClientId(context), message);
// Here's where we could call file.getInputStream()
}
}
}
the WEB-INF/web.xml file:
<filter>
<filter-name>trinidad</filter-name>
<filter-class>org.apache.myfaces.trinidad.webapp.TrinidadFilter</filter-class
</filter>
<servlet>
<servlet-name>faces</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
</servlet>
<filter-mapping>
<filter-name>trinidad</filter-name>
<servlet-name>faces</servlet-name>
</filter-mapping>
I am using:
Server: Tomcat 7.0.12
MyFaces 2.2.0
Trinidad 2.0.1
JSTL 1.2
Eclipse Java EE IDE for Web Developers / Version: Kepler Service Release 1
Full output:
Schwerwiegend: Servlet.service() for servlet [Faces Servlet] in context with path [/com.cargarantie.ws.claimshandler] threw exception [null] with root cause java.lang.NullPointerException
at org.apache.myfaces.trinidadinternal.config.upload.UploadRequestWrapper.setCharacterEncoding(UploadRequestWrapper.java:83)
at org.apache.myfaces.context.servlet.ServletExternalContextImpl.setRequestCharacterEncoding(ServletExternalContextImpl.java:581)
at javax.faces.context.ExternalContextWrapper.setRequestCharacterEncoding(ExternalContextWrapper.java:416)
at javax.faces.context.ExternalContextWrapper.setRequestCharacterEncoding(ExternalContextWrapper.java:416)
at javax.faces.application.ViewHandler.initView(ViewHandler.java:339)
at org.apache.myfaces.application.ViewHandlerImpl.initView(ViewHandlerImpl.java:191)
at javax.faces.application.ViewHandlerWrapper.initView(ViewHandlerWrapper.java:49)
at org.apache.myfaces.lifecycle.RestoreViewExecutor.doPrePhaseActions(RestoreViewExecutor.java:83)
at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:182)
at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:143)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:196)
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)
Any ideas? Thanks in advance.
I solved the problem!
I don't know if this approach is best way to solve the problem but it works.
Create your own SetCharacterEncodingFilter class and add it to your build path. Source:
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class SetCharacterEncodingFilter implements Filter {
protected String encoding = null;
protected FilterConfig filterConfig = null;
protected boolean ignore = true;
#Override
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// Conditionally select and set the character encoding to be used
if (ignore || (request.getCharacterEncoding() == null)) {
String characterEncoding = selectEncoding(request);
if (characterEncoding != null)
request.setCharacterEncoding(characterEncoding);
}
// Pass control on to the next filter
chain.doFilter(request, response);
Utilities.ConsoleMsg("Done.", this, "doFilter", 5);
}
#Override
public void init(FilterConfig fConfig) throws ServletException {
this.filterConfig = fConfig;
this.encoding = fConfig.getInitParameter("encoding");
String value = fConfig.getInitParameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase("true"))
this.ignore = true;
else if (value.equalsIgnoreCase("yes"))
this.ignore = true;
else
this.ignore = false;
}
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
}
Register the Filter in web.xml and set your init parameters.
<filter>
<filter-name>UTFEncodingFilter</filter-name>
<filter-class>path.to.your.package.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>ignore</param-name>
<param-value>false</param-value>
</init-param>
</filter>
Add URIEncoding="UTF-8" attribute to all Connectors in server.xml. Example:
<Connector port="8080"
protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8" />
Sources:
https://issues.apache.org/jira/browse/TRINIDAD-1744
http://docs.oracle.com/cd/E16162_01/core.1112/e22506/chapter_adf_trinid_messages.htm
Character encoding problems with tomcat
Related
In Production Environment,When I make Request for my web page.The Request show in apache's access logs,but not in configured my configured web logs.
My logback.xml is
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml" />
<jmxConfigurator />
<property name="CONSOLE_LOG_PATTERN"
value="%d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${PID:- } --- [%15.15t{14}] %-40.40logger{0} : %m%n" />
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>/var/log/company_name/payments.log</file>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
</encoder>
</appender>
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="FILE" />
</root>
And My controller is
#CrossOrigin
#RestController
#RequestMapping("/my/v1")
public class PaymentApi {
#RequestMapping(value = RestURIConstants.VOID_TRANSACTION,
method = RequestMethod.POST )
public #ResponseBody ResponseEntity<?> voidPayment(#RequestParam("request") String voidRequestJson,
HttpServletRequest httpServletRequest) {
//Code here.
}
#ExceptionHandler
void handleException(Exception e, HttpServletResponse response) throws IOException {
logger.error("Error in Request : " + new ObjectMapper().writeValueAsString(e));
if (e instanceof IllegalArgumentException) {
response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
return;
}
response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), "an error occured while processing request");
}
}
I am making web Request using below code.
public static <T extends Response,S extends Request> T doPostRequest(S request,
Class<T> responseClass,
String urlString) throws ClientProtocolException, IOException{
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
logger.info("Sending Request " + objectMapper.writeValueAsString(request));
HttpEntity<String> entity = new HttpEntity<String>("request=" + objectMapper.writeValueAsString(request), headers);
ResponseEntity<String> response = null ;
response = restTemplate.exchange(urlString, HttpMethod.POST, entity, String.class);
logger.info("Response recieved " + response.toString());
if (response.getStatusCode() == HttpStatus.OK ||
response.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR) {
return objectMapper.readValue(response.getBody(), responseClass) ;
// gson.fromJson(response.getBody(), responseClass) ;
}else{
return objectMapper.readValue(response.getBody(), responseClass) ;
}
}
Same code is working for my local ,But in production it throws 400 Error and also there are no logs in payments.log file.
The Java version in production on my payment server is on 1.8.0_25 and server which is making these request are on 1.8.0_91.
I am unable to identify the reasons as there are no logs are present for this web request in payments.log
their is limit on header size on production.Because of that i am getting this issue and there are no logs in payments.log.
I have implemented a standard GCM client following the instructions on google developers page (Gcm implementation). Push messages have worked great no problem there. But then I implemented Robospice REST lib in the application and GCM stopped working. I am sure it does not work because of Robospice because as soon as I remove the code for SpiceManager GCM starts working.
API calls via Robospice Spring module work fine. This is my declaration of Robospice services:
enter<receiver
android:name="com.clover.spika.enterprise.chat.services.gcm.GcmBroadcastRe ceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.clover.spika.enterprise.chat.gcm" />
</intent-filter>
</receiver>
<service android:name="com.clover.spika.enterprise.chat.services.gcm.GcmIntentService" />
<service
android:name="com.clover.spika.enterprise.chat.services.robospice.Jackson2 SpiceService"
android:exported="false" />
<service android:name="com.clover.spika.enterprise.chat.services.custom.PoolingServ ice" /> code here
This is my custom spice service:
package com.clover.spika.enterprise.chat.services.robospice;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.ContentCodingType;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import android.app.Application;
import android.app.Notification;
import com.octo.android.robospice.SpringAndroidSpiceService;
import com.octo.android.robospice.persistence.CacheManager;
import com.octo.android.robospice.persistence.exception.CacheCreationException;
import com.octo.android.robospice.persistence.springandroid.json.jackson.JacksonO bjectPersisterFactory;
public class Jackson2SpiceService extends SpringAndroidSpiceService {
// private static final int WEBSERVICES_TIMEOUT = 10000;
#Override
public RestTemplate createRestTemplate() {
RestTemplate restTemplate = new RestTemplate() {
#Override
protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
ClientHttpRequest request = super.createRequest(url, method);
HttpHeaders headers = request.getHeaders();
headers.setAcceptEncoding(ContentCodingType.ALL);
return request;
}
};
// bug on http connection for Android < 2.2
// http://android-developers.blogspot.fr/2011/09/androids-http-clients.html
// but still a problem for upload with Spring-android on android 4.1
// System.setProperty("http.keepAlive", "false");
// // set timeout for requests
// ClientHttpRequestFactory factory = restTemplate.getRequestFactory();
// if (factory instanceof HttpComponentsClientHttpRequestFactory) {
// HttpComponentsClientHttpRequestFactory advancedFactory =
// (HttpComponentsClientHttpRequestFactory) factory;
// advancedFactory.setConnectTimeout(WEBSERVICES_TIMEOUT);
// advancedFactory.setReadTimeout(WEBSERVICES_TIMEOUT);
// } else if (factory instanceof SimpleClientHttpRequestFactory) {
// SimpleClientHttpRequestFactory advancedFactory =
// (SimpleClientHttpRequestFactory) factory;
// advancedFactory.setConnectTimeout(WEBSERVICES_TIMEOUT);
// advancedFactory.setReadTimeout(WEBSERVICES_TIMEOUT);
// }
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
// StringHttpMessageConverter stringHttpMessageConverter = new
// StringHttpMessageConverter();
List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
supportedMediaTypes.add(MediaType.TEXT_HTML);
supportedMediaTypes.add(MediaType.APPLICATION_JSON);
// stringHttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes);
jsonConverter.setSupportedMediaTypes(supportedMediaTypes);
final List<HttpMessageConverter<?>> listHttpMessageConverters = restTemplate.getMessageConverters();
listHttpMessageConverters.add(jsonConverter);
listHttpMessageConverters.add(formHttpMessageConverter);
// listHttpMessageConverters.add(stringHttpMessageConverter);
restTemplate.setMessageConverters(listHttpMessageConverters);
return restTemplate;
}
#Override
public CacheManager createCacheManager(Application application) throws CacheCreationException {
CacheManager cacheManager = new CacheManager();
JacksonObjectPersisterFactory jacksonObjectPersisterFactory = new JacksonObjectPersisterFactory(application);
cacheManager.addPersister(jacksonObjectPersisterFactory);
return cacheManager;
}
#Override
public Notification createDefaultNotification() {
return null;
}
}
Does anyone have any idea what could be the problem? I can post additional code if it is needed.
I have solved the issue, it was not robospice or gcm fault, it was a thing in our server handling.
The thing is that we read some values from User-Agent header that i was not aware of and i did not set it to the OkHttp client.
my JSF 2.0 web application is intended to produce PDF reports.
the problem is that no PDF report is shown up in the explorer window.
I am using eclipse kepler, with apache-tomcat-7.0.52 and the version of jasper Ireport is 4.8
any help would be appreciated.
I will provide the whole java class :
package khldqr.beans;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
#ManagedBean
#SessionScoped
public class TestReport {
private List<Refugee> refugee;
public List<Refugee> connectRefugeeData() {
ResultSet rs = null;
PreparedStatement pst = null;
Connection con = Database.getConnection();
String stm = "Select R_NO, F_P_Name from M_MAIN_INFO where R_NO < 10";
refugee = new ArrayList<Refugee>();
try {
pst = con.prepareStatement(stm);
pst.execute();
rs = pst.getResultSet();
while (rs.next()) {
Refugee refugeelist = new Refugee();
refugeelist.setR_NO(rs.getInt(1));
refugeelist.setF_P_Name(rs.getString(2));
refugee.add(refugeelist);
}
} catch (SQLException e) {
e.printStackTrace();
}
return refugee;
}
public void PDF(ActionEvent actionEvent) throws IOException, JRException {
System.out.println("this is not my lucky day!!!!!");
File jasper = new File(FacesContext.getCurrentInstance().getExternalContext().getRealPath("report/Majd.jasper"));
byte[] bytes = JasperRunManager.runReportToPdf(jasper.getPath(),null,new JRBeanCollectionDataSource(refugee));
HttpServletResponse response =(HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setContentType("application/pdf");
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(bytes, 0 , bytes.length);
outputStream.flush();
outputStream.close();
FacesContext.getCurrentInstance().responseComplete();
}
public TestReport() {
connectRefugeeData();
}
public List<Refugee> getRefugee() {
return refugee;
}
public void setRefugee(List<Refugee> refugee) {
this.refugee = refugee;
}
}
and here is xhtml file:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Hello To GOPA World!!</title>
</h:head>
<h:body dir="rtl">
<h:form>
<p:commandButton value = "PDF" actionListener="#{testReport.PDF}"></p:commandButton>
</h:form>
<h:dataTable value="#{testReport.refugee}" var="var">
<h:column>
<h:outputText value="#{var.r_NO}"></h:outputText>
</h:column>
<h:column >
<h:outputText value="#{var.f_P_Name}"></h:outputText>
</h:column>
</h:dataTable>
</h:body>
</html>
I can see the message on the console and the page gets refreshed but no PDF report is come up the explorer screen
I have replaced the above PDF method with the code below, but in vain, the same result: no PDF report is coming up the explorer screen.
JasperPrint jasperPrint;
public void init() throws JRException{
JRBeanCollectionDataSource beanCollectionDataSource=new JRBeanCollectionDataSource(refugee);
String reportPath= "e:\\Rita.jasper";
jasperPrint=JasperFillManager.fillReport(reportPath, new HashMap(),beanCollectionDataSource);
}
public void PDF(ActionEvent actionEvent) throws JRException, IOException{
init();
HttpServletResponse httpServletResponse=(HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
// httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pdf");
FacesContext.getCurrentInstance().getExternalContext().setResponseContentType("application/pdf");
ServletOutputStream servletOutputStream=httpServletResponse.getOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
System.out.println("All done the report is done");
servletOutputStream.flush();
servletOutputStream.close();
FacesContext.getCurrentInstance().responseComplete();
}
the code is correct, and there is nothing wrong with it.
the problem was some kind of security issue.
I faced the above problem when the report was in a full access folder to all users.
put when I put both of the requested xhtml and the report in a secured folder, everything went OK.
I don't know why!! but that was the case with me.
hoping others will make use of this.
thx.
<p:commandButton value = "PDF" actionListener="#{testReport.PDF}" ajax="false" type="submit"></p:commandButton>
you cant use ajax when calling jasperReports
I have a requirement to write a REST service to support a file upload; I'm using JBOSS / Resteasy / Jersey, as follows:
Server HTTP REST handler:
#Path("document")
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.TEXT_PLAIN)
public Response uploadFile(#FormDataParam("file") InputStream fileInputStream,
#FormDataParam("file") FormDataContentDisposition contentDispositionHeader,
#FormDataParam("selectedName") String selectedName,
#FormDataParam("name") String name,
#FormDataParam("notes") String notes) {
String documentId;
// upload the file
String filePath = SERVER_UPLOAD_LOCATION_FOLDER + contentDispositionHeader.getFileName();
try { fileUpload(fileInputStream, filePath);
}
catch (IOException e) { throw new ApplicationRuntimeException( "Unable to upload file: " + selectedName);
}
// create the document record
documentId = create(selectedName, name, notes);
return Response.ok("123456789").build();
}
Unit Test
In order to test the services I wrote the following unit test:
#Test
public void testCreateDocument() throws Exception {
Assert.assertNotNull(file);
Assert.assertTrue(file.canRead());
given()
.multiPart("notes", "my notes") .multiPart("selectedName", "selectedName")
.multiPart("name", "test.txt") .multiPart("file",file)
.contentType(MediaType.APPLICATION_OCTET_STREAM) .expect().body(equalTo("This is an uploaded test file."))
.when().post(DOCUMENT_URL);
}
The unit test fails. Following are the error message received by the unit test as well as the server logs
Unit Test Error Message
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
In addition, the following server logs are recorded when issuing the unit test above:
09:26:40,340 WARN [org.jboss.resteasy.core.ExceptionHandler] (http-/127.0.0.1:8080-7) failed to execute: javax.ws.rs.NotSupportedException: Could not find message body reader for type: class com.sun.jersey.core.header.FormDataContentDisposition of content type: multipart/form-data;boundary=J6UnCyDNsA50mzrPqDb2ctHPBb6fEpFJRF
at org.jboss.resteasy.core.interception.ServerReaderInterceptorContext.throwReaderNotFound(ServerReaderInterceptorContext.java:52) [resteasy-jaxrs-3.0.7.Final.jar:]
at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.getReader(AbstractReaderInterceptorContext.java:73) [resteasy-jaxrs-3.0.7.Final.jar:]
at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.proceed(AbstractReaderInterceptorContext.java:50) [resteasy-jaxrs-3.0.7.Final.jar:]
at org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor.aroundReadFrom(GZIPDecodingInterceptor.java:59) [resteasy-jaxrs-3.0.7.Final.jar:]
at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.proceed(AbstractReaderInterceptorContext.java:53) [resteasy-jaxrs-3.0.7.Final.jar:]
at org.jboss.resteasy.core.MessageBodyParameterInjector.inject(MessageBodyParameterInjector.java:150) [resteasy-jaxrs-3.0.7.Final.jar:]
at org.jboss.resteasy.core.MethodInjectorImpl.injectArguments(MethodInjectorImpl.java:89) [resteasy-jaxrs-3.0.7.Final.jar:]
at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:112) [resteasy-jaxrs-3.0.7.Final.jar:]
at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:288) [resteasy-jaxrs-3.0.7.Final.jar:]
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:242) [resteasy-jaxrs-3.0.7.Final.jar:]
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:229) [resteasy-jaxrs-3.0.7.Final.jar:]
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:356) [resteasy-jaxrs-3.0.7.Final.jar:]
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:179) [resteasy-jaxrs-3.0.7.Final.jar:]
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:220) [resteasy-jaxrs-3.0.7.Final.jar:]
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56) [resteasy-jaxrs-3.0.7.Final.jar:]
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51) [resteasy-jaxrs-3.0.7.Final.jar:]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.2.Final-redhat-1.jar:1.0.2.Final-redhat-1]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:295) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:149) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:169) [jboss-as-web-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:145) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:97) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:102) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:336) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:653) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:920) [jbossweb-7.2.2.Final-redhat-1.jar:7.2.2.Final-redhat-1]
at java.lang.Thread.run(Thread.java:744) [rt.jar:1.7.0_45]
I searched all over for references to the Could not find message body reader for type: class com.sun.jersey.core.header.FormDataContentDisposition of content type: multipart/form-data error but have not been able to find anything helpfull.
I had the same issue and to fix it I have used the solution described in volkerbenders repository. Here is the solution that have worked for me:
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>3.0.11.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-multipart-provider</artifactId>
<version>3.0.11.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>3.0.11.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
And this is the resource class:
import org.apache.commons.io.IOUtils;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
#Path("/file")
public class FileResource {
public static final String UPLOADED_FILE_PARAMETER_NAME = "file";
#Path("/upload")
#POST
#Consumes("multipart/form-data")
public Response uploadFile(MultipartFormDataInput input) {
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
List<InputPart> inputParts = uploadForm.get(UPLOADED_FILE_PARAMETER_NAME);
for (InputPart inputPart : inputParts) {
MultivaluedMap<String, String> headers = inputPart.getHeaders();
try {
InputStream inputStream = inputPart.getBody(InputStream.class, null);
byte[] bytes = IOUtils.toByteArray(inputStream);
String filename = getFileName(headers);
//TODO: HERE you do whatever you want to do with the file
//...
} catch (IOException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
return Response.status(Response.Status.OK).build();
}
private String getFileName(MultivaluedMap<String, String> headers) {
String[] contentDisposition = headers.getFirst("Content-Disposition").split(";");
for (String filename : contentDisposition) {
if ((filename.trim().startsWith("filename"))) {
String[] name = filename.split("=");
String finalFileName = sanitizeFilename(name[1]);
return finalFileName;
}
}
return "unknown";
}
private String sanitizeFilename(String s) {
return s.trim().replaceAll("\"", "");
}
}
Jersey is unnecessary in this context to support file uploads via multi-part POST. RESTEasy supports multi-part POST request processing in a different way.
Using Jersey is also the reason why you're seeing the warning in the first place - I suspect some classes (especially the FormDataContentDisposition class from Jersey and it's related classes are not accessible to the RESTEasy module in the JBoss application server. Just don't complicate things by adding in two JAX-RS providers without understanding the JBoss module system; this is pointless.
I have a problem to upload files larger than 1mb the FileUploadEvent is not called, for smaller files works normally.
Web.xml:
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
<init-param>
<param-name>thresholdSize</param-name>
<param-value>52428800</param-value>
</init-param>
<init-param>
<param-name>uploadDirectory</param-name>
<param-value>D:\</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
ManagedBean:
#ManagedBean
#RequestScoped
public class TesteUpload {
public void handleFileUpload(FileUploadEvent event) {
UploadedFile uploadedFile = event.getFile();
File file = new File(PropertiesLoader.getInstance().getPropertie(PropertiesLoader.PATCH_MIDIA), uploadedFile.getFileName());
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte[] buffer = new byte[6124];
int bulk;
InputStream inputStream = event.getFile().getInputstream();
while (true) {
bulk = inputStream.read(buffer);
if (bulk < 0) {
break;
}
fileOutputStream.write(buffer, 0, bulk);
fileOutputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
FacesMessage error = new FacesMessage("Erro!!");
FacesContext.getCurrentInstance().addMessage(null, error);
}
}
}
Page:
<ui:composition template="/public/templates/master.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<ui:define name="divMainPublic">
<h:form enctype="multipart/form-data">
<p:fileUpload fileUploadListener="#{testeUpload.handleFileUpload}" mode="advanced" sizeLimit="51380224" />
</h:form>
</ui:define>
I am using;
commons-fileupload-1.2.2
commons-io-2.3
primefaces-4.0
jsf 2.2
I shall give you the answer, 2 years later... lol
Change the "Max Post Size" in your web server.
If you use Glassfish:
Configurations - > network config -> listner -> http -> "Max Post Size"
This problem haunted me for 3 months.
Uploaded files are saved in D drive. It works.
Update handleFileUpload method with below code
public void handleFileUpload(FileUploadEvent event) {
try {
UploadedFile file = event.getFile();
InputStream inputStream = file.getInputstream();
OutputStream outputStream = new FileOutputStream("D:/"+ file.getFileName());
byte[] bytes = file.getContents();
int read = 0;
while ((read = inputStream.read(bytes)) != -1 ) {
outputStream.write(bytes, 0, read);
}
inputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}