List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload getItemIterator
public FileItemIterator getItemIterator(HttpServletRequest request) throws FileUploadException, IOException
From source file:org.elissa.server.StencilSetExtensionGeneratorServlet.java
/** * Request parameters are documented in/* w w w . j a va 2 s . c o m*/ * editor/test/examples/stencilset-extension-generator.xhtml * The parameter 'csvFile' is always required. * An example CSV file can be found in * editor/test/examples/design-thinking-example-data.csv * which has been exported using OpenOffice.org from * editor/test/examples/design-thinking-example-data.ods */ protected void doPost(HttpServletRequest request, HttpServletResponse response) { this.request = request; this.response = response; this.baseUrl = Repository.getBaseUrl(request); this.repository = new Repository(baseUrl); // parameters and their default values String modelNamePrefix = "Generated Model using "; String stencilSetExtensionNamePrefix = StencilSetExtensionGenerator.DEFAULT_STENCIL_SET_EXTENSION_NAME_PREFIX; String baseStencilSetPath = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET_PATH; String baseStencilSet = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET; String baseStencil = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL; List<String> stencilSetExtensionUrls = new ArrayList<String>(); String[] columnPropertyMapping = null; String[] csvHeader = null; List<Map<String, String>> stencilPropertyMatrix = new ArrayList<Map<String, String>>(); String modelDescription = "The initial version of this model has been created by the Stencilset Extension Generator."; String additionalERDFContentForGeneratedModel = ""; String[] modelTags = null; // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iterator; try { iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { // ordinary form field String value = Streams.asString(stream); //System.out.println("Form field " + name + " with value " // + value + " detected."); if (name.equals("modelNamePrefix")) { modelNamePrefix = value; } else if (name.equals("stencilSetExtensionNamePrefix")) { stencilSetExtensionNamePrefix = value; } else if (name.equals("baseStencilSetPath")) { baseStencilSetPath = value; } else if (name.equals("baseStencilSet")) { baseStencilSet = value; } else if (name.equals("stencilSetExtension")) { stencilSetExtensionUrls.add(value); } else if (name.equals("baseStencil")) { baseStencil = value; } else if (name.equals("columnPropertyMapping")) { columnPropertyMapping = value.split(","); } else if (name.equals("modelDescription")) { modelDescription = value; } else if (name.equals("modelTags")) { modelTags = value.split(","); } else if (name.equals("additionalERDFContentForGeneratedModel")) { additionalERDFContentForGeneratedModel = value; } } else { // file field //System.out.println("File field " + name + " with file name " // + item.getName() + " detected."); // Process the input stream if (name.equals("csvFile")) { CsvMapReader csvFileReader = new CsvMapReader(new InputStreamReader(stream), CsvPreference.EXCEL_PREFERENCE); csvHeader = csvFileReader.getCSVHeader(true); if (columnPropertyMapping != null || columnPropertyMapping.length > 0) { csvHeader = columnPropertyMapping; } Map<String, String> row; while ((row = csvFileReader.read(csvHeader)) != null) { stencilPropertyMatrix.add(row); } } } } // generate stencil set Date creationDate = new Date(System.currentTimeMillis()); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss.SSS"); String stencilSetExtensionName = stencilSetExtensionNamePrefix + " " + dateFormat.format(creationDate); stencilSetExtensionUrls .add(StencilSetExtensionGenerator.generateStencilSetExtension(stencilSetExtensionName, stencilPropertyMatrix, columnPropertyMapping, baseStencilSet, baseStencil)); // generate new model String modelName = modelNamePrefix + stencilSetExtensionName; String model = repository.generateERDF(UUID.randomUUID().toString(), additionalERDFContentForGeneratedModel, baseStencilSetPath, baseStencilSet, stencilSetExtensionUrls, modelName, modelDescription); String modelUrl = baseUrl + repository.saveNewModel(model, modelName, modelDescription, baseStencilSet, baseStencilSetPath); // hack for reverse proxies: modelUrl = modelUrl.substring(modelUrl.lastIndexOf("http://")); // tag model if (modelTags != null) { for (String tagName : modelTags) { repository.addTag(modelUrl, tagName.trim()); } } // redirect client to editor with that newly generated model response.setHeader("Location", modelUrl); response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { // TODO Add some error message } }
From source file:org.epics.archiverappliance.mgmt.bpl.UploadChannelArchiverConfigAction.java
@Override public void execute(HttpServletRequest req, HttpServletResponse resp, ConfigService configService) throws IOException { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { throw new IOException("HTTP request is not sending multipart content; therefore we cannnot process"); }// ww w .jav a 2 s .c om // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); List<String> fieldsAsPartOfStream = ArchivePVAction.getFieldsAsPartOfStream(configService); try (PrintWriter out = new PrintWriter(new NullOutputStream())) { FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if (item.isFormField()) { logger.debug("Form field " + name + " detected."); } else { logger.debug("File field " + name + " with file name " + item.getName() + " detected."); try (InputStream is = new BufferedInputStream(item.openStream())) { is.mark(1024); logger.info((new LineNumberReader(new InputStreamReader(is))).readLine()); is.reset(); LinkedList<PVConfig> pvConfigs = EngineConfigParser.importEngineConfig(is); for (PVConfig pvConfig : pvConfigs) { boolean scan = !pvConfig.isMonitor(); float samplingPeriod = pvConfig.getPeriod(); if (logger.isDebugEnabled()) logger.debug("Adding " + pvConfig.getPVName() + " using " + (scan ? SamplingMethod.SCAN : SamplingMethod.MONITOR) + " and a period of " + samplingPeriod); ArchivePVAction.archivePV(out, pvConfig.getPVName(), true, scan ? SamplingMethod.SCAN : SamplingMethod.MONITOR, samplingPeriod, null, null, null, false, configService, fieldsAsPartOfStream); } } catch (Exception ex) { logger.error("Error importing configuration", ex); resp.sendRedirect("../ui/integration.html?message=Error importing config file " + item.getName() + " " + ex.getMessage()); return; } } } resp.sendRedirect("../ui/integration.html?message=Successfully imported configuration files"); } catch (FileUploadException ex) { throw new IOException(ex); } }
From source file:org.fcrepo.server.management.UploadServlet.java
/** * The servlet entry point. http://host:port/fedora/management/upload *///w w w .j av a 2 s. c o m @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Context context = ReadOnlyContext.getContext(Constants.HTTP_REQUEST.REST.uri, request); try { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request, looking for "file" InputStream in = null; FileItemIterator iter = upload.getItemIterator(request); while (in == null && iter.hasNext()) { FileItemStream item = iter.next(); logger.info( "Got next item: isFormField=" + item.isFormField() + " fieldName=" + item.getFieldName()); if (!item.isFormField() && item.getFieldName().equals("file")) { in = item.openStream(); } } if (in == null) { sendResponse(HttpServletResponse.SC_BAD_REQUEST, "No data sent.", response); } else { sendResponse(HttpServletResponse.SC_CREATED, m_management.putTempStream(context, in), response); } } catch (AuthzException ae) { throw RootException.getServletException(ae, request, "Upload", new String[0]); } catch (Exception e) { e.printStackTrace(); sendResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getClass().getName() + ": " + e.getMessage(), response); } }
From source file:org.fcrepo.server.rest.RestUtil.java
/** * Retrieves the contents of the HTTP Request. * @return InputStream from the request//from ww w .j ava 2 s. c o m */ public static RequestContent getRequestContent(HttpServletRequest request, HttpHeaders headers) throws Exception { RequestContent rContent = null; // See if the request is a multi-part file upload request if (ServletFileUpload.isMultipartContent(request)) { logger.debug("processing multipart content..."); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request, use the first available File item FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { rContent = new RequestContent(); rContent.contentStream = item.openStream(); rContent.mimeType = item.getContentType(); FileItemHeaders itemHeaders = item.getHeaders(); if (itemHeaders != null) { String contentLength = itemHeaders.getHeader("Content-Length"); if (contentLength != null) { rContent.size = Long.parseLong(contentLength); } } break; } else { logger.trace("ignoring form field \"{}\" \"{}\"", item.getFieldName(), item.getName()); } } } else { // If the content stream was not been found as a multipart, // try to use the stream from the request directly if (rContent == null) { String contentLength = request.getHeader("Content-Length"); long size = 0; if (contentLength != null) { size = Long.parseLong(contentLength); } else size = request.getContentLength(); if (size > 0) { rContent = new RequestContent(); rContent.contentStream = request.getInputStream(); rContent.size = size; } else { String transferEncoding = request.getHeader("Transfer-Encoding"); if (transferEncoding != null && transferEncoding.contains("chunked")) { BufferedInputStream bis = new BufferedInputStream(request.getInputStream()); bis.mark(2); if (bis.read() > 0) { bis.reset(); rContent = new RequestContent(); rContent.contentStream = bis; } } else { logger.warn( "Expected chunked data not found- " + "Transfer-Encoding : {}, Content-Length: {}", transferEncoding, size); } } } } // Attempt to set the mime type and size if not already set if (rContent != null) { if (rContent.mimeType == null) { MediaType mediaType = headers.getMediaType(); if (mediaType != null) { rContent.mimeType = mediaType.toString(); } } if (rContent.size == 0) { List<String> lengthHeaders = headers.getRequestHeader("Content-Length"); if (lengthHeaders != null && lengthHeaders.size() > 0) { rContent.size = Long.parseLong(lengthHeaders.get(0)); } } } return rContent; }
From source file:org.geowe.server.upload.FileUploadServlet.java
@Override public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final ServletFileUpload upload = new ServletFileUpload(); response.setContentType("text/plain; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_FILE_SIZE);//from ww w.ja v a2 s. c o m try { final FileItemIterator iter = upload.getItemIterator(request); final StringWriter writer = new StringWriter(); while (iter.hasNext()) { final FileItemStream item = iter.next(); IOUtils.copy(item.openStream(), writer, "UTF-8"); final String content = writer.toString(); response.setStatus(HttpStatus.SC_OK); response.getWriter().printf(content); } } catch (SizeLimitExceededException e) { response.setStatus(HttpStatus.SC_REQUEST_TOO_LONG); response.getWriter().printf(HttpStatus.SC_REQUEST_TOO_LONG + ":" + e.getMessage()); LOG.error(e.getMessage()); } catch (Exception e) { response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); response.getWriter().printf(HttpStatus.SC_INTERNAL_SERVER_ERROR + ": ups! something went wrong."); LOG.error(e.getMessage()); } }
From source file:org.geowe.server.upload.FileUploadZipServlet.java
@Override public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final ServletFileUpload upload = new ServletFileUpload(); response.setContentType("text/plain; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_FILE_SIZE);//w ww.ja v a 2 s .c o m try { final FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { final FileItemStream item = iter.next(); ZipFile zipFile = createZipFile(item); final String content = readZipFile(zipFile); if (EMPTY.equals(content)) { response.setStatus(HttpStatus.SC_NO_CONTENT); response.getWriter().printf(HttpStatus.SC_NO_CONTENT + ":" + content); } else if (BAD_FORMAT.equals(content)) { response.setStatus(HttpStatus.SC_NOT_ACCEPTABLE); response.getWriter().printf(HttpStatus.SC_NOT_ACCEPTABLE + ":" + content); } else { response.setStatus(HttpStatus.SC_OK); response.getWriter().printf(content); } } } catch (SizeLimitExceededException e) { response.setStatus(HttpStatus.SC_REQUEST_TOO_LONG); response.getWriter().printf(HttpStatus.SC_REQUEST_TOO_LONG + ":" + e.getMessage()); LOG.error(e.getMessage()); } catch (Exception e) { response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); response.getWriter().printf(HttpStatus.SC_INTERNAL_SERVER_ERROR + ": ups! something went wrong."); LOG.error(e.getMessage()); } }
From source file:org.gss_project.gss.server.rest.FilesHandler.java
/** * A method for handling multipart POST requests for uploading * files from browser-based JavaScript clients. * * @param request the HTTP request// w ww. j av a2 s .c o m * @param response the HTTP response * @param path the resource path * @throws IOException in case an error occurs writing to the * response stream */ private void handleMultipart(HttpServletRequest request, HttpServletResponse response, String path) throws IOException { if (logger.isDebugEnabled()) logger.debug("Multipart POST for resource: " + path); User owner = getOwner(request); boolean exists = true; Object resource = null; FileHeader file = null; try { resource = getService().getResourceAtPath(owner.getId(), path, false); } catch (ObjectNotFoundException e) { exists = false; } catch (RpcException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } if (exists) if (resource instanceof FileHeader) { file = (FileHeader) resource; if (file.isDeleted()) { response.sendError(HttpServletResponse.SC_CONFLICT, file.getName() + " is in the trash"); return; } } else { response.sendError(HttpServletResponse.SC_CONFLICT, path + " is a folder"); return; } Object parent; String parentPath = null; try { parentPath = getParentPath(path); parent = getService().getResourceAtPath(owner.getId(), parentPath, true); } catch (ObjectNotFoundException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND, parentPath); return; } catch (RpcException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } if (!(parent instanceof Folder)) { response.sendError(HttpServletResponse.SC_CONFLICT); return; } final Folder folderLocal = (Folder) parent; final String fileName = getLastElement(path); if (!isValidResourceName(fileName)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } FileItemIterator iter; File uploadedFile = null; try { // Create a new file upload handler. ServletFileUpload upload = new ServletFileUpload(); StatusProgressListener progressListener = new StatusProgressListener(getService()); upload.setProgressListener(progressListener); iter = upload.getItemIterator(request); String dateParam = null; String auth = null; while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { final String value = Streams.asString(stream); if (name.equals(DATE_PARAMETER)) dateParam = value; else if (name.equals(AUTHORIZATION_PARAMETER)) auth = value; if (logger.isDebugEnabled()) logger.debug(name + ":" + value); } else { // Fetch the timestamp used to guard against replay attacks. if (dateParam == null) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "No Date parameter"); return; } long timestamp; try { timestamp = DateUtil.parseDate(dateParam).getTime(); } catch (DateParseException e) { response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); return; } // Fetch the Authorization parameter and find the user specified in it. if (auth == null) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "No Authorization parameter"); return; } String[] authParts = auth.split(" "); if (authParts.length != 2) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String username = authParts[0]; String signature = authParts[1]; User user = null; try { user = getService().findUser(username); } catch (RpcException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } if (user == null) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } request.setAttribute(USER_ATTRIBUTE, user); // Remove the servlet path from the request URI. String p = request.getRequestURI(); String servletPath = request.getContextPath() + request.getServletPath(); p = p.substring(servletPath.length()); // Validate the signature in the Authorization parameter. String data = request.getMethod() + dateParam + p; if (!isSignatureValid(signature, user, data)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } progressListener.setUserId(user.getId()); progressListener.setFilename(fileName); final String contentType = item.getContentType(); try { uploadedFile = getService().uploadFile(stream, user.getId()); } catch (IOException ex) { throw new GSSIOException(ex, false); } FileHeader fileLocal = null; final File upf = uploadedFile; final FileHeader f = file; final User u = user; if (file == null) fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() { @Override public FileHeader call() throws Exception { return getService().createFile(u.getId(), folderLocal.getId(), fileName, contentType, upf.getCanonicalFile().length(), upf.getAbsolutePath()); } }); else fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() { @Override public FileHeader call() throws Exception { return getService().updateFileContents(u.getId(), f.getId(), contentType, upf.getCanonicalFile().length(), upf.getAbsolutePath()); } }); updateAccounting(owner, new Date(), fileLocal.getCurrentBody().getFileSize()); getService().removeFileUploadProgress(user.getId(), fileName); } } // We can't return 204 here since GWT's onSubmitComplete won't fire. response.setContentType("text/html"); response.getWriter().print("<pre></pre>"); } catch (FileUploadException e) { String error = "Error while uploading file"; logger.error(error, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error); } catch (GSSIOException e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "Error while uploading file"; if (e.logAsError()) logger.error(error, e); else logger.debug(error, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error); } catch (DuplicateNameException e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "The specified file name already exists in this folder"; logger.error(error, e); response.sendError(HttpServletResponse.SC_CONFLICT, error); } catch (InsufficientPermissionsException e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "You don't have the necessary permissions"; logger.error(error, e); response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, error); } catch (QuotaExceededException e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "Not enough free space available"; if (logger.isDebugEnabled()) logger.debug(error, e); response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, error); } catch (ObjectNotFoundException e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "A specified object was not found"; logger.error(error, e); response.sendError(HttpServletResponse.SC_NOT_FOUND, error); } catch (RpcException e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "An error occurred while communicating with the service"; logger.error(error, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error); } catch (Exception e) { if (uploadedFile != null && uploadedFile.exists()) uploadedFile.delete(); String error = "An internal server error occurred"; logger.error(error, e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error); } }
From source file:org.intermine.webservice.server.lists.ListUploadService.java
/** * Get the reader for the identifiers uploaded with this request. * @param request The request object./* w w w. j a va 2s. c o m*/ * @return A buffered reader for reading the identifiers. */ protected BufferedReader getReader(final HttpServletRequest request) { BufferedReader r = null; if (ServletFileUpload.isMultipartContent(request)) { final ServletFileUpload upload = new ServletFileUpload(); try { final FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { final FileItemStream item = iter.next(); final String fieldName = item.getFieldName(); if (!item.isFormField() && "identifiers".equalsIgnoreCase(fieldName)) { final InputStream stream = item.openStream(); final InputStreamReader in = new InputStreamReader(stream); r = new BufferedReader(in); break; } } } catch (FileUploadException e) { throw new InternalErrorException("Could not read request body", e); } catch (IOException e) { throw new InternalErrorException(e); } } else { if (!requestIsOfSuitableType()) { throw new BadRequestException("Bad content type - " + request.getContentType() + USAGE); } try { r = request.getReader(); } catch (IOException e) { throw new InternalErrorException(e); } } if (r == null) { throw new BadRequestException("No identifiers found in request." + USAGE); } return r; }
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 w w .j av 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.jahia.tools.files.FileUpload.java
/** * Init the MultiPartReq object if it's actually null * * @exception IOException//from w ww . j a v a 2 s . c om */ protected void init() throws IOException { params = new HashMap<String, List<String>>(); paramsContentType = new HashMap<String, String>(); files = new HashMap<String, DiskFileItem>(); filesByFieldName = new HashMap<String, DiskFileItem>(); parseQueryString(); if (checkSavePath(savePath)) { try { final ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(req); DiskFileItemFactory factory = null; while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); if (item.isFormField()) { final String name = item.getFieldName(); final List<String> v; if (params.containsKey(name)) { v = params.get(name); } else { v = new ArrayList<String>(); params.put(name, v); } v.add(Streams.asString(stream, encoding)); paramsContentType.put(name, item.getContentType()); } else { if (factory == null) { factory = new DiskFileItemFactory(); factory.setSizeThreshold(1); factory.setRepository(new File(savePath)); } DiskFileItem fileItem = (DiskFileItem) factory.createItem(item.getFieldName(), item.getContentType(), item.isFormField(), item.getName()); try { Streams.copy(item.openStream(), fileItem.getOutputStream(), true); } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new IOFileUploadException("Processing of " + FileUploadBase.MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e); } final FileItemHeaders fih = item.getHeaders(); fileItem.setHeaders(fih); if (fileItem.getSize() > 0) { files.put(fileItem.getStoreLocation().getName(), fileItem); filesByFieldName.put(fileItem.getFieldName(), fileItem); } } } } catch (FileUploadException ioe) { logger.error("Error while initializing FileUpload class:", ioe); throw new IOException(ioe.getMessage()); } } else { logger.error("FileUpload::init storage path does not exists or can write"); throw new IOException("FileUpload::init storage path does not exists or cannot write"); } }