List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setHeaderEncoding
public void setHeaderEncoding(String encoding)
From source file:org.guvnor.m2repo.backend.server.FileServlet.java
/** * Get the form data from the inbound request. *//*ww w .j a v a2 s . c om*/ @SuppressWarnings("rawtypes") public static FormData getFormData(HttpServletRequest request) throws IOException { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); FormData data = new FormData(); GAV emptyGAV = new GAV(); try { List items = upload.parseRequest(request); Iterator it = items.iterator(); while (it.hasNext()) { FileItem item = (FileItem) it.next(); if (!item.isFormField()) { data.setFile(item); } if (item.isFormField() && item.getFieldName().equals(HTMLFileManagerFields.GROUP_ID)) { System.out.println("GROUP_ID:" + item.getString()); emptyGAV.setGroupId(item.getString()); } else if (item.isFormField() && item.getFieldName().equals(HTMLFileManagerFields.ARTIFACT_ID)) { System.out.println("ARTIFACT_ID:" + item.getString()); emptyGAV.setArtifactId(item.getString()); } else if (item.isFormField() && item.getFieldName().equals(HTMLFileManagerFields.VERSION_ID)) { System.out.println("VERSION_ID:" + item.getString()); emptyGAV.setVersion(item.getString()); } } if (emptyGAV.getArtifactId() == null || "".equals(emptyGAV.getArtifactId()) || emptyGAV.getArtifactId() == null || "".equals(emptyGAV.getArtifactId()) || emptyGAV.getVersion() == null || "".equals(emptyGAV.getVersion())) { data.setGav(null); } else { data.setGav(emptyGAV); } return data; } catch (FileUploadException e) { //TODO //throw new RulesRepositoryException( e ); } return null; }
From source file:org.guvnor.m2repo.backend.server.helpers.HttpPostHelper.java
@SuppressWarnings("rawtypes") private FormData extractFormData(final HttpServletRequest request) throws IOException { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); FormData data = new FormData(); GAV emptyGAV = new GAV(); try {/*from www .j av a 2 s . c o m*/ List items = upload.parseRequest(request); Iterator it = items.iterator(); while (it.hasNext()) { FileItem item = (FileItem) it.next(); if (!item.isFormField()) { data.setFile(item); } if (item.isFormField() && item.getFieldName().equals(HTMLFileManagerFields.GROUP_ID)) { emptyGAV.setGroupId(item.getString()); } else if (item.isFormField() && item.getFieldName().equals(HTMLFileManagerFields.ARTIFACT_ID)) { emptyGAV.setArtifactId(item.getString()); } else if (item.isFormField() && item.getFieldName().equals(HTMLFileManagerFields.VERSION_ID)) { emptyGAV.setVersion(item.getString()); } } if (isNullOrEmpty(emptyGAV.getGroupId()) || isNullOrEmpty(emptyGAV.getArtifactId()) || isNullOrEmpty(emptyGAV.getVersion())) { data.setGav(null); } else { data.setGav(emptyGAV); } return data; } catch (FileUploadException e) { log.error(e.getMessage(), e); } return null; }
From source file:org.jahia.ajax.gwt.content.server.GWTFileManagerUploadServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); SettingsBean settingsBean = SettingsBean.getInstance(); final long fileSizeLimit = settingsBean.getJahiaFileUploadMaxSize(); upload.setHeaderEncoding("UTF-8"); Map<String, FileItem> uploads = new HashMap<String, FileItem>(); String location = null;//from w ww . ja v a 2 s . c o m String type = null; boolean unzip = false; response.setContentType("text/plain; charset=" + settingsBean.getCharacterEncoding()); final PrintWriter printWriter = response.getWriter(); try { FileItemIterator itemIterator = upload.getItemIterator(request); FileSizeLimitExceededException sizeLimitExceededException = null; while (itemIterator.hasNext()) { final FileItemStream item = itemIterator.next(); if (sizeLimitExceededException != null) { continue; } FileItem fileItem = factory.createItem(item.getFieldName(), item.getContentType(), item.isFormField(), item.getName()); long contentLength = getContentLength(item.getHeaders()); // If we have a content length in the header we can use it if (fileSizeLimit > 0 && contentLength != -1L && contentLength > fileSizeLimit) { throw new FileSizeLimitExceededException("The field " + item.getFieldName() + " exceeds its maximum permitted size of " + fileSizeLimit + " bytes.", contentLength, fileSizeLimit); } InputStream itemStream = item.openStream(); InputStream limitedInputStream = null; try { limitedInputStream = fileSizeLimit > 0 ? new LimitedInputStream(itemStream, fileSizeLimit) { @Override protected void raiseError(long pSizeMax, long pCount) throws IOException { throw new FileUploadIOException(new FileSizeLimitExceededException( "The field " + item.getFieldName() + " exceeds its maximum permitted size of " + fileSizeLimit + " bytes.", pCount, pSizeMax)); } } : itemStream; Streams.copy(limitedInputStream, fileItem.getOutputStream(), true); } catch (FileUploadIOException e) { if (e.getCause() instanceof FileSizeLimitExceededException) { if (sizeLimitExceededException == null) { sizeLimitExceededException = (FileSizeLimitExceededException) e.getCause(); } } else { throw e; } } finally { IOUtils.closeQuietly(limitedInputStream); } if ("unzip".equals(fileItem.getFieldName())) { unzip = true; } else if ("uploadLocation".equals(fileItem.getFieldName())) { location = fileItem.getString("UTF-8"); } else if ("asyncupload".equals(fileItem.getFieldName())) { String name = fileItem.getName(); if (name.trim().length() > 0) { uploads.put(extractFileName(name, uploads), fileItem); } type = "async"; } else if (!fileItem.isFormField() && fileItem.getFieldName().startsWith("uploadedFile")) { String name = fileItem.getName(); if (name.trim().length() > 0) { uploads.put(extractFileName(name, uploads), fileItem); } type = "sync"; } } if (sizeLimitExceededException != null) { throw sizeLimitExceededException; } } catch (FileUploadBase.FileSizeLimitExceededException e) { printWriter.write("UPLOAD-SIZE-ISSUE: " + getSizeLimitErrorMessage(fileSizeLimit, e, request) + "\n"); return; } catch (FileUploadIOException e) { if (e.getCause() != null && (e.getCause() instanceof FileSizeLimitExceededException)) { printWriter.write("UPLOAD-SIZE-ISSUE: " + getSizeLimitErrorMessage(fileSizeLimit, (FileSizeLimitExceededException) e.getCause(), request) + "\n"); } else { logger.error("UPLOAD-ISSUE", e); printWriter.write("UPLOAD-ISSUE: " + e.getLocalizedMessage() + "\n"); } return; } catch (FileUploadException e) { logger.error("UPLOAD-ISSUE", e); printWriter.write("UPLOAD-ISSUE: " + e.getLocalizedMessage() + "\n"); return; } if (type == null || type.equals("sync")) { response.setContentType("text/plain"); final JahiaUser user = (JahiaUser) request.getSession().getAttribute(Constants.SESSION_USER); final List<String> pathsToUnzip = new ArrayList<String>(); for (String fileName : uploads.keySet()) { final FileItem fileItem = uploads.get(fileName); try { StringBuilder name = new StringBuilder(fileName); final int saveResult = saveToJcr(user, fileItem, location, name); switch (saveResult) { case OK: if (unzip && fileName.toLowerCase().endsWith(".zip")) { pathsToUnzip.add( new StringBuilder(location).append("/").append(name.toString()).toString()); } printWriter.write("OK: " + UriUtils.encode(name.toString()) + "\n"); break; case EXISTS: storeUploadedFile(request.getSession().getId(), fileItem); printWriter.write("EXISTS: " + UriUtils.encode(fileItem.getFieldName()) + " " + UriUtils.encode(fileItem.getName()) + " " + UriUtils.encode(fileName) + "\n"); break; case READONLY: printWriter.write("READONLY: " + UriUtils.encode(fileItem.getFieldName()) + "\n"); break; default: printWriter.write("UPLOAD-FAILED: " + UriUtils.encode(fileItem.getFieldName()) + "\n"); break; } } catch (IOException e) { logger.error("Upload failed for file \n", e); } finally { fileItem.delete(); } } // direct blocking unzip if (unzip && pathsToUnzip.size() > 0) { try { ZipHelper zip = ZipHelper.getInstance(); //todo : in which workspace do we upload ? zip.unzip(pathsToUnzip, true, JCRSessionFactory.getInstance().getCurrentUserSession(), (Locale) request.getSession().getAttribute(Constants.SESSION_UI_LOCALE)); } catch (RepositoryException e) { logger.error("Auto-unzipping failed", e); } catch (GWTJahiaServiceException e) { logger.error("Auto-unzipping failed", e); } } } else { response.setContentType("text/html"); for (FileItem fileItem : uploads.values()) { storeUploadedFile(request.getSession().getId(), fileItem); printWriter.write("<html><body>"); printWriter.write("<div id=\"uploaded\" key=\"" + fileItem.getName() + "\" name=\"" + fileItem.getName() + "\"></div>\n"); printWriter.write("</body></html>"); } } }
From source file:org.javalite.activeweb.HttpSupport.java
/** * Returns a collection of uploaded files from a multi-part port request. * * @param encoding specifies the character encoding to be used when reading the headers of individual part. * When not specified, or null, the request encoding is used. If that is also not specified, or null, * the platform default encoding is used. * @param maxFileSize maximum file size in the upload in bytes. -1 indicates no limit. * * @return a collection of uploaded files from a multi-part port request. *///from w ww . ja va2 s . com protected Iterator<FormItem> uploadedFiles(String encoding, long maxFileSize) { HttpServletRequest req = Context.getHttpRequest(); Iterator<FormItem> iterator; if (req instanceof AWMockMultipartHttpServletRequest) {//running inside a test, and simulating upload. iterator = ((AWMockMultipartHttpServletRequest) req).getFormItemIterator(); } else { if (!ServletFileUpload.isMultipartContent(req)) throw new ControllerException( "this is not a multipart request, be sure to add this attribute to the form: ... enctype=\"multipart/form-data\" ..."); ServletFileUpload upload = new ServletFileUpload(); if (encoding != null) upload.setHeaderEncoding(encoding); upload.setFileSizeMax(maxFileSize); try { FileItemIterator it = upload.getItemIterator(Context.getHttpRequest()); iterator = new FormItemIterator(it); } catch (Exception e) { throw new ControllerException(e); } } return iterator; }
From source file:org.javalite.activeweb.HttpSupport.java
/** * Returns a collection of uploaded files and form fields from a multi-part request. * This method uses <a href="http://commons.apache.org/proper/commons-fileupload/apidocs/org/apache/commons/fileupload/disk/DiskFileItemFactory.html">DiskFileItemFactory</a>. * As a result, it is recommended to add the following to your web.xml file: * * <pre>//from w w w . j a va2 s . c o m * <listener> * <listener-class> * org.apache.commons.fileupload.servlet.FileCleanerCleanup * </listener-class> * </listener> *</pre> * * For more information, see: <a href="http://commons.apache.org/proper/commons-fileupload/using.html">Using FileUpload</a> * * The size of upload defaults to max of 20mb. Files greater than that will be rejected. If you want to accept files * smaller of larger, create a file called <code>activeweb.properties</code>, add it to your classpath and * place this property to the file: * * <pre> * #max upload size * maxUploadSize = 20000000 * </pre> * * @param encoding specifies the character encoding to be used when reading the headers of individual part. * When not specified, or null, the request encoding is used. If that is also not specified, or null, * the platform default encoding is used. * * @return a collection of uploaded files from a multi-part request. */ protected List<FormItem> multipartFormItems(String encoding) { //we are thread safe, because controllers are pinned to a thread and discarded after each request. if (formItems != null) { return formItems; } HttpServletRequest req = Context.getHttpRequest(); if (req instanceof AWMockMultipartHttpServletRequest) {//running inside a test, and simulating upload. formItems = ((AWMockMultipartHttpServletRequest) req).getFormItems(); } else { if (!ServletFileUpload.isMultipartContent(req)) throw new ControllerException( "this is not a multipart request, be sure to add this attribute to the form: ... enctype=\"multipart/form-data\" ..."); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(Configuration.getMaxUploadSize()); factory.setRepository(Configuration.getTmpDir()); ServletFileUpload upload = new ServletFileUpload(factory); if (encoding != null) upload.setHeaderEncoding(encoding); upload.setFileSizeMax(Configuration.getMaxUploadSize()); try { List<org.apache.commons.fileupload.FileItem> apacheFileItems = upload .parseRequest(Context.getHttpRequest()); formItems = new ArrayList<>(); for (FileItem apacheItem : apacheFileItems) { ApacheFileItemFacade f = new ApacheFileItemFacade(apacheItem); if (f.isFormField()) { formItems.add(new FormItem(f)); } else { formItems.add(new org.javalite.activeweb.FileItem(f)); } } return formItems; } catch (Exception e) { throw new ControllerException(e); } } return formItems; }
From source file:org.jbpm.console.ng.documents.backend.server.DocumentViewServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {//from w w w. ja va 2 s.co m FileItem file = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); List items = upload.parseRequest(request); Iterator it = items.iterator(); String folder = "/"; while (it.hasNext()) { FileItem item = (FileItem) it.next(); if (!item.isFormField()) { file = item; } else { if ("documentFolder".equals(item.getFieldName())) { folder = item.getString(); } } } response.getWriter().write(processUpload(file, folder)); response.setContentType("text/html"); } catch (Exception e) { } }
From source file:org.jessma.util.http.FileUploader.java
private ServletFileUpload getFileUploadComponent() { DiskFileItemFactory dif = new DiskFileItemFactory(); if (factorySizeThreshold != DEFAULT_SIZE_THRESHOLD) dif.setSizeThreshold(factorySizeThreshold); if (factoryRepository != null) dif.setRepository(new File(factoryRepository)); if (factoryCleaningTracker != null) dif.setFileCleaningTracker(factoryCleaningTracker); ServletFileUpload sfu = new ServletFileUpload(dif); if (sizeMax != NO_LIMIT_SIZE_MAX) sfu.setSizeMax(sizeMax);//w w w. java2s. c o m if (fileSizeMax != NO_LIMIT_FILE_SIZE_MAX) sfu.setFileSizeMax(fileSizeMax); if (servletHeaderencoding != null) sfu.setHeaderEncoding(servletHeaderencoding); if (servletProgressListener != null) sfu.setProgressListener(servletProgressListener); return sfu; }
From source file:org.kie.guvnor.dtablexls.backend.server.FileServlet.java
/** * Get the form data from the inbound request. *//*from ww w. j a va 2 s.c om*/ @SuppressWarnings("rawtypes") public static FormData getFormData(HttpServletRequest request) throws IOException { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); FormData data = new FormData(); try { List items = upload.parseRequest(request); Iterator it = items.iterator(); while (it.hasNext()) { FileItem item = (FileItem) it.next(); if (!item.isFormField()) { data.setFile(item); } if (item.isFormField() && item.getFieldName().equals(HTMLFileManagerFields.FORM_FIELD_PATH)) { System.out.println("path:" + item.getString()); data.setPath(item.getString()); } else if (item.isFormField() && item.getFieldName().equals(HTMLFileManagerFields.FORM_FIELD_NAME)) { System.out.println("name:" + item.getString()); data.setFileName(item.getString()); } else if (item.isFormField() && item.getFieldName().equals(HTMLFileManagerFields.FORM_FIELD_FULL_PATH)) { System.out.println("name:" + item.getString()); data.setFullPath(item.getString()); } } return data; } catch (FileUploadException e) { //TODO //throw new RulesRepositoryException( e ); } return null; }
From source file:org.kie.guvnor.services.backend.file.upload.AbstractFileServlet.java
/** * Get the form data from the inbound request. *///from w w w . j a va2s . com @SuppressWarnings("rawtypes") private FormData getFormData(final HttpServletRequest request) throws IOException { final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); final FormData data = new FormData(); try { final List items = upload.parseRequest(request); final Iterator it = items.iterator(); FileOperation operation = null; String fileName = null; String contextPath = null; String fullPath = null; while (it.hasNext()) { final FileItem item = (FileItem) it.next(); if (!item.isFormField()) { data.setFile(item); } else if (item.getFieldName().equals(FileManagerFields.FORM_FIELD_PATH)) { System.out.println("path:" + item.getString()); contextPath = item.getString(); } else if (item.getFieldName().equals(FileManagerFields.FORM_FIELD_NAME)) { System.out.println("name:" + item.getString()); fileName = item.getString(); } else if (item.getFieldName().equals(FileManagerFields.FORM_FIELD_FULL_PATH)) { System.out.println("full path:" + item.getString()); fullPath = item.getString(); } else if (item.getFieldName().equals(FileManagerFields.FORM_FIELD_OPERATION)) { System.out.println("operation:" + item.getString()); operation = FileOperation.valueOf(item.getString()); } } if (operation == null) { throw new IllegalArgumentException("FORM_FIELD_OPERATION is null. Cannot process upload."); } org.kie.commons.java.nio.file.Path path; switch (operation) { case CREATE: if (fileName == null) { throw new IllegalArgumentException("FORM_FIELD_NAME is null. Cannot process upload."); } if (contextPath == null) { throw new IllegalArgumentException("FORM_FIELD_PATH is null. Cannot process upload."); } data.setOperation(operation); data.setTargetPath(convertPath(fileName, contextPath)); break; case UPDATE: if (fullPath == null) { throw new IllegalArgumentException("FORM_FIELD_FULL_PATH is null. Cannot process upload."); } data.setOperation(operation); data.setTargetPath(convertPath(fullPath)); } return data; } catch (Exception e) { throw new org.kie.commons.java.nio.IOException(e.getMessage()); } }
From source file:org.more.webui.components.upload.Upload.java
public void onEvent(Event event, UIComponent component, ViewContext viewContext) throws Throwable { Upload swfUpload = (Upload) component; HttpServletRequest httpRequest = viewContext.getHttpRequest(); ServletContext servletContext = httpRequest.getSession(true).getServletContext(); if (ServletFileUpload.isMultipartContent(httpRequest) == false) return;// ??multipart?? try {// ww w. j a v a2s. c om //1. DiskFileItemFactory factory = new DiskFileItemFactory();// DiskFileItemFactory??????List ServletFileUpload upload = new ServletFileUpload(factory); String charset = httpRequest.getCharacterEncoding(); if (charset != null) upload.setHeaderEncoding(charset); factory.setSizeThreshold(swfUpload.getUploadSizeThreshold()); File uploadTempDir = new File(servletContext.getRealPath(swfUpload.getUploadTempDir())); if (uploadTempDir.exists() == false) uploadTempDir.mkdirs(); factory.setRepository(uploadTempDir); //2.? List<FileItem> itemList = upload.parseRequest(httpRequest); List<FileItem> finalList = new ArrayList<FileItem>(); Map<String, String> finalParam = new HashMap<String, String>(); for (FileItem item : itemList) if (item.isFormField() == false) finalList.add(item); else finalParam.put(new String(item.getFieldName().getBytes("iso-8859-1")), new String(item.getString().getBytes("iso-8859-1"))); //3. Object returnData = null; MethodExpression onBizActionExp = swfUpload.getOnBizActionExpression(); if (onBizActionExp != null) { HashMap<String, Object> upObject = new HashMap<String, Object>(); upObject.put("files", finalList); upObject.put("params", finalParam); HashMap<String, Object> upParam = new HashMap<String, Object>(); upParam.put("up", upObject); returnData = onBizActionExp.execute(component, viewContext, upParam); } //4.?? for (FileItem item : itemList) try { item.delete(); } catch (Exception e) { } //5. viewContext.sendObject(returnData); } catch (Exception e) { viewContext.sendError(e); } }