List of usage examples for org.apache.commons.fileupload DiskFileUpload setRepositoryPath
public void setRepositoryPath(String repositoryPath)
From source file:com.krawler.spring.importFunctionality.ImportUtil.java
/** * @param request//from w w w .j av a 2s .c om * @param fileid * @return * @throws ServiceException */ private static String uploadDocument(HttpServletRequest request, String fileid) throws ServiceException { String result = ""; try { String destinationDirectory = storageHandlerImpl.GetDocStorePath() + "importplans"; org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload(); org.apache.commons.fileupload.FileItem fi = null; org.apache.commons.fileupload.FileItem docTmpFI = null; List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { KrawlerLog.op.warn("Problem While Uploading file :" + e.toString()); } long size = 0; String Ext = ""; String fileName = null; boolean fileupload = false; java.io.File destDir = new java.io.File(destinationDirectory); fu.setSizeMax(-1); fu.setSizeThreshold(4096); fu.setRepositoryPath(destinationDirectory); java.util.HashMap arrParam = new java.util.HashMap(); for (java.util.Iterator k = fileItems.iterator(); k.hasNext();) { fi = (org.apache.commons.fileupload.FileItem) k.next(); arrParam.put(fi.getFieldName(), fi.getString("UTF-8")); if (!fi.isFormField()) { size = fi.getSize(); fileName = new String(fi.getName().getBytes(), "UTF8"); docTmpFI = fi; fileupload = true; } } if (fileupload) { if (!destDir.exists()) { destDir.mkdirs(); } if (fileName.contains(".")) { Ext = fileName.substring(fileName.lastIndexOf(".")); } if (size != 0) { int startIndex = fileName.contains("\\") ? (fileName.lastIndexOf("\\") + 1) : 0; fileName = fileName.substring(startIndex, fileName.lastIndexOf(".")); fileName = fileName.replaceAll(" ", ""); fileName = fileName.replaceAll("/", ""); result = fileName + "_" + fileid + Ext; File uploadFile = new File(destinationDirectory + "/" + result); docTmpFI.write(uploadFile); // fildoc(fileid, fileName, fileid + Ext, AuthHandler.getUserid(request), size); } } } // catch (ConfigurationException ex) { // Logger.getLogger(ExportImportContacts.class.getName()).log(Level.SEVERE, null, ex); // throw ServiceException.FAILURE("ExportImportContacts.uploadDocument", ex); // } catch (Exception ex) { Logger.getLogger(ImportHandler.class.getName()).log(Level.SEVERE, null, ex); throw ServiceException.FAILURE("ExportImportContacts.uploadDocument", ex); } return result; }
From source file:forseti.JUtil.java
@SuppressWarnings("rawtypes") public static synchronized boolean procesaFicheros(HttpServletRequest req, String dir) { boolean res = true; try {/* w ww . jav a2 s . c o m*/ // construimos el objeto que es capaz de parsear la pericin DiskFileUpload fu = new DiskFileUpload(); // maximo numero de bytes fu.setSizeMax(1024 * 512); // 512 K //System.out.println("Ponemos el tamao mximo"); // tamao por encima del cual los ficheros son escritos directamente en disco fu.setSizeThreshold(4096); // directorio en el que se escribirn los ficheros con tamao superior al soportado en memoria fu.setRepositoryPath("/tmp"); // ordenamos procesar los ficheros List fileItems = fu.parseRequest(req); if (fileItems == null) { //System.out.println("La lista es nula"); return false; } //System.out.println("El nmero de ficheros subidos es: " + fileItems.size()); // Iteramos por cada fichero Iterator i = fileItems.iterator(); FileItem actual = null; //System.out.println("estamos en la iteracin"); while (i.hasNext()) { actual = (FileItem) i.next(); String fileName = actual.getName(); //System.out.println("Nos han subido el fichero" + fileName); // construimos un objeto file para recuperar el trayecto completo File fichero = new File(fileName); //System.out.println("El nombre del fichero es " + fichero.getName()); // nos quedamos solo con el nombre y descartamos el path fichero = new File(dir + fichero.getName()); // escribimos el fichero colgando del nuevo path actual.write(fichero); } } catch (Exception e) { System.out.println("Error de Fichero: " + e.getMessage()); res = false; } return res; }
From source file:nextapp.echo2.webcontainer.filetransfer.JakartaCommonsFileUploadProvider.java
/** * @see nextapp.echo2.webcontainer.filetransfer.MultipartUploadSPI#updateComponent(nextapp.echo2.webrender.Connection, * nextapp.echo2.app.filetransfer.UploadSelect) *//*from w w w.j a va 2 s . co m*/ public void updateComponent(Connection conn, UploadSelect uploadSelect) throws IOException, ServletException { DiskFileUpload handler = null; HttpServletRequest request = null; List items = null; Iterator it = null; FileItem item = null; boolean searching = true; InputStream in = null; int size = 0; String contentType = null; String name = null; try { handler = new DiskFileUpload(); handler.setSizeMax(getFileUploadSizeLimit()); handler.setSizeThreshold(getMemoryCacheThreshold()); handler.setRepositoryPath(getDiskCacheLocation().getCanonicalPath()); request = conn.getRequest(); items = handler.parseRequest(request); searching = true; it = items.iterator(); while (it.hasNext() && searching) { item = (FileItem) it.next(); if (UploadFormService.FILE_PARAMETER_NAME.equals(item.getFieldName())) { in = item.getInputStream(); size = (int) item.getSize(); contentType = item.getContentType(); name = item.getName(); File tempFile = writeTempFile(in, uploadSelect); UploadEvent uploadEvent = new UploadEvent(tempFile, size, contentType, name); UploadSelectPeer.activateUploadSelect(uploadSelect, uploadEvent); searching = false; } } } catch (FileUploadException e) { throw new IOException(e.getMessage()); } }
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 w w w. j ava 2 s . co 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 .j a va 2 s . 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.struts.upload.CommonsMultipartRequestHandler.java
/** * <p> Parses the input stream and partitions the parsed items into a set * of form fields and a set of file items. In the process, the parsed * items are translated from Commons FileUpload <code>FileItem</code> * instances to Struts <code>FormFile</code> instances. </p> * * @param request The multipart request to be processed. * @throws ServletException if an unrecoverable error occurs. *//* w w w. ja v a2 s.c om*/ public void handleRequest(HttpServletRequest request) throws ServletException { // Get the app config for the current request. ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY); // Create and configure a DIskFileUpload instance. DiskFileUpload upload = new DiskFileUpload(); // The following line is to support an "EncodingFilter" // see http://issues.apache.org/bugzilla/show_bug.cgi?id=23255 upload.setHeaderEncoding(request.getCharacterEncoding()); // Set the maximum size before a FileUploadException will be thrown. upload.setSizeMax(getSizeMax(ac)); // Set the maximum size that will be stored in memory. upload.setSizeThreshold((int) getSizeThreshold(ac)); // Set the the location for saving data on disk. upload.setRepositoryPath(getRepositoryPath(ac)); // Create the hash tables to be populated. elementsText = new Hashtable(); elementsFile = new Hashtable(); elementsAll = new Hashtable(); // Parse the request into file items. List items = null; try { items = upload.parseRequest(request); } catch (DiskFileUpload.SizeLimitExceededException e) { // Special handling for uploads that are too big. request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE); return; } catch (FileUploadException e) { log.error("Failed to parse multipart request", e); throw new ServletException(e); } // Partition the items into form fields and files. Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { addTextParameter(request, item); } else { addFileParameter(item); } } }
From source file:org.araneaframework.servlet.filter.StandardServletFileUploadFilterService.java
protected void action(Path path, InputData input, OutputData output) throws Exception { HttpServletRequest request = ((ServletInputData) input).getRequest(); if (FileUpload.isMultipartContent(request)) { Map fileItems = new HashMap(); Map parameterLists = new HashMap(); // Create a new file upload handler DiskFileUpload upload = new DiskFileUpload(); if (useRequestEncoding) upload.setHeaderEncoding(request.getCharacterEncoding()); else if (multipartEncoding != null) upload.setHeaderEncoding(multipartEncoding); // Set upload parameters if (maximumCachedSize != null) upload.setSizeThreshold(maximumCachedSize.intValue()); if (maximumSize != null) upload.setSizeMax(maximumSize.longValue()); if (tempDirectory != null) upload.setRepositoryPath(tempDirectory); // Parse the request List items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { fileItems.put(item.getFieldName(), item); } else { List parameterValues = (List) parameterLists.get(item.getFieldName()); if (parameterValues == null) { parameterValues = new ArrayList(); parameterLists.put(item.getFieldName(), parameterValues); }/* w ww. ja v a 2s . c om*/ parameterValues.add(item.getString()); } } log.debug("Parsed multipart request, found '" + fileItems.size() + "' file items and '" + parameterLists.size() + "' request parameters"); output.extend(ServletFileUploadInputExtension.class, new StandardServletFileUploadInputExtension(fileItems)); request = new MultipartWrapper(request, parameterLists); ((ServletOverridableInputData) input).setRequest(request); } super.action(path, input, output); }
From source file:org.bootchart.servlet.RenderServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { File logTmpFile = null;/*from w ww. jav a2s . c o m*/ try { DiskFileUpload fu = new DiskFileUpload(); // maximum size before a FileUploadException will be thrown fu.setSizeMax(32 * 1024 * 1024); fu.setSizeThreshold(4 * 1024 * 1024); fu.setRepositoryPath(TEMP_DIR); String format = "png"; List fileItems = fu.parseRequest(request); File tmpFile = File.createTempFile("file.", ".tmp"); String tmpName = tmpFile.getName().substring(5, tmpFile.getName().length() - 4); tmpFile.delete(); for (Iterator i = fileItems.iterator(); i.hasNext();) { FileItem fi = (FileItem) i.next(); String name = fi.getName(); if (name == null || name.length() == 0) { if ("format".equals(fi.getFieldName())) { format = fi.getString(); } continue; } if (name.indexOf("bootchart") != -1) { String suffix = ""; if (name.endsWith(".tar.gz")) { suffix = ".tar.gz"; } else { suffix = name.substring(name.lastIndexOf('.')); } logTmpFile = new File(TEMP_DIR, "bootchart." + tmpName + suffix); fi.write(logTmpFile); } } if (logTmpFile == null || !logTmpFile.exists()) { writeError(response, LOG_FORMAT_ERROR, null); log.severe("No log tarball provided"); return; } // Render PNG by default if (format == null) { format = "png"; } boolean prune = true; new File(TEMP_DIR + "/images").mkdirs(); String tmpImgFileName = TEMP_DIR + "/images/" + "bootchart." + tmpName; File tmpImgFile = null; try { tmpImgFileName = Main.render(logTmpFile, format, prune, tmpImgFileName); tmpImgFile = new File(tmpImgFileName); FileInputStream fis = new FileInputStream(tmpImgFileName); OutputStream os = response.getOutputStream(); String contentType = "application/octet-stream"; String suffix = ""; if ("png".equals(format)) { contentType = "image/png"; suffix = new PNGRenderer().getFileSuffix(); } else if ("svg".equals(format)) { contentType = "image/svg+xml"; suffix = new SVGRenderer().getFileSuffix(); } else if ("eps".equals(format)) { contentType = "image/eps"; suffix = new EPSRenderer().getFileSuffix(); } response.setContentType(contentType); response.setHeader("Content-disposition", "attachment; filename=bootchart." + suffix); byte[] buff = new byte[4096]; while (true) { int read = fis.read(buff); if (read < 0) { break; } os.write(buff, 0, read); os.flush(); } fis.close(); } finally { if (tmpImgFile != null && !tmpImgFile.delete()) { tmpImgFile.deleteOnExit(); } } } catch (Exception e) { writeError(response, null, e); log.log(Level.SEVERE, "", e); } if (logTmpFile != null && !logTmpFile.delete()) { logTmpFile.deleteOnExit(); } }
From source file:org.chiba.adapter.web.HttpRequestHandler.java
/** * @param request Servlet request/*w ww. java2s .c o m*/ * @param trigger Trigger control * @return the calculated trigger * @throws XFormsException If an error occurs */ protected String processMultiPartRequest(HttpServletRequest request, String trigger) throws XFormsException { DiskFileUpload upload = new DiskFileUpload(); String encoding = request.getCharacterEncoding(); if (encoding == null) { encoding = "ISO-8859-1"; } upload.setRepositoryPath(this.uploadRoot); if (LOGGER.isDebugEnabled()) { LOGGER.debug("root dir for uploads: " + this.uploadRoot); } List items; try { items = upload.parseRequest(request); } catch (FileUploadException fue) { throw new XFormsException(fue); } Map formFields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); String itemName = item.getName(); String fieldName = item.getFieldName(); String id = fieldName.substring(Config.getInstance().getProperty("chiba.web.dataPrefix").length()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Multipart item name is: " + itemName + " and fieldname is: " + fieldName + " and id is: " + id); LOGGER.debug("Is formfield: " + item.isFormField()); LOGGER.debug("Content: " + item.getString()); } if (item.isFormField()) { // check for upload-remove action if (fieldName.startsWith(getRemoveUploadPrefix())) { id = fieldName.substring(getRemoveUploadPrefix().length()); // if data is null, file will be removed ... // TODO: remove the file from the disk as well chibaBean.updateControlValue(id, "", "", null); continue; } // It's a field name, it means that we got a non-file // form field. Upload is not required. We must treat it as we // do in processUrlencodedRequest() processMultipartParam(formFields, fieldName, item, encoding); } else { String uniqueFilename = new File(getUniqueParameterName("file"), new File(itemName).getName()) .getPath(); File savedFile = new File(this.uploadRoot, uniqueFilename); byte[] data = null; data = processMultiPartFile(item, id, savedFile, encoding, data); // if data is null, file will be removed ... // TODO: remove the file from the disk as well chibaBean.updateControlValue(id, item.getContentType(), itemName, data); } // handle regular fields if (formFields.size() > 0) { Iterator it = formFields.keySet().iterator(); while (it.hasNext()) { fieldName = (String) it.next(); String[] values = (String[]) formFields.get(fieldName); // [1] handle data handleData(fieldName, values); // [2] handle selector handleSelector(fieldName, values[0]); // [3] handle trigger trigger = handleTrigger(trigger, fieldName); } } } return trigger; }
From source file:org.hdiv.config.multipart.StrutsMultipartConfig.java
/** * Parses the input stream and partitions the parsed items into a set of form fields and a set of file items. * /*from ww w .jav a 2 s. co m*/ * @param request * The multipart request wrapper. * @param servletContext * Our ServletContext object * @return multipart processed request * @throws HdivMultipartException * if an unrecoverable error occurs. */ public HttpServletRequest handleMultipartRequest(RequestWrapper request, ServletContext servletContext) throws HdivMultipartException { DiskFileUpload upload = new DiskFileUpload(); upload.setHeaderEncoding(request.getCharacterEncoding()); // Set the maximum size before a FileUploadException will be thrown. upload.setSizeMax(getSizeMax()); // Set the maximum size that will be stored in memory. upload.setSizeThreshold((int) getSizeThreshold()); // Set the the location for saving data on disk. upload.setRepositoryPath(getRepositoryPath(servletContext)); List<FileItem> items = null; try { items = upload.parseRequest(request); } catch (DiskFileUpload.SizeLimitExceededException e) { if (log.isErrorEnabled()) { log.error("Size limit exceeded exception"); } // Special handling for uploads that are too big. throw new HdivMultipartException(e); } catch (FileUploadException e) { if (log.isErrorEnabled()) { log.error("Failed to parse multipart request", e); } throw new HdivMultipartException(e); } // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { this.addTextParameter(request, item); } else { this.addFileParameter(request, item); } } return request; }