Primefaces fileUpload not work to file size > 1Mb. - file-upload

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();
}
}

Related

Providing security to JAX-RS Web Service

Our project implemented using WAS Server 8.5/Struts 2 application.
javax.ws.rs.core.SecurityContext is just an interface.
Which can be used as below.
#javax.ws.rs.GET
#javax.ws.rs.Path("/{abc}")
#javax.ws.rs.Produces(MediaType.APPLICATION_XML)
#Secured
public List<Object> getReport(#PathParam("abc") String abc,#Context SecurityContext securityContext) {
System.out.println("securityContext.isSecure() "+securityContext.isSecure());
if(securityContext.isSecure()!=true){
throw new SecurityException("User is unauthorized.");
}
}
My servlet configuration file looks like this.
<servlet>
<servlet-name>JAXRSRestConfig</servlet-name>
<servlet-class>com.ibm.websphere.jaxrs.server.IBMRestServlet</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.ubs.gsp.rest.RestWebAppConfig</param-value>
</init-param>
<init-param>
<param-name>javax.ws.rs.container.ContainerRequestFilter</param-name>
<param-value>com.ubs.gsp.rest.AuthenticationFilter</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<security-constraint>
<web-resource-collection>
<web-resource-name>RestWebServiceResource</web-resource-name>
<url-pattern>/rest/*</url-pattern>
</web-resource-collection>
<!-- <auth-constraint>
<role-name>ADMIN</role-name>
</auth-constraint> -->
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
<servlet-mapping>
<servlet-name>JAXRSRestConfig</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
AuthenticationFilter class:
#Provider
#Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {
#Context
private ResourceInfo resourceInfo;
private static final String AUTHORIZATION_PROPERTY = "Authorization";
private static final String AUTHENTICATION_SCHEME = "Basic";
private static final Response ACCESS_DENIED = Response.status(Response.Status.UNAUTHORIZED)
.entity("You cannot access this resource").build();
private static final Response ACCESS_FORBIDDEN = Response.status(Response.Status.FORBIDDEN)
.entity("Access blocked for all users !!").build();
#Override
public void filter(ContainerRequestContext requestContext)
{
System.out.println("filter ContainerRequestContext");
Method method = resourceInfo.getResourceMethod();
//Access allowed for all
if( ! method.isAnnotationPresent(PermitAll.class))
{
//Access denied for all
if(method.isAnnotationPresent(DenyAll.class))
{
requestContext.abortWith(ACCESS_FORBIDDEN);
return;
}
//Get request headers
final MultivaluedMap<String, String> headers = requestContext.getHeaders();
//Fetch authorization header
final List<String> authorization = headers.get(AUTHORIZATION_PROPERTY);
//If no authorization information present; block access
if(authorization == null || authorization.isEmpty())
{
requestContext.abortWith(ACCESS_DENIED);
return;
}
//Get encoded username and password
final String encodedUserPassword = authorization.get(0).replaceFirst(AUTHENTICATION_SCHEME + " ", "");
//Decode username and password
//String usernameAndPassword = new String(Base64.decode(encodedUserPassword.getBytes()));;
String usernameAndPassword = new String(Base64.decode(encodedUserPassword));;
//Split username and password tokens
final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
final String username = tokenizer.nextToken();
final String password = tokenizer.nextToken();
//Verifying Username and password
System.out.println(username);
System.out.println(password);
//Verify user access
if(method.isAnnotationPresent(RolesAllowed.class))
{
RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
Set<String> rolesSet = new HashSet<String>(Arrays.asList(rolesAnnotation.value()));
//Is user valid?
if( ! isUserAllowed(username, password, rolesSet))
{
requestContext.abortWith(ACCESS_DENIED);
return;
}
}
}
}
private boolean isUserAllowed(final String username, final String password, final Set<String> rolesSet)
{
System.out.println("filter isUserAllowed");
boolean isAllowed = false;
//Step 1. Fetch password from database and match with password in argument
//If both match then get the defined role for user from database and continue; else return isAllowed [false]
//Access the database and do this part yourself
//String userRole = userMgr.getUserRole(username);
if(username.equals("password") && password.equals("password"))
{
isAllowed = true;
}
return isAllowed;
}
}
All the authentication related code goes into AuthenticationFilter class.
I need some idea about registering AuthenticationFilter to our project.
Whenever getReport() method is called, AuthenticationFilter should be intercepted for security purposes. How to do it?
Any help really appreciated!!

How to implement Generate Jasper Report PDF on button click in Liferay Portal 6.1

I have a requirement to provide report generation functionality on a button click. I am using Liferay Portal 6.1 with Tomcat 7 as web portal, Liferay Developer Studio (Eclipse Indigo) IDE, iReport (to create report template), and JasperReports library to produce the PDF. The portal is a ticket management system with two entities (Tickets and Documents) which are entered via their respective custom portlets. Both entities, when in edit mode, need the 'View Report' function. I have searched for answers to this problem extensively, picking up a snippet here and there, but nothing I have found is exactly my situation. Upon clicking the 'View Report' button, the user needs to be presented with a formatted PDF where the user can then decide to 'Save', 'Print', or 'Close' from. I also need to pass data to the report so information can be retrieved for the entity that is open (i.e., documentId, ticketId, docType, etc.), but this piece can be added later; once I just get a PDF to open.
Not knowing how to go about implementing this, I decided to use a jQuery Modal to open 'viewReport.jsp' page and process the report there. However, this approach yields a JRException IllegalState: cannot obtain OutputStream because writer is already in use. I have read in my searches that Liferay layout uses OutputStream and that's probably why the writer is already in use. Here's the code I am using:
edit_document.jsp (button and jQuery Modal)
<!-- View Report Button at bottom of form -->
<aui:button type="button" id="viewReportBtn" value="View Report" />
<!-- URL declaration for PDF popup window -->
<portlet:renderURL var="viewReportURL" windowState="<%= LiferayWindowState.EXCLUSIVE.toString() %>" >
<portlet:param name="mvcPath" value="/html/document/viewReport.jsp" />
<portlet:param name="documentId" value="<%= Long.toString(documentID) %>" />
<portlet:param name="ticketId" value="<%= Long.toString(ticketID) %>: />
<portlet:param name="docType" value="<%= docType %>" /> <!-- This is already a String value -->
</portlet:renderURL>
<!-- jQuery to open popup window for PDF -->
<aui:script use="aui-dialog, aui-overlay-manager, dd-constrain" >
var reportDialogOptions = {
title : 'Dialog',
bodyContent : '',
centered : true,
group : default,
height : 800,
width : 1000,
modal : true,
};
$('#viewReportBtn').on('click', finction(event) {
var editFeelingDialog = new A.Dialog(
A.merge(reportDialogOptions, {
title : 'Document View Report'
})
).plugin(A.Plugin.IO,{uri : '<%= viewReportURL %>'}).render();
});
</aui:script>
viewReport.jsp (page to process jrxml template and open PDF)
<!-- viewReport.jsp page to render PDF -->
<%# page contentType = "application/pdf" %>
<%# page trimDirectiveWhitespaces = "true" %>
<%# page import = "net.sf.jasperreports.engine.*" %>
<%# page import = "java.io.File" %>
<%# page import = "java.io.FileInputStream" %>
<%# page import = "java.io.FileNotFoundException" %>
<%# page import = "java.io.InputStream" %>
<%# page import = "java.sql.Connection" %>
<%# page import = "java.sql.SQLException" %>
<%
Connection conn = null;
try
{
String url = "jdbc:oracle:thin:#myDBSRV:1521:myDatabase";
String userName = "myUsername";
String password = "myPassword";
// Connecting to the Oracle database
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, username, password);
// Loading the Jasper Report file from local file system\
String jrxmlFile = session.getServletContext().getRealPath(request.getContextPath())+"\\report5.jrxml";
InputStream input = new FileInputStream(new File(jrxmlFile));
// Generate the report
JasperReport jasperReport = JasperCompileManager.compileReport(input);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPrint, null, conn);
// Export the report as a PDF
JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
}
catch (FileNotFoundExcecption ex)
{
System.out.println(ex.getMessage());
ex.printStakeTrace();
}
catch (JRException ex)
{
System.out.println(ex.getMessage());
ex.printStakeTrace();
}
catch (ClassNotFoundException ex)
{
System.out.println(ex.getMessage());
ex.printStakeTrace();
}
catch (SQLException ex)
{
System.out.println(ex.getMessage());
ex.printStakeTrace();
}
finally
{
if (conn != null)
{
conn.close();
}
}
%>
I also tried to add java methods to my DocumentPortlet.java class and call the method(s) when the button is clicked, but I am not that familiar enough with ajax to get it right:
DocumentPortlet.java
public class DocumentPortlet extends MVCPortlet{
Connection conn = null;
// More methods for saving, editing, and deleting documents are here...
public void generateReport()
{
initConnection();
showReport();
}
public void initConnection()
{
String host = "jdbc:oracle:thin:#ncimsdbsrv:1521:ncimsdev";
String userName = "lportal";
String password = "NSS4207itnp";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
try
{
conn = DriverManager.getConnection(host, userName, password);
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
public void showReport()
{
//Path to your .jrxml file
String reportName = "[path to file]";
//Get a stream to read the file
InputStream is = this.getClass().getClassLoader().getResourceAsStream(reportName);
try
{
//Fill the report with parameter, connection, and stream reader
JasperPrint jp = JasperFillManager.fillReport(is, null, session);
//Viewer for Jasper report
JRViewer jv = new JRViewer(jp);
//Insert viewer to a JFrame to make it showable
JFrame jf = new JFrame();
jf.getContentPane().add(jv);
jf.validate();
jf.setVisible(true);
jf.setSize(new Dimension(800, 600));
jf.setLocation(300, 100);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
catch (JRException ex)
{
ex.printStakeTrace();
}
finally
{
closeSession(session);
}
}
}
How can I provide this functionality in a way that my users can click the button and a PDF be generated on their screen? I need a clear and concise solution to this problem. Thank you!
Lee
In case anyone is interested, I found an answer on a Liferay forum. My implementation was not correct. So now I have this in my
viewDocument.jsp:
<!-- View Report button at bottom of form -->
<aui:button id="viewReportBtn" value="View Report" />
<!-- URL declaration for PDF generation -->
<portlet:resourceURL id="generatePDF" var="generateReportURL" >
<portlet:param name="jspPage" value="/html/document/viewReport.jsp" />
<portlet:param name="docType" value="<%= docType %>" />
</portlet:resourceURL>
<!-- AJAX call to resource request handler in DocumentPortlet.java file -->
<aui:script use="aui-dialog, aui-overlay-manager, dd-constrain" >
$(document).ready(function()
{
$('#viewReportBtn').click(function(event)
{
$.ajax('<%= generateReportURL %>');
}
});
I also created the ResourceRequestHandler in my Portlet java file like so:
DocumentPortlet.java:
public class DocumentPortlet extends MVCPortlet{
Connection conn = null;
// More methods to add, update, and delete here
#Override
public void serveResource(ResourceRequest request, ResourceResponse response)
throws IOException, PortletException
{
String url = "jdbc:oracle:thin:#myDatabaseSrv:1521:myDatabaseSid";
String user = "myUserName";
String pass = "myPassword";
String docType = ParamUtil.getString(request, "docType");
try
{
// Connect to database
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, user, pass);
// Load JRXml file from local file system
String jrxmlFile = "C:\\Reports\\report5.jrxml";
InputStream input = new FileInputStream(new File(jrxmlFile));
// Generate report
JasperReport jasperReport = JasperCompileManager.compileReport(input);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPrint, null, conn);
/***** Display PDF in Adobe Reader *****/
// Create new OutputStream where data is written to byte array[]
ByteArrayOutputStream output = new ByteArrayOutputStream();
// Export the report to PDF format
JasperExportManager.exportReportToPdfStream(jasperPrint, output);
// Create a String for thr report title
final String fileName = docType + ".pdf";
//Create a new stream and call the report
OutputStream pdfFile = new FileOutputStream(new File(fileName));
//Write the PDF
pdfFile.write(output.toByteArray());
//Clean the PDF
pdfFile.flush();
//Close it
pdfFile.close();
//Run the brand new PDF report
final String PDF_RUN = "rundll32 url.dll, FileProtocolHandaler " + fileName;
//Execute the command
Runtime.getRuntime().exec(PDF_RUN);
}
catch(FileNotFoundException ex)
{
System.out.println("File not found on file system, check file path!!" + ex.getMessage());
ex.printStackTrace();
}
catch(JRException ex)
{
System.out.println("Error in Jasper Report!!" + ex.getMessage());
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
System.out.println("Oracle Class for driver not found!!" + ex.getMessage());
ex.printStackTrace();
}
catch(SQLException ex)
{
System.out.println("Error getting connection to database!!" + ex.getMessage());
ex.printStackTrace();
}
}
}
This eliminated the IllegalStateException I was getting and will open the pdf in Adobe Reader just fine, however, it opens it up on the server. Therefore, a problem still remains. Anybody know how I can get this pdf to open on the client machine?

