List of usage examples for org.apache.commons.fileupload FileItem delete
void delete();
From source file:com.mx.nibble.middleware.web.util.FileUploadOLD.java
public String execute() throws Exception { //ActionContext ac = invocation.getInvocationContext(); HttpServletResponse response = ServletActionContext.getResponse(); // MultiPartRequestWrapper multipartRequest = ((MultiPartRequestWrapper)ServletActionContext.getRequest()); HttpServletRequest multipartRequest = ServletActionContext.getRequest(); List<FileItem> items2 = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(multipartRequest); System.out.println("TAMAO ITEMS " + items2.size()); System.out.println("Check that we have a file upload request"); boolean isMultipart = ServletFileUpload.isMultipartContent(multipartRequest); System.out.println("isMultipart: " + isMultipart); String ourTempDirectory = "/opt/erp/import/obras/"; byte[] cr = { 13 }; byte[] lf = { 10 }; String CR = new String(cr); String LF = new String(lf); String CRLF = CR + LF;/*from w w w .j a v a 2 s . c om*/ System.out.println("Before a LF=chr(10)" + LF + "Before a CR=chr(13)" + CR + "Before a CRLF" + CRLF); //Initialization for chunk management. boolean bLastChunk = false; int numChunk = 0; //CAN BE OVERRIDEN BY THE postURL PARAMETER: if error=true is passed as a parameter on the URL boolean generateError = false; boolean generateWarning = false; boolean sendRequest = false; response.setContentType("text/plain"); java.util.Enumeration<String> headers = multipartRequest.getHeaderNames(); System.out.println("[parseRequest.jsp] ------------------------------ "); System.out.println("[parseRequest.jsp] Headers of the received request:"); while (headers.hasMoreElements()) { String header = headers.nextElement(); System.out.println("[parseRequest.jsp] " + header + ": " + multipartRequest.getHeader(header)); } System.out.println("[parseRequest.jsp] ------------------------------ "); try { System.out.println(" Get URL Parameters."); Enumeration paraNames = multipartRequest.getParameterNames(); System.out.println("[parseRequest.jsp] ------------------------------ "); System.out.println("[parseRequest.jsp] Parameters: "); String pname; String pvalue; while (paraNames.hasMoreElements()) { pname = (String) paraNames.nextElement(); pvalue = multipartRequest.getParameter(pname); System.out.println("[parseRequest.jsp] " + pname + " = " + pvalue); if (pname.equals("jufinal")) { System.out.println("pname.equals(\"jufinal\")"); bLastChunk = pvalue.equals("1"); } else if (pname.equals("jupart")) { System.out.println("pname.equals(\"jupart\")"); numChunk = Integer.parseInt(pvalue); } //For debug convenience, putting error=true as a URL parameter, will generate an error //in this response. if (pname.equals("error") && pvalue.equals("true")) { generateError = true; } //For debug convenience, putting warning=true as a URL parameter, will generate a warning //in this response. if (pname.equals("warning") && pvalue.equals("true")) { generateWarning = true; } //For debug convenience, putting readRequest=true as a URL parameter, will send back the request content //into the response of this page. if (pname.equals("sendRequest") && pvalue.equals("true")) { sendRequest = true; } } System.out.println("[parseRequest.jsp] ------------------------------ "); int ourMaxMemorySize = 10000000; int ourMaxRequestSize = 2000000000; /////////////////////////////////////////////////////////////////////////////////////////////////////// //The code below is directly taken from the jakarta fileupload common classes //All informations, and download, available here : http://jakarta.apache.org/commons/fileupload/ /////////////////////////////////////////////////////////////////////////////////////////////////////// // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(ourMaxMemorySize); factory.setRepository(new File(ourTempDirectory)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(ourMaxRequestSize); // Parse the request if (sendRequest) { //For debug only. Should be removed for production systems. System.out.println( "[parseRequest.jsp] ==========================================================================="); System.out.println("[parseRequest.jsp] Sending the received request content: "); InputStream is = multipartRequest.getInputStream(); int c; while ((c = is.read()) >= 0) { System.out.write(c); } //while is.close(); System.out.println( "[parseRequest.jsp] ==========================================================================="); } else if (!multipartRequest.getContentType().startsWith("multipart/form-data")) { System.out.println("[parseRequest.jsp] No parsing of uploaded file: content type is " + multipartRequest.getContentType()); } else { List /* FileItem */ items = upload.parseRequest(multipartRequest); // Process the uploaded items Iterator iter = items.iterator(); FileItem fileItem; File fout; System.out.println("[parseRequest.jsp] Let's read the sent data (" + items.size() + " items)"); while (iter.hasNext()) { fileItem = (FileItem) iter.next(); if (fileItem.isFormField()) { System.out.println("[parseRequest.jsp] (form field) " + fileItem.getFieldName() + " = " + fileItem.getString()); //If we receive the md5sum parameter, we've read finished to read the current file. It's not //a very good (end of file) signal. Will be better in the future ... probably ! //Let's put a separator, to make output easier to read. if (fileItem.getFieldName().equals("md5sum[]")) { System.out.println("[parseRequest.jsp] ------------------------------ "); } } else { //Ok, we've got a file. Let's process it. //Again, for all informations of what is exactly a FileItem, please //have a look to http://jakarta.apache.org/commons/fileupload/ // System.out.println("[parseRequest.jsp] FieldName: " + fileItem.getFieldName()); System.out.println("[parseRequest.jsp] File Name: " + fileItem.getName()); System.out.println("[parseRequest.jsp] ContentType: " + fileItem.getContentType()); System.out.println("[parseRequest.jsp] Size (Bytes): " + fileItem.getSize()); //If we are in chunk mode, we add ".partN" at the end of the file, where N is the chunk number. String uploadedFilename = fileItem.getName() + (numChunk > 0 ? ".part" + numChunk : ""); fout = new File(ourTempDirectory + (new File(uploadedFilename)).getName()); System.out.println("[parseRequest.jsp] File Out: " + fout.toString()); System.out.println(" write the file"); fileItem.write(fout); ////////////////////////////////////////////////////////////////////////////////////// System.out.println( " Chunk management: if it was the last chunk, let's recover the complete file"); System.out.println(" by concatenating all chunk parts."); // if (bLastChunk) { System.out.println( "[parseRequest.jsp] Last chunk received: let's rebuild the complete file (" + fileItem.getName() + ")"); //First: construct the final filename. FileInputStream fis; FileOutputStream fos = new FileOutputStream(ourTempDirectory + fileItem.getName()); int nbBytes; byte[] byteBuff = new byte[1024]; String filename; for (int i = 1; i <= numChunk; i += 1) { filename = fileItem.getName() + ".part" + i; System.out.println("[parseRequest.jsp] " + " Concatenating " + filename); fis = new FileInputStream(ourTempDirectory + filename); while ((nbBytes = fis.read(byteBuff)) >= 0) { //out.println("[parseRequest.jsp] " + " Nb bytes read: " + nbBytes); fos.write(byteBuff, 0, nbBytes); } fis.close(); } fos.close(); } // End of chunk management ////////////////////////////////////////////////////////////////////////////////////// fileItem.delete(); } } //while } if (generateWarning) { System.out.println("WARNING: just a warning message.\\nOn two lines!"); } System.out.println("[parseRequest.jsp] " + "Let's write a status, to finish the server response :"); //Let's wait a little, to simulate the server time to manage the file. Thread.sleep(500); //Do you want to test a successful upload, or the way the applet reacts to an error ? if (generateError) { System.out.println( "ERROR: this is a test error (forced in /wwwroot/pages/parseRequest.jsp).\\nHere is a second line!"); } else { System.out.println("SUCCESS"); //out.println(" <span class=\"cpg_user_message\">Il y eu une erreur lors de l'excution de la requte</span>"); } System.out.println("[parseRequest.jsp] " + "End of server treatment "); } catch (Exception e) { System.out.println(""); System.out.println("ERROR: Exception e = " + e.toString()); System.out.println(""); } return SUCCESS; }
From source file:hu.sztaki.lpds.pgportal.portlets.file.LFCFileStoragePortlet.java
@Override public void processAction(ActionRequest request, ActionResponse response) throws PortletException { try {/*from w w w . j a va2s .c o m*/ String userId = request.getRemoteUser(); /* if(request.getAttribute(SportletProperties.ACTION_EVENT)!=null) action=(""+request.getAttribute(SportletProperties.ACTION_EVENT)).split("=")[1]; */ String action = null; if ((request.getParameter("action") != null) && (!request.getParameter("action").equals(""))) { action = request.getParameter("action"); } if (PortletFileUpload.isMultipartContent(request)) { DiskFileItemFactory factory = new DiskFileItemFactory(); PortletFileUpload pfu = new PortletFileUpload(factory); pfu.setSizeMax(10485760); // Maximum upload size //pfu.setProgressListener(new FileUploadProgressListener()); /* PortletSession ps = request.getPortletSession(); ps.setAttribute("upload", pfu, ps.APPLICATION_SCOPE); String actionName = null;*/ String fieldName; List fileItems = pfu.parseRequest(request); Iterator iter = fileItems.iterator(); HashMap params = new HashMap(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // retrieve hidden parameters if item is a form field if (item.isFormField()) { //getting parameters fieldName = item.getFieldName(); // System.out.println("Name is : " + fieldName + " value is : " + item.getString()); if (item.getFieldName().equals(new String("SEListBoxBean_select"))) { params.put("se", item.getString()); } if (item.getFieldName().equals(new String("uploadName"))) { params.put("upName", item.getString()); } if (item.getFieldName().equals(new String("ownRead"))) { params.put("urBean", item.getString()); } if (item.getFieldName().equals(new String("ownWrite"))) { params.put("uwBean", item.getString()); } if (item.getFieldName().equals(new String("ownExecute"))) { params.put("uxBean", item.getString()); } if (item.getFieldName().equals(new String("grRead"))) { params.put("grBean", item.getString()); } if (item.getFieldName().equals(new String("grWrite"))) { params.put("gwBean", item.getString()); } if (item.getFieldName().equals(new String("grExecute"))) { params.put("gxBean", item.getString()); } if (item.getFieldName().equals(new String("othRead"))) { params.put("orBean", item.getString()); } if (item.getFieldName().equals(new String("othWrite"))) { params.put("owBean", item.getString()); } if (item.getFieldName().equals(new String("othExecute"))) { params.put("oxBean", item.getString()); } } else { // item is not a form field, do file upload String s = item.getName(); s = FilenameUtils.getName(s); String tempDir = System.getProperty("java.io.tmpdir") + "/uploads/" + request.getRemoteUser(); String origfile = tempDir + "/" + s; params.put("origfile", origfile); File f = new File(tempDir); if (!f.exists()) f.mkdirs(); File serverSideFile = new File(tempDir, s); item.write(serverSideFile); item.delete(); } } if (action == null) { doUpload(request, response, params); } } if (action != null) { try { Method method = this.getClass().getMethod(action, new Class[] { ActionRequest.class, ActionResponse.class }); method.invoke(this, new Object[] { request, response }); } catch (IllegalArgumentException ex) { Logger.getLogger(LFCFileStoragePortlet.class.getName()).log(Level.SEVERE, null, ex); } catch (InvocationTargetException ex) { Logger.getLogger(LFCFileStoragePortlet.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchMethodException e) { System.out.println("-----------------------Nincs ilyen metdus:"); } catch (IllegalAccessException e) { System.out.println("----------------------Nincs jogod a metdushoz"); } } PortletMode pMode = request.getPortletMode(); // upload -- enctype="multipart/form-data" } catch (Exception ex) { Logger.getLogger(LFCFileStoragePortlet.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:net.sourceforge.stripes.controller.multipart.CommonsMultipartWrapper.java
/** * Responsible for constructing a FileBean object for the named file parameter. If there is no * file parameter with the specified name this method should return null. * * @param name the name of the file parameter * @return a FileBean object wrapping the uploaded file *///from w w w . ja v a2 s. c o m public FileBean getFileParameterValue(String name) { final FileItem item = this.files.get(name); if (item == null || ((item.getName() == null || item.getName().length() == 0) && item.getSize() == 0)) { return null; } else { // Attempt to ensure the file name is just the basename with no path included String filename = item.getName(); int index; if (WINDOWS_PATH_PREFIX_PATTERN.matcher(filename).find()) index = filename.lastIndexOf('\\'); else index = filename.lastIndexOf('/'); if (index >= 0 && index + 1 < filename.length() - 1) filename = filename.substring(index + 1); // Use an anonymous inner subclass of FileBean that overrides all the // methods that rely on having a File present, to use the FileItem // created by commons upload instead. return new FileBean(null, item.getContentType(), filename, this.charset) { @Override public long getSize() { return item.getSize(); } @Override public InputStream getInputStream() throws IOException { return item.getInputStream(); } @Override public void save(File toFile) throws IOException { try { item.write(toFile); delete(); } catch (Exception e) { if (e instanceof IOException) throw (IOException) e; else { IOException ioe = new IOException("Problem saving uploaded file."); ioe.initCause(e); throw ioe; } } } @Override public void delete() throws IOException { item.delete(); } }; } }
From source file:OpenProdocServ.Oper.java
/** * /*from www . j av a2s.c o m*/ * @param request * @param response */ private void InsFile(HttpServletRequest Req, HttpServletResponse response) throws Exception { if (PDLog.isDebug()) PDLog.Debug("InsFile"); FileItem ItemFile = null; InputStream FileData = null; HashMap ListFields = new HashMap(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000000); ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(Req); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) ListFields.put(item.getFieldName(), item.getString()); else { FileData = item.getInputStream(); ItemFile = item; } } DriverGeneric PDSession = getSessOPD(Req); String Id = (String) ListFields.get("Id"); String Ver = (String) ListFields.get("Ver"); PDSession.InsertFile(Id, Ver, FileData); if (FileData != null) FileData.close(); if (ItemFile != null) ItemFile.delete(); items.clear(); // to help and speed gc PrintWriter out = response.getWriter(); Answer(Req, out, true, null, null); out.close(); }
From source file:org.aeroivr.rsmc.web.controller.SetVoiceXMLApplicationPageController.java
private void processUploadedFile(final FileItem item) throws Exception { final File warFile = ServiceLocator.getInstance().getTempFileWithUniqueName("temp_", ".war"); item.write(warFile);//from w w w . j a v a 2 s. c om item.delete(); final File rsmcServletFolder = ServiceLocator.getInstance().getFile(getServletContext().getRealPath("/")); final AppServerAdminClient client = ServiceLocator.getInstance().getAppServerAdminClient(); client.setVoiceXMLApplication(rsmcServletFolder.getParent(), warFile.getPath()); }
From source file:org.apache.catalina.manager.HTMLManagerServlet.java
/** * Process a POST request for the specified resource. * * @param request The servlet request we are processing * @param response The servlet response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet-specified error occurs *//*from www. ja v a2s . c o m*/ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Identify the request parameters that we need String command = request.getPathInfo(); if (command == null || !command.equals("/upload")) { doGet(request, response); return; } // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; // Create a new file upload handler DiskFileUpload upload = new DiskFileUpload(); // Get the tempdir File tempdir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir"); // Set upload parameters upload.setSizeMax(-1); upload.setRepositoryPath(tempdir.getCanonicalPath()); // Parse the request String basename = null; File appBaseDir = null; String war = null; FileItem warUpload = null; try { List items = upload.parseRequest(request); // Process the uploaded fields Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { if (item.getFieldName().equals("deployWar") && warUpload == null) { warUpload = item; } else { item.delete(); } } } while (true) { if (warUpload == null) { message = sm.getString("htmlManagerServlet.deployUploadNoFile"); break; } war = warUpload.getName(); if (!war.toLowerCase().endsWith(".war")) { message = sm.getString("htmlManagerServlet.deployUploadNotWar", war); break; } // Get the filename if uploaded name includes a path if (war.lastIndexOf('\\') >= 0) { war = war.substring(war.lastIndexOf('\\') + 1); } if (war.lastIndexOf('/') >= 0) { war = war.substring(war.lastIndexOf('/') + 1); } // Identify the appBase of the owning Host of this Context // (if any) String appBase = null; appBase = ((Host) context.getParent()).getAppBase(); appBaseDir = new File(appBase); if (!appBaseDir.isAbsolute()) { appBaseDir = new File(System.getProperty("catalina.base"), appBase); } basename = war.substring(0, war.indexOf(".war")); File file = new File(appBaseDir, war); if (file.exists()) { message = sm.getString("htmlManagerServlet.deployUploadWarExists", war); break; } warUpload.write(file); try { URL url = file.toURL(); war = url.toString(); war = "jar:" + war + "!/"; } catch (MalformedURLException e) { file.delete(); throw e; } break; } } catch (Exception e) { message = sm.getString("htmlManagerServlet.deployUploadFail", e.getMessage()); log(message, e); } finally { if (warUpload != null) { warUpload.delete(); } warUpload = null; } // Extract the nested context deployment file (if any) File localWar = new File(appBaseDir, basename + ".war"); File localXml = new File(configBase, basename + ".xml"); try { extractXml(localWar, localXml); } catch (IOException e) { log("managerServlet.extract[" + localWar + "]", e); return; } String config = null; try { if (localXml.exists()) { URL url = localXml.toURL(); config = url.toString(); } } catch (MalformedURLException e) { throw e; } // If there were no errors, deploy the WAR if (message.length() == 0) { message = deployInternal(config, null, war); } list(request, response, message); }
From source file:org.apache.catalina.servlets.HTMLManagerServlet.java
/** * Process a POST request for the specified resource. * * @param request The servlet request we are processing * @param response The servlet response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet-specified error occurs *//*from w w w .jav a2s.c o m*/ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Identify the request parameters that we need String command = request.getPathInfo(); if (command == null || !command.equals("/upload")) { doGet(request, response); return; } // Prepare our output writer to generate the response message Locale locale = Locale.getDefault(); String charset = context.getCharsetMapper().getCharset(locale); response.setLocale(locale); response.setContentType("text/html; charset=" + charset); String message = ""; // Create a new file upload handler DiskFileUpload upload = new DiskFileUpload(); // Get the tempdir File tempdir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir"); // Set upload parameters upload.setSizeMax(-1); upload.setRepositoryPath(tempdir.getCanonicalPath()); // Parse the request String war = null; FileItem warUpload = null; try { List items = upload.parseRequest(request); // Process the uploaded fields Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { if (item.getFieldName().equals("installWar") && warUpload == null) { warUpload = item; } else { item.delete(); } } } while (true) { if (warUpload == null) { message = sm.getString("htmlManagerServlet.installUploadNoFile"); break; } war = warUpload.getName(); if (!war.toLowerCase().endsWith(".war")) { message = sm.getString("htmlManagerServlet.installUploadNotWar", war); break; } // Get the filename if uploaded name includes a path if (war.lastIndexOf('\\') >= 0) { war = war.substring(war.lastIndexOf('\\') + 1); } if (war.lastIndexOf('/') >= 0) { war = war.substring(war.lastIndexOf('/') + 1); } // Identify the appBase of the owning Host of this Context // (if any) String appBase = null; File appBaseDir = null; appBase = ((Host) context.getParent()).getAppBase(); appBaseDir = new File(appBase); if (!appBaseDir.isAbsolute()) { appBaseDir = new File(System.getProperty("catalina.base"), appBase); } File file = new File(appBaseDir, war); if (file.exists()) { message = sm.getString("htmlManagerServlet.installUploadWarExists", war); break; } warUpload.write(file); try { URL url = file.toURL(); war = url.toString(); war = "jar:" + war + "!/"; } catch (MalformedURLException e) { file.delete(); throw e; } break; } } catch (Exception e) { message = sm.getString("htmlManagerServlet.installUploadFail", e.getMessage()); log(message, e); } finally { if (warUpload != null) { warUpload.delete(); } warUpload = null; } // If there were no errors, install the WAR if (message.length() == 0) { message = install(null, null, war); } list(request, response, message); }
From source file:org.apache.hupa.server.FileItemRegistry.java
public void remove(FileItem item) { if (item != null) { logger.debug("Remove item " + item.getName() + " with name " + item.getFieldName()); map.remove(item.getFieldName()); // Remove temporary stuff item.delete(); }//from www . ja v a 2 s .c o m }
From source file:org.apache.jackrabbit.server.util.HttpMultipartPost.java
/** * Release all file items hold with the name-to-items map. specially those * having a tmp-file associated with./*from w ww. j av a2 s . c o m*/ * * @see FileItem#delete() */ synchronized void dispose() { checkInitialized(); for (List<FileItem> fileItems : nameToItems.values()) { for (FileItem fileItem : fileItems) { fileItem.delete(); } } nameToItems.clear(); fileParamNames.clear(); initialized = false; }
From source file:org.apache.myfaces.custom.fileupload.HtmlFileUploadRendererTest.java
public void testUploadedFileDefaultMemoryImplSerializable() throws Exception { String fieldName = "inputFile"; String contentType = "someType"; MockControl control = MockControl.createControl(FileItem.class); FileItem item = (FileItem) control.getMock(); item.getName();/* www . j av a 2 s. c om*/ control.setReturnValue(fieldName, 1); item.getContentType(); control.setReturnValue(contentType, 1); item.getSize(); control.setReturnValue(0, 1); item.getInputStream(); control.setReturnValue(new InputStream() { public int read() throws IOException { return -1; } }, 1); item.delete(); control.setVoidCallable(1); control.replay(); UploadedFileDefaultMemoryImpl original = new UploadedFileDefaultMemoryImpl(item); ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(original); oos.close(); byte[] serializedArray = out.toByteArray(); InputStream in = new ByteArrayInputStream(serializedArray); ObjectInputStream ois = new ObjectInputStream(in); UploadedFileDefaultMemoryImpl copy = (UploadedFileDefaultMemoryImpl) ois.readObject(); assertEquals(original.getName(), copy.getName()); assertEquals(original.getContentType(), copy.getContentType()); assertEquals(copy.getSize(), 0); copy.getStorageStrategy().deleteFileContents(); }