List of usage examples for org.apache.commons.fileupload FileItem delete
void delete();
From source file:org.apache.ofbiz.pricat.sample.SamplePricatParser.java
/** * Parse pricat excel file in xlsx format. * //w ww . j av a 2 s . c om */ public void parsePricatExcel(boolean writeFile) { XSSFWorkbook workbook = null; try { // 1. read the pricat excel file FileInputStream is = new FileInputStream(pricatFile); // 2. use POI to load this bytes report.print(UtilProperties.getMessage(resource, "ParsePricatFileStatement", new Object[] { pricatFile.getName() }, locale), InterfaceReport.FORMAT_DEFAULT); try { workbook = new XSSFWorkbook(is); report.println(UtilProperties.getMessage(resource, "ok", locale), InterfaceReport.FORMAT_OK); } catch (IOException e) { report.println(e); report.println(UtilProperties.getMessage(resource, "PricatSuggestion", locale), InterfaceReport.FORMAT_ERROR); return; } catch (POIXMLException e) { report.println(e); report.println(UtilProperties.getMessage(resource, "PricatSuggestion", locale), InterfaceReport.FORMAT_ERROR); return; } // 3. only first sheet will be parsed // 3.1 verify the file has a sheet at least formatter = new HSSFDataFormatter(locale); isNumOfSheetsOK(workbook); // 3.2 verify the version is supported XSSFSheet sheet = workbook.getSheetAt(0); if (!isVersionSupported(sheet)) { return; } // 3.3 get currencyId existsCurrencyId(sheet); // 3.4 verify the table header row is just the same as column names, if not, print error and return if (!isTableHeaderMatched(sheet)) { return; } // 3.5 verify the first table has 6 rows at least containsDataRows(sheet); if (UtilValidate.isNotEmpty(errorMessages)) { report.println(UtilProperties.getMessage(resource, "HeaderContainsError", locale), InterfaceReport.FORMAT_ERROR); return; } // 4. parse data // 4.1 parse row by row and store the contents into database parseRowByRow(sheet); if (UtilValidate.isNotEmpty(errorMessages)) { report.println(UtilProperties.getMessage(resource, "DataContainsError", locale), InterfaceReport.FORMAT_ERROR); if (writeFile) { sequenceNum = report.getSequenceNum(); writeCommentsToFile(workbook, sheet); } } // 5. clean up the log files and commented Excel files cleanupLogAndCommentedExcel(); } catch (IOException e) { report.println(e); Debug.logError(e, module); } finally { if (UtilValidate.isNotEmpty(fileItems)) { // remove tmp files FileItem fi = null; for (int i = 0; i < fileItems.size(); i++) { fi = fileItems.get(i); fi.delete(); } } if (workbook != null) { try { workbook.close(); } catch (IOException e) { Debug.logError(e, module); } } } }
From source file:org.apache.tapestry5.upload.internal.services.UploadedFileItemTest.java
@Test public void cleanupCallsFileItemDelete() throws Exception { FileItem item = newMock(FileItem.class); UploadedFileItem uploadedFile = new UploadedFileItem(item); item.delete(); replay();//from w ww . j a v a2s . co m uploadedFile.cleanup(); verify(); }
From source file:org.chiba.agent.web.servlet.HttpRequestHandler.java
protected void processUploadParameters(Map uploads, HttpServletRequest request) throws XFormsException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("updating " + uploads.keySet().size() + " uploads(s)"); }/*from ww w.j a v a 2 s.c o m*/ try { // update repeat indices Iterator iterator = uploads.keySet().iterator(); String id; FileItem item; byte[] data; while (iterator.hasNext()) { id = (String) iterator.next(); item = (FileItem) uploads.get(id); if (item.getSize() > 0) { LOGGER.debug("i'm here"); String name = item.getName(); if (name.contains("/")) { name = name.substring(name.lastIndexOf('/') + 1); } if (name.contains("\\")) { name = name.substring(name.lastIndexOf('\\') + 1); } if (this.xformsProcessor.isFileUpload(id, "anyURI")) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("found upload type 'anyURI'"); } String localPath = new StringBuffer().append(System.currentTimeMillis()).append('/') .append(name).toString(); File localFile = new File(this.uploadRoot, localPath); localFile.getParentFile().mkdirs(); item.write(localFile); if (LOGGER.isDebugEnabled()) { LOGGER.debug("saving data to path: " + localFile); } // todo: externalize file handling and uri generation data = localFile.toURI().toString().getBytes("UTF-8"); } else { data = item.get(); } this.xformsProcessor.setUploadValue(id, item.getContentType(), name, data); // After the value has been set and the RRR took place, create new UploadInfo with status set to 'done' request.getSession().setAttribute(XFormsSession.ADAPTER_PREFIX + sessionKey + "-uploadInfo", new UploadInfo(1, 0, 0, 0, "done")); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("ignoring empty upload " + id); } // todo: removal ? } item.delete(); } } catch (Exception e) { LOGGER.error(e); throw new XFormsException(e); } }
From source file:org.chiba.web.servlet._HttpRequestHandler.java
protected void processUploadParameters(Map uploads, HttpServletRequest request) throws XFormsException { LOGGER.info("updating " + uploads.keySet().size() + " uploads(s)"); try {//from ww w . j a v a2 s.c o m // update repeat indices Iterator iterator = uploads.keySet().iterator(); String id; FileItem item; byte[] data; while (iterator.hasNext()) { id = (String) iterator.next(); item = (FileItem) uploads.get(id); if (item.getSize() > 0) { if (this.chibaBean.hasControlType(id, "anyURI")) { String localPath = new StringBuffer().append('/').append(id).toString(); File localFile = new File(uploadRoot + this.sessionKey, localPath); localFile.getParentFile().mkdirs(); item.write(localFile); // todo: externalize file handling and uri generation data = localFile.toURI().toString().getBytes("UTF-8"); } else { data = item.get(); } this.chibaBean.updateControlValue(id, item.getContentType(), item.getName(), data); // After the value has been set and the RRR took place, create new UploadInfo with status set to 'done' request.getSession().setAttribute(XFormsSession.ADAPTER_PREFIX + sessionKey + "-uploadInfo", new UploadInfo(1, 0, 0, 0, "done")); } else { LOGGER.info("ignoring empty upload " + id); // todo: removal ? } item.delete(); } } catch (Exception e) { throw new XFormsException(e); } }
From source file:org.cloudata.tools.cloudatafs.WebUtil.java
public static void saveFile(CloudataConf conf, FileItem fileItem, String parentPath) throws IOException { BufferedInputStream uploadedStream = new BufferedInputStream(fileItem.getInputStream()); CloudataFS fs = CloudataFS.get(conf); //BufferedOutputStream serverFileOut = new BufferedOutputStream(new FileOutputStream("c:/temp/bb/" + fileItem.getName())); BufferedOutputStream serverFileOut = new BufferedOutputStream(fs.create(parentPath + fileItem.getName())); try {//from ww w .ja va 2 s . c o m byte[] buf = new byte[4096]; int readLen = 0; while ((readLen = uploadedStream.read(buf)) > 0) { serverFileOut.write(buf, 0, readLen); } } finally { serverFileOut.close(); uploadedStream.close(); } fileItem.delete(); }
From source file:org.codehaus.cargo.daemon.request.StartRequest.java
/** * Cleans up the temporary data associated with this request. *//*w ww . jav a 2s . c o m*/ public void cleanup() { try { for (FileItem item : files.values()) { item.delete(); } files.clear(); parameters.clear(); } catch (Throwable t) { return; } }
From source file:org.eclipse.kura.web.server.servlet.FileServlet.java
private void doPostCommand(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { UploadRequest upload = new UploadRequest(this.m_diskFileItemFactory); try {//from w ww . j a v a 2 s. c o m upload.parse(req); } catch (FileUploadException e) { s_logger.error("Error parsing the file upload request"); throw new ServletException("Error parsing the file upload request", e); } // BEGIN XSRF - Servlet dependent code Map<String, String> formFields = upload.getFormFields(); try { GwtXSRFToken token = new GwtXSRFToken(formFields.get("xsrfToken")); KuraRemoteServiceServlet.checkXSRFToken(req, token); } catch (Exception e) { throw new ServletException("Security error: please retry this operation correctly.", e); } // END XSRF security check List<FileItem> fileItems = null; InputStream is = null; File localFolder = new File(System.getProperty("java.io.tmpdir")); OutputStream os = null; try { fileItems = upload.getFileItems(); if (fileItems.size() > 0) { FileItem item = fileItems.get(0); is = item.getInputStream(); byte[] bytes = IOUtils.toByteArray(is); ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(bytes)); int entries = 0; long total = 0; ZipEntry ze = zis.getNextEntry(); while (ze != null) { byte[] buffer = new byte[BUFFER]; String expectedFilePath = new StringBuilder(localFolder.getPath()).append(File.separator) .append(ze.getName()).toString(); String fileName = validateFileName(expectedFilePath, localFolder.getPath()); File newFile = new File(fileName); if (newFile.isDirectory()) { newFile.mkdirs(); ze = zis.getNextEntry(); continue; } if (newFile.getParent() != null) { File parent = new File(newFile.getParent()); parent.mkdirs(); } FileOutputStream fos = new FileOutputStream(newFile); int len; while (total + BUFFER <= tooBig && (len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); total += len; } fos.flush(); fos.close(); entries++; if (entries > tooMany) { throw new IllegalStateException("Too many files to unzip."); } if (total > tooBig) { throw new IllegalStateException("File being unzipped is too big."); } ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); } } catch (IOException e) { throw e; } catch (GwtKuraException e) { throw new ServletException("File is outside extraction target directory."); } finally { if (os != null) { try { os.close(); } catch (IOException e) { s_logger.warn("Cannot close output stream", e); } } if (is != null) { try { is.close(); } catch (IOException e) { s_logger.warn("Cannot close input stream", e); } } if (fileItems != null) { for (FileItem fileItem : fileItems) { fileItem.delete(); } } } }
From source file:org.eclipse.kura.web.server.servlet.FileServlet.java
private void doPostDeployUpload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServiceLocator locator = ServiceLocator.getInstance(); DeploymentAgentService deploymentAgentService; try {//from ww w . j a v a2 s. c o m deploymentAgentService = locator.getService(DeploymentAgentService.class); } catch (GwtKuraException e) { s_logger.error("Error locating DeploymentAgentService", e); throw new ServletException("Error locating DeploymentAgentService", e); } // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { s_logger.error("Not a file upload request"); throw new ServletException("Not a file upload request"); } UploadRequest upload = new UploadRequest(this.m_diskFileItemFactory); try { upload.parse(req); } catch (FileUploadException e) { s_logger.error("Error parsing the file upload request", e); throw new ServletException("Error parsing the file upload request", e); } // BEGIN XSRF - Servlet dependent code Map<String, String> formFields = upload.getFormFields(); try { GwtXSRFToken token = new GwtXSRFToken(formFields.get("xsrfToken")); KuraRemoteServiceServlet.checkXSRFToken(req, token); } catch (Exception e) { throw new ServletException("Security error: please retry this operation correctly.", e); } // END XSRF security check List<FileItem> fileItems = null; InputStream is = null; File localFile = null; OutputStream os = null; boolean successful = false; try { fileItems = upload.getFileItems(); if (fileItems.size() != 1) { s_logger.error("expected 1 file item but found {}", fileItems.size()); throw new ServletException("Wrong number of file items"); } FileItem item = fileItems.get(0); String filename = item.getName(); is = item.getInputStream(); String filePath = System.getProperty("java.io.tmpdir") + File.separator + filename; localFile = new File(filePath); if (localFile.exists()) { if (localFile.delete()) { s_logger.error("Cannot delete file: {}", filePath); throw new ServletException("Cannot delete file: " + filePath); } } try { localFile.createNewFile(); localFile.deleteOnExit(); } catch (IOException e) { s_logger.error("Cannot create file: {}", filePath, e); throw new ServletException("Cannot create file: " + filePath); } try { os = new FileOutputStream(localFile); } catch (FileNotFoundException e) { s_logger.error("Cannot find file: {}", filePath, e); throw new ServletException("Cannot find file: " + filePath, e); } s_logger.info("Copying uploaded package file to file: {}", filePath); try { IOUtils.copy(is, os); } catch (IOException e) { s_logger.error("Failed to copy deployment package file: {}", filename, e); throw new ServletException("Failed to copy deployment package file: " + filename, e); } try { os.close(); } catch (IOException e) { s_logger.warn("Cannot close output stream", e); } URL url = localFile.toURI().toURL(); String sUrl = url.toString(); s_logger.info("Installing package..."); try { deploymentAgentService.installDeploymentPackageAsync(sUrl); successful = true; } catch (Exception e) { s_logger.error("Package installation failed", e); throw new ServletException("Package installation failed", e); } } catch (IOException e) { throw e; } catch (ServletException e) { throw e; } finally { if (os != null) { try { os.close(); } catch (IOException e) { s_logger.warn("Cannot close output stream", e); } } if (localFile != null && !successful) { try { localFile.delete(); } catch (Exception e) { s_logger.warn("Cannot delete file"); } } if (is != null) { try { is.close(); } catch (IOException e) { s_logger.warn("Cannot close input stream", e); } } if (fileItems != null) { for (FileItem fileItem : fileItems) { fileItem.delete(); } } } }
From source file:org.eclipse.rtp.httpdeployer.repository.RepositoryServlet.java
@Override public Document parseMultipartPostRequest(HttpServletRequest req) throws FileUploadException, IOException { RequestResults result = new RequestResults(); List<FileItem> files = HttpDeployerUtils.parseMultipartRequest(req); if (files.size() != 1) { throw new FileUploadException("File not found"); }// w w w .j av a 2 s .c o m try { InputStream repository = files.get(0).getInputStream(); result.addResult(new RepositoryModificationResult( repositoryManager.addRepository(repository).toString(), null, Action.ADD)); } catch (InvalidRepositoryException e) { result.addResult(new RepositoryModificationResult("local", e.getMessage(), Action.ADD)); } // delete temporary files for (FileItem item : files) { item.delete(); } return result.getDocument(); }
From source file:org.eclipse.vtp.framework.engine.http.HttpConnector.java
/** * invokeProcessEngine.//from w w w . j a v a 2 s . co m * * @param req * @param res * @param httpSession * @param pathInfo * @param embeddedInvocation TODO * @throws IOException * @throws ServletException */ private void invokeProcessEngine(HttpServletRequest req, HttpServletResponse res, HttpSession httpSession, String pathInfo, Map<Object, Object> variableValues, @SuppressWarnings("rawtypes") Map<String, String[]> parameterValues, boolean embeddedInvocation) throws IOException, ServletException { boolean newSession = false; Integer depth = (Integer) httpSession.getAttribute("connector.depth"); if (depth == null) { depth = new Integer(0); } String prefix = "connector.attributes."; String fullPrefix = prefix + depth.intValue() + "."; if (embeddedInvocation) httpSession.setAttribute(fullPrefix + "fragment", "true"); Deployment deployment = null; String brand = null; String entryName = null; boolean subdialog = false; if (!pathInfo.startsWith(PATH_PREFIX)) { System.out.println("invoking process engine for new session: " + pathInfo); newSession = true; synchronized (this) { for (String path : deploymentsByPath.keySet()) { System.out.println("Comparing to deployment: " + path); if (pathInfo.equals(path) || pathInfo.startsWith(path) && pathInfo.length() > path.length() && pathInfo.charAt(path.length()) == '/') { deployment = deploymentsByPath.get(path); System.out.println("Matching deployment found: " + deployment); brand = req.getParameter("BRAND"); if (req.getParameter("SUBDIALOG") != null) subdialog = Boolean.parseBoolean(req.getParameter("SUBDIALOG")); if (pathInfo.length() > path.length() + 1) { entryName = pathInfo.substring(path.length() + 1); System.out.println("Entry point name: " + entryName); } break; } } } if (deployment == null) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (entryName == null) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } pathInfo = NEXT_PATH; httpSession.setAttribute(fullPrefix + DEPLOYMENT_ID, deployment.getProcessID()); } else if (pathInfo.equals(LOG_PATH)) { if (req.getParameter("cmd") != null && req.getParameter("cmd").equals("set")) { String level = req.getParameter("level"); if (level == null || (!level.equalsIgnoreCase("ERROR") && !level.equalsIgnoreCase("WARN") && !level.equalsIgnoreCase("INFO") && !level.equalsIgnoreCase("DEBUG"))) level = "INFO"; System.setProperty("org.eclipse.vtp.loglevel", level); } writeLogging(req, res); return; } else { String deploymentID = (String) httpSession.getAttribute(fullPrefix + DEPLOYMENT_ID); synchronized (this) { deployment = deploymentsByID.get(deploymentID); } if (deployment == null) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } if (subdialog) httpSession.setAttribute(fullPrefix + "subdialog", "true"); if (pathInfo.equals(INDEX_PATH)) { writeIndex(res, deployment); return; } ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); if (ServletFileUpload.isMultipartContent(new ServletRequestContext(req))) { System.out.println( "ServletFileUpload.isMultipartContent(new ServletRequestContext(httpRequest)) is true"); try { List items = upload.parseRequest(req); for (int i = 0; i < items.size(); i++) { FileItem fui = (FileItem) items.get(i); if (fui.isFormField() || "text/plain".equals(fui.getContentType())) { System.out.println("Form Field: " + fui.getFieldName() + " | " + fui.getString()); parameterValues.put(fui.getFieldName(), new String[] { fui.getString() }); } else { File temp = File.createTempFile(Guid.createGUID(), ".tmp"); fui.write(temp); parameterValues.put(fui.getFieldName(), new String[] { temp.getAbsolutePath() }); fui.delete(); System.out.println("File Upload: " + fui.getFieldName()); System.out.println("\tTemp file name: " + temp.getAbsolutePath()); System.out.println("\tContent Type: " + fui.getContentType()); System.out.println("\tSize: " + fui.getSize()); } } } catch (Exception e) { e.printStackTrace(); } } for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); parameterValues.put(key, req.getParameterValues(key)); } for (String key : parameterValues.keySet()) { String[] values = parameterValues.get(key); if (values == null || values.length == 0) System.out.println(key + " empty"); else { System.out.println(key + " " + values[0]); for (int i = 1; i < values.length; i++) System.out.println("\t" + values[i]); } } IDocument document = null; if (pathInfo.equals(ABORT_PATH)) document = deployment.abort(httpSession, req, res, prefix, depth.intValue(), variableValues, parameterValues); else if (pathInfo.equals(NEXT_PATH)) { if (brand == null && !newSession) document = deployment.next(httpSession, req, res, prefix, depth.intValue(), variableValues, parameterValues); else document = deployment.start(httpSession, req, res, prefix, depth.intValue(), variableValues, parameterValues, entryName, brand, subdialog); } else { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (document == null) { res.setStatus(HttpServletResponse.SC_NO_CONTENT); return; } else if (document instanceof ControllerDocument) { ControllerDocument cd = (ControllerDocument) document; if (cd.getTarget() == null) { @SuppressWarnings("unchecked") Map<String, Map<String, Object>> outgoing = (Map<String, Map<String, Object>>) httpSession .getAttribute(fullPrefix + "outgoing-data"); int newDepth = depth.intValue() - 1; if (newDepth == 0) httpSession.removeAttribute("connector.depth"); else httpSession.setAttribute("connector.depth", new Integer(newDepth)); String oldFullPrefix = fullPrefix; fullPrefix = prefix + newDepth + "."; Object[] params = (Object[]) httpSession.getAttribute(fullPrefix + "exitparams"); if (params != null) for (int i = 0; i < params.length; i += 2) parameterValues.put((String) params[i], (String[]) params[i + 1]); String[] paramNames = cd.getParameterNames(); for (int i = 0; i < paramNames.length; ++i) parameterValues.put(paramNames[i], cd.getParameterValues(paramNames[i])); String[] variableNames = cd.getVariableNames(); Map<Object, Object> variables = new HashMap<Object, Object>(variableNames.length); if (outgoing != null) { Map<String, Object> map = outgoing.get(cd.getParameterValues("exit")[0]); if (map != null) { for (int i = 0; i < variableNames.length; ++i) { Object mapping = map.get(variableNames[i]); if (mapping != null) variables.put(mapping, cd.getVariableValue(variableNames[i])); } } } deployment.end(httpSession, prefix, depth.intValue()); for (@SuppressWarnings("rawtypes") Enumeration e = httpSession.getAttributeNames(); e.hasMoreElements();) { String name = (String) e.nextElement(); if (name.startsWith(oldFullPrefix)) httpSession.removeAttribute(name); } invokeProcessEngine(req, res, httpSession, NEXT_PATH, variables, parameterValues, newDepth > 0); return; } else { String[] paramNames = cd.getParameterNames(); Object[] params = new Object[paramNames.length * 2]; for (int i = 0; i < params.length; i += 2) { params[i] = paramNames[i / 2]; params[i + 1] = cd.getParameterValues(paramNames[i / 2]); } httpSession.setAttribute(fullPrefix + "exitparams", params); String[] variableNames = cd.getVariableNames(); Map<Object, Object> variables = new HashMap<Object, Object>(variableNames.length); for (int i = 0; i < variableNames.length; ++i) variables.put(variableNames[i], cd.getVariableValue(variableNames[i])); httpSession.setAttribute("connector.depth", new Integer(depth.intValue() + 1)); fullPrefix = prefix + (depth.intValue() + 1) + "."; String deploymentId = cd.getTarget().substring(0, cd.getTarget().lastIndexOf('(') - 1); String entryPointName = cd.getTarget().substring(cd.getTarget().lastIndexOf('(') + 1, cd.getTarget().length() - 1); httpSession.setAttribute(fullPrefix + DEPLOYMENT_ID, deploymentId); httpSession.setAttribute(fullPrefix + ENTRY_POINT_NAME, entryPointName); Map<String, Map<String, Object>> outgoing = new HashMap<String, Map<String, Object>>(); String[] outPaths = cd.getOutgoingPaths(); for (int i = 0; i < outPaths.length; ++i) { Map<String, Object> map = new HashMap<String, Object>(); String[] names = cd.getOutgoingDataNames(outPaths[i]); for (int j = 0; j < names.length; ++j) map.put(names[j], cd.getOutgoingDataValue(outPaths[i], names[j])); outgoing.put(outPaths[i], map); } httpSession.setAttribute(fullPrefix + "outgoing-data", outgoing); invokeProcessEngine(req, res, httpSession, "/" + deploymentId + "/" + entryPointName, variables, parameterValues, true); return; } } res.setStatus(HttpServletResponse.SC_OK); if (!document.isCachable()) res.setHeader("Cache-Control", "max-age=0, no-cache"); res.setContentType(document.getContentType()); OutputStream writer = res.getOutputStream(); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); XMLWriter xmlWriter = new XMLWriter(writer); xmlWriter.setCompactElements(true); transformer.transform(document.toXMLSource(), xmlWriter.toXMLResult()); if (reporter.isSeverityEnabled(IReporter.SEVERITY_INFO) && !document.isSecured()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); xmlWriter = new XMLWriter(baos); xmlWriter.setCompactElements(true); transformer.transform(document.toXMLSource(), xmlWriter.toXMLResult()); System.out.println(new String(baos.toByteArray(), "UTF-8")); } } catch (TransformerException e) { throw new ServletException(e); } writer.flush(); writer.close(); }