List of usage examples for org.apache.commons.fileupload FileItem delete
void delete();
From source file:org.elissa.server.AMLSupport.java
/** * The POST request.EPCUpload.java/*from www . j a va 2s.c om*/ */ protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException { PrintWriter out = null; FileItem fileItem = null; try { String oryxBaseUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + "/"; // Get the PrintWriter res.setContentType("text/plain"); res.setCharacterEncoding("utf-8"); out = res.getWriter(); // No isMultipartContent => Error final boolean isMultipartContent = ServletFileUpload.isMultipartContent(req); if (!isMultipartContent) { printError(out, "No Multipart Content transmitted."); return; } // Get the uploaded file final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload servletFileUpload = new ServletFileUpload(factory); servletFileUpload.setSizeMax(-1); final List<?> items; items = servletFileUpload.parseRequest(req); if (items.size() != 1) { printError(out, "Not exactly one File."); return; } fileItem = (FileItem) items.get(0); // replace dtd reference by existing reference /oryx/lib/ARIS-Export.dtd String amlStr = fileItem.getString("UTF-8"); amlStr = amlStr.replaceFirst("\"ARIS-Export.dtd\"", "\"" + oryxBaseUrl + "lib/ARIS-Export.dtd\""); FileOutputStream fileout = null; OutputStreamWriter outwriter = null; try { fileout = new FileOutputStream(((DiskFileItem) fileItem).getStoreLocation()); outwriter = new OutputStreamWriter(fileout, "UTF-8"); outwriter.write(amlStr); outwriter.flush(); } finally { if (outwriter != null) outwriter.close(); if (fileout != null) fileout.close(); } //parse AML file AMLParser parser = new AMLParser(((DiskFileItem) fileItem).getStoreLocation().getAbsolutePath()); parser.parse(); Collection<EPC> epcs = new HashSet<EPC>(); Iterator<String> ids = parser.getModelIds().iterator(); while (ids.hasNext()) { String modelId = ids.next(); epcs.add(parser.getEPC(modelId)); } // serialize epcs to eRDF oryx format OryxSerializer oryxSerializer = new OryxSerializer(epcs, oryxBaseUrl); oryxSerializer.parse(); Document outputDocument = oryxSerializer.getDocument(); // get document as string String docAsString = ""; Source source = new DOMSource(outputDocument); StringWriter stringWriter = new StringWriter(); Result result = new StreamResult(stringWriter); TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer transformer = tfactory.newTransformer(); transformer.transform(source, result); docAsString = stringWriter.getBuffer().toString(); // write response out.print("" + docAsString + ""); } catch (Exception e) { handleException(out, e); } finally { if (fileItem != null) { fileItem.delete(); } } }
From source file:org.getobjects.appserver.elements.WOFileUpload.java
@Override public void takeValuesFromRequest(final WORequest _rq, final WOContext _ctx) { final Object cursor = _ctx.cursor(); String formName = this.elementNameInContext(_ctx); Object formValue = _rq.formValueForKey(formName); if (this.writeValue != null) this.writeValue.setValue(formValue, cursor); if (formValue == null) { if (this.filePath != null) this.filePath.setValue(null, cursor); if (this.data != null) this.data.setValue(null, cursor); } else if (formValue instanceof String) { /* this happens if the enctype is not multipart/formdata */ if (this.filePath != null) this.filePath.setStringValue((String) formValue, cursor); } else if (formValue instanceof FileItem) { FileItem fileItem = (FileItem) formValue; if (this.size != null) this.size.setValue(fileItem.getSize(), cursor); if (this.contentType != null) this.contentType.setStringValue(fileItem.getContentType(), cursor); if (this.filePath != null) this.filePath.setStringValue(fileItem.getName(), cursor); /* process content */ if (this.data != null) this.data.setValue(fileItem.get(), cursor); else if (this.string != null) { // TODO: we could support a encoding get-binding this.string.setStringValue(fileItem.getString(), cursor); } else if (this.inputStream != null) { try { this.inputStream.setValue(fileItem.getInputStream(), cursor); } catch (IOException e) { log.error("failed to get input stream for upload file", e); this.inputStream.setValue(null, cursor); }/*from w ww . j ava2s . c om*/ } /* delete temporary file */ if (this.deleteAfterPush != null) { if (this.deleteAfterPush.booleanValueInComponent(cursor)) fileItem.delete(); } } else log.warn("cannot process WOFileUpload value: " + formValue); }
From source file:org.hudsonci.plugins.vault.ui.UploadsUI.java
@StaplerAccessible public void doUpload(final StaplerRequest req, final StaplerResponse resp) throws Exception { assert req != null; checkPermission();/*from w w w .jav a 2 s . c o m*/ ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); // Parse the request FileItem fileItem = (FileItem) upload.parseRequest(req).get(0); String fileName = Util.getFileName(fileItem.getName()); log.info("File uploaded: {}", fileItem); File dir = Vault.get().getUploadsDir(); dir.mkdirs(); fileItem.write(new File(dir, fileName)); fileItem.delete(); redirectParent(req, resp); }
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 a va 2s . 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.jodconverter.sample.webapp.ConverterServlet.java
private void writeUploadedFile(final FileItem uploadedFile, final File destinationFile) throws ServletException { try {/*from ww w. j a v a 2 s. c o m*/ uploadedFile.write(destinationFile); } catch (Exception exception) { throw new ServletException("Error writing uploaded file", exception); } uploadedFile.delete(); }
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 {//from w ww. j av a2 s. c o m //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); } }
From source file:org.opencms.ade.upload.CmsUploadBean.java
/** * Creates the resources.<p>//from ww w.java 2 s .c om * @param listener the listener * * @throws CmsException if something goes wrong * @throws UnsupportedEncodingException */ private void createResources(CmsUploadListener listener) throws CmsException, UnsupportedEncodingException { // get the target folder String targetFolder = getTargetFolder(); List<String> filesToUnzip = getFilesToUnzip(); // iterate over the list of files to upload and create each single resource for (FileItem fileItem : m_multiPartFileItems) { if ((fileItem != null) && (!fileItem.isFormField())) { // read the content of the file byte[] content = fileItem.get(); fileItem.delete(); // determine the new resource name String fileName = m_parameterMap .get(fileItem.getFieldName() + I_CmsUploadConstants.UPLOAD_FILENAME_ENCODED_SUFFIX)[0]; fileName = URLDecoder.decode(fileName, "UTF-8"); if (filesToUnzip.contains(CmsResource.getName(fileName.replace('\\', '/')))) { // import the zip CmsImportFolder importZip = new CmsImportFolder(); try { importZip.importZip(content, targetFolder, getCmsObject(), false); } finally { // get the created resource names m_resourcesCreated.addAll(importZip.getCreatedResourceNames()); } } else { // create the resource String newResname = createSingleResource(fileName, targetFolder, content); // add the name of the created resource to the list of successful created resources m_resourcesCreated.add(newResname); } if (listener.isCanceled()) { throw listener.getException(); } } } }
From source file:org.opencms.editors.fckeditor.CmsFCKEditorFileBrowser.java
/** * Uploads a file to the OpenCms VFS and returns the necessary JavaScript for the file browser.<p> * //from w w w . ja v a2 s . co m * @return the necessary JavaScript for the file browser */ protected String uploadFile() { String errorCode = ERROR_UPLOAD_OK; try { // get the file item from the multipart request Iterator i = m_multiPartFileItems.iterator(); FileItem fi = null; while (i.hasNext()) { fi = (FileItem) i.next(); if (fi.getName() != null) { // found the file object, leave iteration break; } else { // this is no file object, check next item continue; } } if (fi != null) { String fileName = fi.getName(); long size = fi.getSize(); long maxFileSizeBytes = OpenCms.getWorkplaceManager().getFileBytesMaxUploadSize(getCms()); // check file size if ((maxFileSizeBytes > 0) && (size > maxFileSizeBytes)) { // file size is larger than maximum allowed file size, throw an error throw new Exception(); } byte[] content = fi.get(); fi.delete(); // single file upload String newResname = CmsResource.getName(fileName.replace('\\', '/')); // determine Title property value to set on new resource String title = newResname; if (title.lastIndexOf('.') != -1) { title = title.substring(0, title.lastIndexOf('.')); } List properties = new ArrayList(1); CmsProperty titleProp = new CmsProperty(); titleProp.setName(CmsPropertyDefinition.PROPERTY_TITLE); if (OpenCms.getWorkplaceManager().isDefaultPropertiesOnStructure()) { titleProp.setStructureValue(title); } else { titleProp.setResourceValue(title); } properties.add(titleProp); // determine the resource type id from the given information int resTypeId = OpenCms.getResourceManager().getDefaultTypeForName(newResname).getTypeId(); // calculate absolute path of uploaded resource newResname = getParamCurrentFolder() + newResname; if (!getCms().existsResource(newResname, CmsResourceFilter.IGNORE_EXPIRATION)) { try { // create the resource getCms().createResource(newResname, resTypeId, content, properties); } catch (CmsDbSqlException sqlExc) { // SQL error, probably the file is too large for the database settings, delete file getCms().lockResource(newResname); getCms().deleteResource(newResname, CmsResource.DELETE_PRESERVE_SIBLINGS); throw sqlExc; } } else { // resource exists, overwrite existing resource checkLock(newResname); CmsFile file = getCms().readFile(newResname, CmsResourceFilter.IGNORE_EXPIRATION); byte[] contents = file.getContents(); try { getCms().replaceResource(newResname, resTypeId, content, null); } catch (CmsDbSqlException sqlExc) { // SQL error, probably the file is too large for the database settings, restore content file.setContents(contents); getCms().writeFile(file); throw sqlExc; } } } else { // no upload file found throw new Exception(); } } catch (Throwable e) { // something went wrong, change error code errorCode = ERROR_UPLOAD_INVALID; } // create JavaScript to return to file browser StringBuffer result = new StringBuffer(256); result.append("<html><head><script type=\"text/javascript\">\n"); result.append("window.parent.frames[\"frmUpload\"].OnUploadCompleted("); result.append(errorCode); result.append(");\n"); result.append("</script></head></html>"); return result.toString(); }
From source file:org.opencms.ugc.CmsUgcUploadHelper.java
/** * Passes the form data with the given ID to the handler object, then removes it and deletes its stored data.<p> * * The form data is removed even if an exception is thrown while calling the form data handler. * * @param formDataId the id of the form data to process * @param handler the handler to which the form data should be passed * @throws Exception if something goes wrong *///from w w w .jav a 2 s .c om public void consumeFormData(String formDataId, I_CmsFormDataHandler handler) throws Exception { List<FileItem> items = m_storedFormData.get(formDataId); if (items != null) { Map<String, I_CmsFormDataItem> itemMap = Maps.newHashMap(); LOG.debug(formDataId + ": Processing file items"); for (FileItem item : items) { LOG.debug(formDataId + ": " + item.toString()); if (!item.isFormField() && CmsStringUtil.isEmptyOrWhitespaceOnly(item.getName())) { LOG.debug(formDataId + ": skipping previous file field because it is empty"); } else { itemMap.put(item.getFieldName(), new CmsUgcDataItem(item)); } } Exception storedException = null; try { handler.handleFormData(itemMap); } catch (Exception e) { storedException = e; } for (FileItem item : items) { item.delete(); } m_storedFormData.remove(formDataId); if (storedException != null) { throw storedException; } } }
From source file:org.opencms.workplace.administration.A_CmsImportFromHttp.java
/** * Gets a database import file from the client and copies it to the server.<p> * * @param destination the destination of the file on the server * //from ww w . ja v a2 s . co m * @return the name of the file or null if something went wrong when importing the file * * @throws CmsIllegalArgumentException if the specified file name is invalid * @throws CmsRfsException if generating folders or files on the server fails */ protected String copyFileToServer(String destination) throws CmsIllegalArgumentException, CmsRfsException { // get the file item from the multipart request Iterator i = getMultiPartFileItems().iterator(); FileItem fi = null; while (i.hasNext()) { fi = (FileItem) i.next(); if (fi.getName() != null) { // found the file object, leave iteration break; } else { // this is no file object, check next item continue; } } String fileName = null; if ((fi != null) && CmsStringUtil.isNotEmptyOrWhitespaceOnly(fi.getName())) { // file name has been specified, upload the file fileName = fi.getName(); byte[] content = fi.get(); fi.delete(); // get the file name without folder information fileName = CmsResource.getName(fileName.replace('\\', '/')); // first create the folder if it does not exist File discFolder = new File(OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf( OpenCms.getSystemInfo().getPackagesRfsPath() + File.separator)); if (!discFolder.exists()) { if (!discFolder.mkdir()) { throw new CmsRfsException(Messages.get().container(Messages.ERR_FOLDER_NOT_CREATED_0)); } } // write the file into the packages folder of the OpenCms server File discFile = new File(OpenCms.getSystemInfo() .getAbsoluteRfsPathRelativeToWebInf(destination + File.separator + fileName)); try { // write the new file to disk OutputStream s = new FileOutputStream(discFile); s.write(content); s.close(); } catch (FileNotFoundException e) { throw new CmsRfsException(Messages.get().container(Messages.ERR_FILE_NOT_FOUND_1, fileName, e)); } catch (IOException e) { throw new CmsRfsException(Messages.get().container(Messages.ERR_FILE_NOT_WRITTEN_0, e)); } } else { // no file name has been specified, throw exception throw new CmsIllegalArgumentException(Messages.get().container(Messages.ERR_FILE_NOT_SPECIFIED_0)); } // set the request parameter to the name of the import file setParamImportfile(fileName); return fileName; }