NullPointerException at setCharacterEncoding(UploadRequestWrapper.java:83)

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

How to upload file of p:fileUpload using command button instead of upload button

Iam using JSF2.1 along with primefaces for uploading file.In my application i have to add the file dynamically on creating a record.But when i use
i cant write the code for uploading my file during save.I want the file to be uploaded on click of save only and not during upload.
Can anyone help me how to implement this
public String handleFileUpload(FileUploadEvent event) throws IOException {
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
UploadedFile file = event.getFile();
String prefix = FilenameUtils.getBaseName(file.getFileName());
String suffix = FilenameUtils.getExtension(file.getFileName());
String path = "C:/apache-tomcat-7.0.47/webapps/ROOT/WEB-INF/images";
ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
File fileToDirectory = File.createTempFile(prefix + "-", "." + suffix, new File(path));
InputStream inputStream = event.getFile().getInputstream();
String fileName = event.getFile().getFileName();
OutputStream outputStream = new FileOutputStream(fileToDirectory);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inputStream.read(buffer)) > 0){
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
return path+fileName;
}
I need to have this code on save but i cant get event during save
That isn't possible with auto mode. Use the basic mode instead. Then you can bind the input value to an UploadedFile property directly. This only requires disabling Ajax.
E.g.
<h:form enctype="multipart/form-data">
...
<p:fileUpload mode="simple" value="#{bean.file}" />
...
<p:commandButton value="Save" action="#{bean.save}" ajax="false" />
</h:form>
with
private UploadedFile file; // +getter+setter
public void save() {
try (InputStream input = file.getInputStream()) {
// ...
}
}
The alternative is to migrate to standard JSF <h:inputFile> component which was introduced in JSF 2.2. Then you can continue using Ajax.
E.g.
<h:form enctype="multipart/form-data">
...
<h:inputFile value="#{bean.file}" />
...
<p:commandButton value="Save" action="#{bean.save}" />
</h:form>
with
private Part file; // +getter+setter
public void save() {
try (InputStream input = file.getInputStream()) {
// ...
}
}
See also:
How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?

