List of usage examples for org.apache.commons.fileupload FileItem delete
void delete();
From source file:org.opencms.workplace.commons.CmsReplace.java
/** * Uploads the specified file and replaces the VFS file.<p> * /*from ww w . ja v a 2 s . co m*/ * @throws JspException if inclusion of error dialog fails */ public void actionReplace() throws JspException { try { // 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; } } if (fi != null) { // get file object information 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 CmsException(Messages.get().container(Messages.ERR_FILE_SIZE_TOO_LARGE_1, new Long((maxFileSizeBytes / 1024)))); } byte[] content = fi.get(); fi.delete(); // determine the resource type id from the resource to replace CmsResource res = getCms().readResource(getParamResource(), CmsResourceFilter.IGNORE_EXPIRATION); CmsFile file = getCms().readFile(res); byte[] contents = file.getContents(); int resTypeId = res.getTypeId(); // check the lock state and replace resource checkLock(getParamResource()); try { getCms().replaceResource(getParamResource(), resTypeId, content, null); } catch (CmsDbSqlException sqlExc) { // SQL error, probably the file is too large for the database settings, restore old content file.setContents(contents); getCms().writeFile(file); throw sqlExc; } // close dialog actionCloseDialog(); } else { throw new CmsException(Messages.get().container(Messages.ERR_UPLOAD_FILE_NOT_FOUND_0)); } } catch (Throwable e) { // error replacing file, show error dialog includeErrorpage(this, e); } }
From source file:org.opencms.workplace.explorer.CmsNewCsvFile.java
/** * Returns the content of the file upload and sets the resource name.<p> * /*from w w w. jav a 2 s . c o m*/ * @return the byte content of the uploaded file * @throws CmsWorkplaceException if the filesize if greater that maxFileSizeBytes or if the upload file cannot be found */ public byte[] getFileContentFromUpload() throws CmsWorkplaceException { byte[] content; // 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; } } if (fi != null) { long size = fi.getSize(); if (size == 0) { throw new CmsWorkplaceException(Messages.get().container(Messages.ERR_UPLOAD_FILE_NOT_FOUND_0)); } long maxFileSizeBytes = OpenCms.getWorkplaceManager().getFileBytesMaxUploadSize(getCms()); // check file size if ((maxFileSizeBytes > 0) && (size > maxFileSizeBytes)) { throw new CmsWorkplaceException(Messages.get().container(Messages.ERR_UPLOAD_FILE_SIZE_TOO_HIGH_1, new Long(maxFileSizeBytes / 1024))); } content = fi.get(); fi.delete(); setParamResource(fi.getName()); } else { throw new CmsWorkplaceException(Messages.get().container(Messages.ERR_UPLOAD_FILE_NOT_FOUND_0)); } return content; }
From source file:org.opencms.workplace.explorer.CmsNewResourceUpload.java
/** * Uploads the specified file and unzips it, if selected.<p> * //from www. j a va 2s. com * @throws JspException if inclusion of error dialog fails */ public void actionUpload() throws JspException { // determine the type of upload boolean unzipFile = Boolean.valueOf(getParamUnzipFile()).booleanValue(); // Suffix for error messages (e.g. when exceeding the maximum file upload size) if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(getParamClientFolder())) { CmsUserSettings userSettings = new CmsUserSettings(getCms()); userSettings.setUploadAppletClientFolder(getParamClientFolder()); try { userSettings.save(getCms()); } catch (CmsException e) { // it's not fatal if the client folder for the applet file chooser is not possible if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle(getLocale()).key(Messages.ERR_UPLOAD_STORE_CLIENT_FOLDER_1, new Object[] { getCms().getRequestContext().getCurrentUser().getName() }), e); } } } try { // 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; } } 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 CmsWorkplaceException(Messages.get().container( Messages.ERR_UPLOAD_FILE_SIZE_TOO_HIGH_1, new Long(maxFileSizeBytes / 1024))); } byte[] content = fi.get(); fi.delete(); if (unzipFile) { // zip file upload String currentFolder = getParamUploadFolder(); if (CmsStringUtil.isEmpty(currentFolder)) { // no upload folder parameter found, get current folder currentFolder = getParamCurrentFolder(); } if (CmsStringUtil.isEmpty(currentFolder) || !currentFolder.startsWith("/")) { // no folder information found, guess upload folder currentFolder = computeCurrentFolder(); } // import the zip contents new CmsImportFolder(content, currentFolder, getCms(), false); } else { // 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); newResname = getCms().getRequestContext().getFileTranslator().translateResource(newResname); setParamNewResourceName(newResname); setParamResource(newResname); setParamResource(computeFullResourceName()); // determine the resource type id from the given information int resTypeId = OpenCms.getResourceManager().getDefaultTypeForName(newResname).getTypeId(); int plainId = OpenCms.getResourceManager() .getResourceType(CmsResourceTypePlain.getStaticTypeName()).getTypeId(); if (!getCms().existsResource(getParamResource(), CmsResourceFilter.IGNORE_EXPIRATION)) { try { // create the resource getCms().createResource(getParamResource(), resTypeId, content, properties); } catch (CmsSecurityException e) { // in case of not enough permissions, try to create a plain text file getCms().createResource(getParamResource(), plainId, content, properties); } catch (CmsDbSqlException sqlExc) { // SQL error, probably the file is too large for the database settings, delete file getCms().lockResource(getParamResource()); getCms().deleteResource(getParamResource(), CmsResource.DELETE_PRESERVE_SIBLINGS); throw sqlExc; } } else { checkLock(getParamResource()); CmsFile file = getCms().readFile(getParamResource(), CmsResourceFilter.IGNORE_EXPIRATION); byte[] contents = file.getContents(); try { getCms().replaceResource(getParamResource(), resTypeId, content, null); } catch (CmsSecurityException e) { // in case of not enough permissions, try to create a plain text file getCms().replaceResource(getParamResource(), plainId, 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 { throw new CmsWorkplaceException(Messages.get().container(Messages.ERR_UPLOAD_FILE_NOT_FOUND_0)); } } catch (Throwable e) { // error uploading file, show error dialog setParamMessage(Messages.get().getBundle(getLocale()).key(Messages.ERR_UPLOAD_FILE_0)); setAction(ACTION_SHOWERROR); includeErrorpage(this, e); } }
From source file:org.opencms.workplace.tools.accounts.CmsUserDataImportDialog.java
/** * @see org.opencms.workplace.tools.accounts.A_CmsUserDataImexportDialog#actionCommit() */// w w w .ja v a 2 s. c o m public void actionCommit() throws IOException, ServletException { List errors = new ArrayList(); // get the file item from the multipart request Iterator it = getMultiPartFileItems().iterator(); FileItem fi = null; while (it.hasNext()) { fi = (FileItem) it.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 && CmsStringUtil.isNotEmptyOrWhitespaceOnly(fi.getName())) { byte[] content = fi.get(); File importFile = File.createTempFile("import_users", ".csv"); m_importFile = importFile.getAbsolutePath(); FileOutputStream fileOutput = new FileOutputStream(importFile); fileOutput.write(content); fileOutput.close(); fi.delete(); FileReader fileReader = new FileReader(importFile); BufferedReader bufferedReader = new BufferedReader(fileReader); String line = bufferedReader.readLine(); if (line != null) { List colDefs = CmsStringUtil.splitAsList(line, CmsXsltUtil.getPreferredDelimiter(line)); if (!colDefs.contains("name")) { errors.add(new CmsRuntimeException( Messages.get().container(Messages.ERR_USERDATA_IMPORT_CSV_MISSING_NAME_0))); } if ((line.indexOf("password") == -1) && CmsStringUtil.isEmptyOrWhitespaceOnly(m_password)) { errors.add(new CmsRuntimeException( Messages.get().container(Messages.ERR_USERDATA_IMPORT_CSV_MISSING_PASSWORD_0))); } } bufferedReader.close(); } else { errors.add(new CmsIllegalArgumentException( Messages.get().container(Messages.ERR_USERDATA_IMPORT_NO_CONTENT_0))); } if (errors.isEmpty()) { Map params = new HashMap(); params.put("groups", CmsStringUtil.collectionAsString(getGroups(), ",")); params.put("roles", CmsStringUtil.collectionAsString(getRoles(), ",")); params.put("importfile", m_importFile); params.put("password", m_password); params.put(A_CmsOrgUnitDialog.PARAM_OUFQN, getParamOufqn()); // set action parameter to initial dialog call params.put(CmsDialog.PARAM_ACTION, CmsDialog.DIALOG_INITIAL); getToolManager().jspForwardTool(this, getCurrentToolPath() + "/list", params); } // set the list of errors to display when something goes wrong setCommitErrors(errors); }
From source file:org.opencms.workplace.tools.database.CmsHtmlImportDialog.java
/** * This function reads the file item and if its exits then the * file is saved in the temporary directory of the system.<p> * // w w w. java 2s . co m * @param fi the file item from the multipart-request * * @throws CmsException if something goes wrong. */ private void writeHttpImportDir(FileItem fi) throws CmsException { try { if (fi != null && CmsStringUtil.isNotEmptyOrWhitespaceOnly(fi.getName())) { //write the file in the tmp-directory of the system byte[] content = fi.get(); File importFile = File.createTempFile("import_html", ".zip"); //write the content in the tmp file FileOutputStream fileOutput = new FileOutputStream(importFile.getAbsolutePath()); fileOutput.write(content); fileOutput.close(); fi.delete(); m_htmlimport.setHttpDir(importFile.getAbsolutePath()); } } catch (Exception e) { throw new CmsException(Messages.get().container(Messages.ERR_ACTION_ZIPFILE_UPLOAD_0)); } }
From source file:org.orbeon.oxf.processor.generator.RequestGenerator.java
@Override public ProcessorOutput createOutput(String name) { final ProcessorOutput output = new DigestTransformerOutputImpl(RequestGenerator.this, name) { public void readImpl(final PipelineContext pipelineContext, XMLReceiver xmlReceiver) { final State state = (State) getFilledOutState(pipelineContext); // Transform the resulting document into SAX TransformerUtils.sourceToSAX(new DocumentSource(state.requestDocument), new ForwardingXMLReceiver(xmlReceiver) { @Override public void startElement(String uri, String localname, String qName, Attributes attributes) throws SAXException { try { if (REQUEST_PRIVATE_NAMESPACE_URI.equals(uri)) { // Special treatment for this element if (FILE_ITEM_ELEMENT.equals(qName)) { // Marker for file item final String parameterName = attributes .getValue(PARAMETER_NAME_ATTRIBUTE); final int parameterPosition = Integer .parseInt(attributes.getValue(PARAMETER_POSITION_ATTRIBUTE)); final FileItem fileItem = (FileItem) ((Object[]) getRequest( pipelineContext).getParameterMap() .get(parameterName))[parameterPosition]; final AttributesImpl newAttributes = new AttributesImpl(); super.startPrefixMapping(XMLConstants.XSI_PREFIX, XMLConstants.XSI_URI); super.startPrefixMapping(XMLConstants.XSD_PREFIX, XMLConstants.XSD_URI); newAttributes.addAttribute(XMLConstants.XSI_URI, "type", "xsi:type", "CDATA", useBase64(pipelineContext, fileItem) ? XMLConstants.XS_BASE64BINARY_QNAME.getQualifiedName() : XMLConstants.XS_ANYURI_QNAME.getQualifiedName()); super.startElement("", "value", "value", newAttributes); writeFileItem(pipelineContext, fileItem, state.isSessionScope, useBase64(pipelineContext, fileItem), getXMLReceiver()); super.endElement("", "value", "value"); super.endPrefixMapping(XMLConstants.XSD_PREFIX); super.endPrefixMapping(XMLConstants.XSI_PREFIX); }/*from ww w. j a va2 s. c om*/ } else if (localname.equals("body") && uri.equals("")) { // Marker for request body // Read InputStream into FileItem object, if not already present // We do this so we can read the body multiple times, if needed. // For large files, there will be a performance hit. If we knew // we didn't need to read it multiple times, we could avoid // saving the stream, but practically, it can happen, and it is // convenient. final Context context = getContext(pipelineContext); if (context.bodyFileItem != null || getRequest(pipelineContext).getInputStream() != null) { final ExternalContext.Request request = getRequest(pipelineContext); if (context.bodyFileItem == null) { final FileItem fileItem = new DiskFileItemFactory( getMaxMemorySizeProperty(), SystemUtils.getTemporaryDirectory()).createItem("dummy", "dummy", false, null); pipelineContext.addContextListener( new PipelineContext.ContextListenerAdapter() { public void contextDestroyed(boolean success) { fileItem.delete(); } }); final OutputStream outputStream = fileItem.getOutputStream(); NetUtils.copyStream(request.getInputStream(), outputStream); outputStream.close(); context.bodyFileItem = fileItem; } // Serialize the stream into the body element final AttributesImpl newAttributes = new AttributesImpl(); super.startPrefixMapping(XMLConstants.XSI_PREFIX, XMLConstants.XSI_URI); super.startPrefixMapping(XMLConstants.XSD_PREFIX, XMLConstants.XSD_URI); newAttributes.addAttribute(XMLConstants.XSI_URI, "type", "xsi:type", "CDATA", useBase64(pipelineContext, context.bodyFileItem) ? XMLConstants.XS_BASE64BINARY_QNAME.getQualifiedName() : XMLConstants.XS_ANYURI_QNAME.getQualifiedName()); super.startElement(uri, localname, qName, newAttributes); final String uriOrNull = writeFileItem(pipelineContext, context.bodyFileItem, state.isSessionScope, useBase64(pipelineContext, context.bodyFileItem), getXMLReceiver()); super.endElement(uri, localname, qName); super.endPrefixMapping(XMLConstants.XSD_PREFIX); super.endPrefixMapping(XMLConstants.XSI_PREFIX); // If the body is available as a URL, store it into the pipeline context. // This is done so that native code can access the body even if it has been read // already. Possibly, this could be handled more transparently by ExternalContext, // so that Request.getInputStream() works even upon multiple reads. // NOTE 2013-05-30: We used to store this into the request, but request attributes // are forwarded by LocalRequest. This means that a forwarded-to request might get // the wrong body! Instead, we now use PipelineContext, which is scoped to be per // request. Again, if ExternalContext was handling this, we could just leave it to // ExternalContext. if (uriOrNull != null) pipelineContext.setAttribute(BODY_REQUEST_ATTRIBUTE, uriOrNull); } } else { super.startElement(uri, localname, qName, attributes); } } catch (IOException e) { throw new OXFException(e); } } @Override public void endElement(String uri, String localname, String qName) throws SAXException { if (REQUEST_PRIVATE_NAMESPACE_URI.equals(uri) || localname.equals("body") && uri.equals("")) { // Ignore end element } else { super.endElement(uri, localname, qName); } } }); } protected boolean fillOutState(PipelineContext pipelineContext, DigestState digestState) { final State state = (State) digestState; if (state.requestDocument == null) { // Read config document final Document config = readCacheInputAsDOM4J(pipelineContext, INPUT_CONFIG); // Try to find stream-type attribute final QName streamTypeQName = Dom4jUtils.extractAttributeValueQName(config.getRootElement(), "stream-type"); if (streamTypeQName != null && !(streamTypeQName.equals(XMLConstants.XS_BASE64BINARY_QNAME) || streamTypeQName.equals(XMLConstants.XS_ANYURI_QNAME))) throw new OXFException( "Invalid value for stream-type attribute: " + streamTypeQName.getQualifiedName()); state.requestedStreamType = streamTypeQName; state.isSessionScope = "session".equals(config.getRootElement().attributeValue("stream-scope")); // Read and store request state.requestDocument = readRequestAsDOM4J(pipelineContext, config); // Check if the body was requested state.bodyRequested = XPathUtils.selectSingleNode(state.requestDocument, "/*/body") != null; } final Context context = getContext(pipelineContext); return !context.hasUpload && !state.bodyRequested; } protected byte[] computeDigest(PipelineContext pipelineContext, DigestState digestState) { final State state = (State) digestState; return DigestContentHandler.getDigest(new DocumentSource(state.requestDocument)); } }; addOutput(name, output); return output; }
From source file:org.orbeon.oxf.util.NetUtils.java
private static void deleteFileItem(FileItem fileItem, int scope, Logger logger) { if (logger != null && logger.isDebugEnabled() && fileItem instanceof DiskFileItem) { final File storeLocation = ((DiskFileItem) fileItem).getStoreLocation(); if (storeLocation != null) { final String temporaryFileName = storeLocation.getAbsolutePath(); final String scopeString = (scope == REQUEST_SCOPE) ? "request" : (scope == SESSION_SCOPE) ? "session" : "application"; logger.debug("Deleting temporary " + scopeString + "-scoped file: " + temporaryFileName); }/*w ww . j ava 2s . c om*/ } fileItem.delete(); }
From source file:org.ow2.proactive_grid_cloud_portal.common.server.CredentialsServlet.java
private void login(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/html"); try {// ww w. j a v a 2 s . c o m DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4096); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(1000000); List<?> fileItems = upload.parseRequest(request); Iterator<?> i = fileItems.iterator(); String user = ""; String pass = ""; String sshKey = ""; while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { String name = fi.getFieldName(); String value = fi.getString(); if (name.equals("username")) { user = value; } else if (name.equals("password")) { pass = value; } } else { String field = fi.getFieldName(); byte[] bytes = IOUtils.toByteArray(fi.getInputStream()); if (field.equals("sshkey")) { sshKey = new String(bytes); } } fi.delete(); } String responseS = Service.get().createCredentials(user, pass, sshKey); response.setHeader("Content-disposition", "attachment; filename=" + user + "_cred.txt"); response.setHeader("Location", "" + user + ".cred.txt"); response.getWriter().write(responseS); } catch (Throwable t) { try { response.getWriter().write(t.getMessage()); } catch (IOException e1) { LOGGER.warn("Failed to return login error to client, error was:" + t.getMessage(), e1); } } }
From source file:org.ow2.proactive_grid_cloud_portal.common.server.LoginServlet.java
private void login(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/html"); File cred = null;/* w ww . jav a 2 s . co m*/ try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4096); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(1000000); List<?> fileItems = upload.parseRequest(request); Iterator<?> i = fileItems.iterator(); String user = ""; String pass = ""; String sshKey = ""; while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { String name = fi.getFieldName(); String value = fi.getString(); if (name.equals("username")) { user = value; } else if (name.equals("password")) { pass = value; } } else { String field = fi.getFieldName(); byte[] bytes = IOUtils.toByteArray(fi.getInputStream()); if (field.equals("credential")) { cred = File.createTempFile("credential", null); cred.deleteOnExit(); fi.write(cred); } else if (field.equals("sshkey")) { sshKey = new String(bytes); } } fi.delete(); } String responseS = Service.get().login(user, pass, cred, sshKey); String s = "{ \"sessionId\" : \"" + responseS + "\" }"; response.getWriter().write(SafeHtmlUtils.htmlEscape(s)); } catch (Throwable t) { try { response.getWriter().write(SafeHtmlUtils.htmlEscape(t.getMessage())); } catch (IOException e1) { LOGGER.warn("Failed to return login error to client, error was:" + t.getMessage(), e1); } } finally { if (cred != null) cred.delete(); } }
From source file:org.ow2.proactive_grid_cloud_portal.rm.server.nodesource.serialization.export.ExportToCatalogServlet.java
private CatalogObjectAction buildCatalogObjetAction(HttpServletRequest request) throws Exception { CatalogObjectAction catalogObjectAction = new CatalogObjectAction(); for (FileItem formItem : new ServletRequestTransformer().getFormItems(request)) { if (formItem.isFormField()) { String fieldValue = formItem.getString(); switch (formItem.getFieldName()) { case SESSION_ID_PARAM: catalogObjectAction.setSessionId(fieldValue); break; case BUCKET_NAME_PARAM: catalogObjectAction.setBucketName(fieldValue); break; case NAME_PARAM: catalogObjectAction.setCatalogObjectName(fieldValue); break; case FILE_CONTENT_PARAM: File catalogObjectJsonFile = File.createTempFile("catalog-object-configuration", ".json"); try (PrintWriter writer = new PrintWriter(catalogObjectJsonFile)) { writer.write(fieldValue); }/*from w w w . j av a 2s.co m*/ formItem.write(catalogObjectJsonFile); catalogObjectAction.setCatalogObjectJsonFile(catalogObjectJsonFile); break; case KIND_PARAM: catalogObjectAction.setKind(fieldValue); break; case COMMIT_MESSAGE_PARAM: catalogObjectAction.setCommitMessage(fieldValue); break; case OBJECT_CONTENT_TYPE_PARAM: catalogObjectAction.setObjectContentType(fieldValue); break; case REVISED_PARAM: catalogObjectAction.setRevised(Boolean.parseBoolean(fieldValue)); break; default: } } formItem.delete(); } return catalogObjectAction; }