I'm stuck on file upload (allways not accpting uploading)

I'm stuck ... I followed several tutorial but I do not know what's my problem ... I need to uplod files in the Repertoir C: \ PDF
but I do not get to do
this is my
<h:form enctype="multipart/form-data">
<p:fileUpload
mode="advanced"
fileUploadListener="#{composantbean.upload}"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/" sizeLimit="100000" description="Select Images"
auto="true"/>
</h:form>
this is my methode on bean
#ManagedBean(name="composantbean")
#SessionScoped
public class Composantbeam {
private String destination="C:\\PDF\\";
public void upload(FileUploadEvent event) {
FacesMessage msg = new FacesMessage("Success! ", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
// Do what you want with the file
try {
copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void copyFile(String fileName, InputStream in) {
try {
// write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(new File(destination + fileName));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
in.close();
out.flush();
out.close();
System.out.println("New file created!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
this is my error message it allaws shown when a upload a file
C:\PDF\C:\Documents and Settings\Admin\Bureau\login.png (Syntaxe du nom de fichier, de répertoire ou de volume incorrecte)
C: \ PDF \ C: \ Documents and Settings \ Admin \ Desktop \ login.png (syntax file name, directory or incorrect volume)
The problem is that event.getFile().getFileName() is returning filename with complete path
so I change My methode Like this
File result = new File(destination+ ***FilenameUtils.getName***(event.getFile().getFileName()));
Commons IO offers FilenameUtils#getName() for the exact purpose.
think you all :)