List of usage examples for org.apache.commons.fileupload DiskFileUpload setSizeMax
public void setSizeMax(long sizeMax)
From source file:com.krawler.svnwebclient.util.Uploader.java
public void doPost(HttpServletRequest request, HttpServletResponse responce, String destinationDirectory, String tempDirectory) throws SessionExpiredException { File tempDir = new File(tempDirectory); String sep = StorageHandler.GetFileSeparator(); if (!tempDir.exists()) { tempDir.mkdirs();/*from ww w . j av a 2s. c om*/ } DiskFileUpload fu = new DiskFileUpload(); // maximum size before a FileUploadException will be thrown fu.setSizeMax(-1); // maximum size that will be stored in memory fu.setSizeThreshold(4096); // the location for saving data that is larger than getSizeThreshold() fu.setRepositoryPath(tempDirectory); List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { Logger.getInstance(Uploader.class).error(e, e); } String docid1 = null; String docownerid = null; for (Iterator k = fileItems.iterator(); k.hasNext();) { FileItem fi1 = (FileItem) k.next(); try { if (fi1.getFieldName().toString().equals("docid")) { docid1 = new String(fi1.getString().getBytes(), "UTF8"); } if (fi1.getFieldName().toString().equals("docownerid")) { docownerid = new String(fi1.getString().getBytes(), "UTF8"); } } catch (UnsupportedEncodingException e) { // Logger.getInstance(Uploader.class).error(e, e); } } if (docid1.equals("")) { docid1 = UUID.randomUUID().toString(); this.setFlagType(true); docownerid = AuthHandler.getUserid(request); } else { this.setFlagType(false); } try { if (docownerid.equalsIgnoreCase("my")) { docownerid = AuthHandler.getUserid(request); } destinationDirectory = com.krawler.esp.handlers.StorageHandler.GetDocStorePath() + sep + docownerid; } catch (ConfigurationException ex) { this.isUploaded = false; this.errorMessage = "Problem occurred while uploading file"; return; } File destDir = new File(destinationDirectory); if (!destDir.exists()) { destDir.mkdirs(); } this.parameters.put("destinationDirectory", destinationDirectory); for (Iterator i = fileItems.iterator(); i.hasNext();) { FileItem fi = (FileItem) i.next(); /* * try{ String docid1 = fi.getString("docid"); }catch(Exception e){} */ if (fi.isFormField()) { try { if (fi.getFieldName().toString().equals("docid") && new String(fi.getString().getBytes(), "UTF8").equals("")) { this.parameters.put(fi.getFieldName(), docid1); } else { this.parameters.put(fi.getFieldName(), new String(fi.getString().getBytes(), "UTF8")); } } catch (UnsupportedEncodingException e) { Logger.getInstance(Uploader.class).error(e, e); } } else { // filename on the client String fileName = null; try { fileName = new String(fi.getName().getBytes(), "UTF8"); // org.tmatesoft.svn.core.internal.wc.SVNFileUtil.isExecutable(fi); String filext = ""; if (fileName.contains(".")) filext = fileName.substring(fileName.lastIndexOf(".")); if (fi.getSize() != 0) { this.isUploaded = true; // write the file File uploadFile = new File( destinationDirectory + sep + FileUtil.getLastPathElement(docid1 + filext)); fi.write(uploadFile); this.parameters.put("svnName", uploadFile.getName()); if (filext.equals("")) { this.parameters.put("fileExt", filext); } else { this.parameters.put("fileExt", filext.substring(1)); } } else { this.isUploaded = false; this.errorMessage = "Cannot upload a 0 byte file"; } } catch (Exception e) { this.isUploaded = false; this.errorMessage = "Problem occurred while uploading file"; Logger.getInstance(Uploader.class).error(e, e); } this.parameters.put(FormParameters.FILE_NAME, FileUtil.getLastPathElement(fileName)); } } }
From source file:com.exedio.copernica.Form.java
@SuppressWarnings("deprecation") // TODO use new way of fileupload public Form(final HttpServletRequest request) { this.request = request; if (FileUploadBase.isMultipartContent(request)) { final org.apache.commons.fileupload.DiskFileUpload upload = new org.apache.commons.fileupload.DiskFileUpload(); final int maxSize = 100 * 1024; // TODO: make this configurable upload.setSizeThreshold(maxSize); // TODO: always save to disk upload.setSizeMax(maxSize); //upload.setRepositoryPath(""); multipartContentParameters = new HashMap<String, Object>(); try {/* ww w.j av a 2 s .co m*/ for (Iterator<?> i = upload.parseRequest(request).iterator(); i.hasNext();) { final FileItem item = (FileItem) i.next(); if (item.isFormField()) { final String name = item.getFieldName(); final String value = item.getString(); multipartContentParameters.put(name, value); } else { final String name = item.getFieldName(); multipartContentParameters.put(name, item); } } } catch (FileUploadException e) { throw new RuntimeException(e); } } else { multipartContentParameters = null; } }
From source file:com.sun.licenseserver.License.java
/** * Construct a license object using the input provided in the * request object,// ww w .j a va2s.c o m * * @param req */ public License(HttpServletRequest req) { if (FileUpload.isMultipartContent(req)) { DiskFileUpload upload = new DiskFileUpload(); upload.setSizeMax(2 * 1024 * 1024); List items; try { items = upload.parseRequest(req); } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { if (item.getSize() > 2 * 1024 * 1024) { continue; } m_log.fine("Size of uploaded license is [" + item.getSize() + "]"); try { license = item.getInputStream(); licSize = item.getSize(); mime = item.getContentType(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return; } } else { String name = item.getFieldName(); String value = item.getString(); m_log.fine("MC ItemName [" + name + "] Value[" + value + "]"); if (name != null) { if (name.equals("id")) { id = value; continue; } if (name.equals("userId")) { userId = value; continue; } if (name.equals("contentId")) { contentId = value; continue; } if (name.equals("shopId")) { shopId = value; continue; } } } } } }
From source file:com.sun.faban.harness.webclient.RunUploader.java
/** * Post method to upload the run.// w ww . j a v a 2 s. com * @param request The servlet request * @param response The servlet response * @throws ServletException If the servlet fails * @throws IOException If there is an I/O error */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String host = null; String key = null; boolean origin = false; // Whether the upload is to the original // run requestor. If so, key is needed. DiskFileUpload fu = new DiskFileUpload(); // No maximum size fu.setSizeMax(-1); // maximum size that will be stored in memory fu.setSizeThreshold(4096); // the location for saving data that is larger than getSizeThreshold() fu.setRepositoryPath(Config.TMP_DIR); List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e); } // assume we know there are two files. The first file is a small // text file, the second is unknown and is written to a file on // the server for (Iterator i = fileItems.iterator(); i.hasNext();) { FileItem item = (FileItem) i.next(); String fieldName = item.getFieldName(); if (item.isFormField()) { if ("host".equals(fieldName)) { host = item.getString(); } else if ("key".equals(fieldName)) { key = item.getString(); } else if ("origin".equals(fieldName)) { String value = item.getString(); origin = Boolean.parseBoolean(value); } continue; } if (host == null) { logger.warning("Host not received on upload request!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } // The host, origin, key info must be here before we receive // any file. if (origin) { if (Config.daemonMode != Config.DaemonModes.POLLEE) { logger.warning("Origin upload requested. Not pollee!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } if (key == null) { logger.warning("Origin upload requested. No key!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } if (!RunRetriever.authenticate(host, key)) { logger.warning("Origin upload requested. " + "Host/key mismatch: " + host + '/' + key + "!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } } if (!"jarfile".equals(fieldName)) // ignore continue; String fileName = item.getName(); if (fileName == null) // We don't process files without names continue; // Now, this name may have a path attached, dependent on the // source browser. We need to cover all possible clients... char[] pathSeparators = { '/', '\\' }; // Well, if there is another separator we did not account for, // just add it above. for (int j = 0; j < pathSeparators.length; j++) { int idx = fileName.lastIndexOf(pathSeparators[j]); if (idx != -1) { fileName = fileName.substring(idx + 1); break; } } // Ignore all non-jarfiles. if (!fileName.toLowerCase().endsWith(".jar")) continue; File uploadFile = new File(Config.TMP_DIR, host + '.' + fileName); try { item.write(uploadFile); } catch (Exception e) { throw new ServletException(e); } File runTmp = unjarTmp(uploadFile); String runId = null; if (origin) { // Change origin file to know where this run came from. File metaInf = new File(runTmp, "META-INF"); File originFile = new File(metaInf, "origin"); if (!originFile.exists()) { logger.warning("Origin upload requested. Origin file" + "does not exist!"); response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Origin file does not exist!"); break; } RunId origRun; try { origRun = new RunId(readStringFromFile(originFile).trim()); } catch (IndexOutOfBoundsException e) { response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Origin file error. " + e.getMessage()); break; } runId = origRun.getBenchName() + '.' + origRun.getRunSeq(); String localHost = origRun.getHostName(); if (!localHost.equals(Config.FABAN_HOST)) { logger.warning("Origin upload requested. Origin host " + localHost + " does not match this host " + Config.FABAN_HOST + '!'); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } writeStringToFile(runTmp.getName(), originFile); } else { runId = runTmp.getName(); } if (recursiveCopy(runTmp, new File(Config.OUT_DIR, runId))) { uploadFile.delete(); recursiveDelete(runTmp); } else { logger.warning("Origin upload requested. Copy error!"); response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE); break; } response.setStatus(HttpServletResponse.SC_CREATED); break; } }
From source file:com.tern.web.MultiPartEnabledRequest.java
private List uploadFiles(HttpServletRequest req) throws FileUploadException { DiskFileUpload upload = new DiskFileUpload(); /*try //from ww w . j a v a 2 s . c om { upload.setSizeThreshold(res.getInteger("file.upload.size.threshold")); } catch (MissingResourceException e) { // use defaults }*/ try { upload.setSizeMax(MaxFileSize); } catch (MissingResourceException e) { // use defaults } /*try { upload.setRepositoryPath(res.getString("file.upload.repository")); } catch (MissingResourceException e) { // use defaults }*/ List all = new DiskFileUpload().parseRequest(req); return all; }
From source file:com.krawler.esp.servlets.ExportImportContactsServlet.java
public static String uploadDocument(HttpServletRequest request, String fileid, String userId) throws ServiceException { String result = ""; try {// ww w. j a v a 2 s.c o m String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator() + "importcontacts" + StorageHandler.GetFileSeparator() + userId; 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()); 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) { File uploadFile = new File(destinationDirectory + "/" + fileid + Ext); docTmpFI.write(uploadFile); // fildoc(fileid, fileName, fileid + Ext, AuthHandler.getUserid(request), size); result = fileid + Ext; } } } catch (ConfigurationException ex) { Logger.getLogger(importToDoTask.class.getName()).log(Level.SEVERE, null, ex); throw ServiceException.FAILURE("ExportImportContactServlet.uploadDocument", ex); } catch (Exception ex) { Logger.getLogger(importToDoTask.class.getName()).log(Level.SEVERE, null, ex); throw ServiceException.FAILURE("ExportImportContactServlet.uploadDocument", ex); } return result; }
From source file:com.meikai.common.web.servlet.FCKeditorConnectorServlet.java
/** * Manage the Post requests (FileUpload).<br> * /*from ww w. j a v a2s . c om*/ * The servlet accepts commands sent in the following format:<br> * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br> * <br> * It store the file (renaming it in case a file with the same name exists) * and then return an HTML file with a javascript command in it. * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (debug) System.out.println("--- BEGIN Connector DOPOST ---"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); String retVal = "0"; String newName = ""; // edit check user uploader file size int contextLength = request.getContentLength(); int fileSize = (int) (((float) contextLength) / ((float) (1024))); PrintWriter out = response.getWriter(); if (fileSize < 30240) { String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); String currentPath = baseDir + typeStr + "/" + dateCreated.substring(0, 4) + "/" + dateCreated.substring(5) + currentFolderStr; // create user dir makeDirectory(getServletContext().getRealPath("/"), currentPath); String currentDirPath = getServletContext().getRealPath(currentPath); // edit end ++++++++++++++++ if (debug) System.out.println(currentDirPath); if (!commandStr.equals("FileUpload")) retVal = "203"; else { DiskFileUpload upload = new DiskFileUpload(); try { upload.setSizeMax(1 * 1024 * 1024); // ??,??: upload.setSizeThreshold(4096); // ???,??: upload.setRepositoryPath("c:/temp/"); // ?getSizeThreshold()? List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; String nameWithoutExt = getNameWithoutExtension(fileName); String ext = getExtension(fileName); File pathToSave = new File(currentDirPath, fileName); if (FckeditorUtil.extIsAllowed(allowedExtensions, deniedExtensions, typeStr, ext)) { int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); // ? if (logger.isInfoEnabled()) { logger.info("..."); } } else { retVal = "202"; if (debug) System.out.println("Invalid file type: " + ext); } } catch (Exception ex) { ex.printStackTrace(); retVal = "203"; } } } else { retVal = "204"; } out.println("<script type=\"text/javascript\">"); out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:com.sun.faban.harness.webclient.Uploader.java
/** * Responsible for uploading the runs./*from w w w.ja v a2 s .com*/ * @param request * @param response * @return String * @throws java.io.IOException * @throws javax.servlet.ServletException * @throws java.lang.ClassNotFoundException */ public String uploadRuns(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, ClassNotFoundException { // 3. Upload the run HashSet<String> duplicateSet = new HashSet<String>(); HashSet<String> replaceSet = new HashSet<String>(); String host = null; String key = null; boolean origin = false; // Whether the upload is to the original // run requestor. If so, key is needed. DiskFileUpload fu = new DiskFileUpload(); // No maximum size fu.setSizeMax(-1); // maximum size that will be stored in memory fu.setSizeThreshold(4096); // the location for saving data that is larger than // getSizeThreshold() fu.setRepositoryPath(Config.TMP_DIR); List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e); } // assume we know there are two files. The first file is a small // text file, the second is unknown and is written to a file on // the server for (Iterator i = fileItems.iterator(); i.hasNext();) { FileItem item = (FileItem) i.next(); String fieldName = item.getFieldName(); if (item.isFormField()) { if ("host".equals(fieldName)) { host = item.getString(); } else if ("replace".equals(fieldName)) { replaceSet.add(item.getString()); } else if ("key".equals(fieldName)) { key = item.getString(); } else if ("origin".equals(fieldName)) { String value = item.getString(); origin = Boolean.parseBoolean(value); } continue; } if (host == null) { logger.warning("Host not received on upload request!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } // The host, origin, key info must be here before we receive // any file. if (origin) { if (Config.daemonMode != Config.DaemonModes.POLLEE) { logger.warning("Origin upload requested. Not pollee!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } if (key == null) { logger.warning("Origin upload requested. No key!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } if (!RunRetriever.authenticate(host, key)) { logger.warning("Origin upload requested. " + "Host/key mismatch: " + host + '/' + key + "!"); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } } if (!"jarfile".equals(fieldName)) // ignore continue; String fileName = item.getName(); if (fileName == null) // We don't process files without names continue; // Now, this name may have a path attached, dependent on the // source browser. We need to cover all possible clients... char[] pathSeparators = { '/', '\\' }; // Well, if there is another separator we did not account for, // just add it above. for (int j = 0; j < pathSeparators.length; j++) { int idx = fileName.lastIndexOf(pathSeparators[j]); if (idx != -1) { fileName = fileName.substring(idx + 1); break; } } // Ignore all non-jarfiles. if (!fileName.toLowerCase().endsWith(".jar")) continue; File uploadFile = new File(Config.TMP_DIR, host + '.' + fileName); try { item.write(uploadFile); } catch (Exception e) { throw new ServletException(e); } int runIdx = fileName.lastIndexOf("."); String runName = host + '.' + fileName.substring(0, runIdx); File runTmp = unjarTmp(uploadFile); //Check if archived recently if (checkIfArchived(runName) && !(replaceSet.contains(fileName.substring(0, runIdx)))) { //Now check if timestamps are same //Get the timestamp of run being uploaded at this point //ts is timestamp of run being uploaded String ts = getRunIdTimestamp(runName, Config.TMP_DIR); l1: while (true) { //reposTs is timestamp of run being compared in the //repository String reposTs = getRunIdTimestamp(runName, Config.OUT_DIR); if (reposTs.equals(ts)) { duplicateSet.add(fileName.substring(0, runIdx)); } else { runName = getNextRunId(runName); if (checkIfArchived(runName)) continue l1; File newRunNameFile = new File(Config.OUT_DIR, runName); if (newRunNameFile.exists()) { recursiveDelete(newRunNameFile); } if (recursiveCopy(runTmp, newRunNameFile)) { newRunNameFile.setLastModified(runTmp.lastModified()); uploadTags(runName); uploadFile.delete(); recursiveDelete(runTmp); } else { logger.warning("Origin upload requested. " + "Copy error!"); response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE); break; } response.setStatus(HttpServletResponse.SC_CREATED); } break; } } else { //File runTmp = unjarTmp(uploadFile); String runId = null; if (origin) { // Change origin file to know where this run came from. File metaInf = new File(runTmp, "META-INF"); File originFile = new File(metaInf, "origin"); if (!originFile.exists()) { logger.warning("Origin upload requested. " + "Origin file does not exist!"); response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Origin file does not exist!"); break; } RunId origRun; try { origRun = new RunId(readStringFromFile(originFile).trim()); } catch (IndexOutOfBoundsException e) { response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Origin file error. " + e.getMessage()); break; } runId = origRun.getBenchName() + '.' + origRun.getRunSeq(); String localHost = origRun.getHostName(); if (!localHost.equals(Config.FABAN_HOST)) { logger.warning("Origin upload requested. Origin " + "host" + localHost + " does not match this host " + Config.FABAN_HOST + '!'); response.sendError(HttpServletResponse.SC_FORBIDDEN); break; } writeStringToFile(runTmp.getName(), originFile); } else { runId = runTmp.getName(); } File newRunFile = new File(Config.OUT_DIR, runId); if (newRunFile.exists()) { recursiveDelete(newRunFile); } if (recursiveCopy(runTmp, newRunFile)) { newRunFile.setLastModified(runTmp.lastModified()); uploadFile.delete(); uploadTags(runId); recursiveDelete(runTmp); } else { logger.warning("Origin upload requested. Copy error!"); response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE); break; } } response.setStatus(HttpServletResponse.SC_CREATED); //break; } request.setAttribute("duplicates", duplicateSet); return "/duplicates.jsp"; }
From source file:com.sun.faban.harness.webclient.Deployer.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from w w w. j a va 2s . c om*/ List<String> deployNames = new ArrayList<String>(); List<String> cantDeployNames = new ArrayList<String>(); List<String> errDeployNames = new ArrayList<String>(); List<String> invalidNames = new ArrayList<String>(); List<String> errHeaders = new ArrayList<String>(); List<String> errDetails = new ArrayList<String>(); String user = null; String password = null; boolean clearConfig = false; boolean hasPermission = true; // Check whether we have to return text or html boolean acceptHtml = false; String acceptHeader = request.getHeader("Accept"); if (acceptHeader != null && acceptHeader.indexOf("text/html") >= 0) acceptHtml = true; DiskFileUpload fu = new DiskFileUpload(); // No maximum size fu.setSizeMax(-1); // maximum size that will be stored in memory fu.setSizeThreshold(4096); // the location for saving data that is larger than getSizeThreshold() fu.setRepositoryPath(Config.TMP_DIR); StringWriter messageBuffer = new StringWriter(); PrintWriter messageWriter = new PrintWriter(messageBuffer); List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e); } // assume we know there are two files. The first file is a small // text file, the second is unknown and is written to a file on // the server for (Iterator i = fileItems.iterator(); i.hasNext();) { FileItem item = (FileItem) i.next(); String fieldName = item.getFieldName(); if (item.isFormField()) { if ("user".equals(fieldName)) { user = item.getString(); } else if ("password".equals(fieldName)) { password = item.getString(); } else if ("clearconfig".equals(fieldName)) { String value = item.getString(); clearConfig = Boolean.parseBoolean(value); } continue; } if (!"jarfile".equals(fieldName)) continue; String fileName = item.getName(); if (fileName == null) // We don't process files without names continue; if (Config.SECURITY_ENABLED) { if (Config.DEPLOY_USER == null || Config.DEPLOY_USER.length() == 0 || !Config.DEPLOY_USER.equals(user)) { hasPermission = false; break; } if (Config.DEPLOY_PASSWORD == null || Config.DEPLOY_PASSWORD.length() == 0 || !Config.DEPLOY_PASSWORD.equals(password)) { hasPermission = false; break; } } // Now, this name may have a path attached, dependent on the // source browser. We need to cover all possible clients... char[] pathSeparators = { '/', '\\' }; // Well, if there is another separator we did not account for, // just add it above. for (int j = 0; j < pathSeparators.length; j++) { int idx = fileName.lastIndexOf(pathSeparators[j]); if (idx != -1) { fileName = fileName.substring(idx + 1); break; } } // Ignore all non-jarfiles. if (!fileName.toLowerCase().endsWith(".jar")) { invalidNames.add(fileName); continue; } String deployName = fileName.substring(0, fileName.length() - 4); if (deployName.indexOf('.') > -1) { invalidNames.add(deployName); continue; } // Check if we can deploy benchmark or service. // If running or queued, we won't deploy benchmark. // If service being used by current run,we won't deploy service. if (!DeployUtil.canDeployBenchmark(deployName) || !DeployUtil.canDeployService(deployName)) { cantDeployNames.add(deployName); continue; } File uploadFile = new File(Config.BENCHMARK_DIR, fileName); if (uploadFile.exists()) FileHelper.recursiveDelete(uploadFile); try { item.write(uploadFile); } catch (Exception e) { throw new ServletException(e); } try { DeployUtil.processUploadedJar(uploadFile, deployName); } catch (Exception e) { messageWriter.println("\nError deploying " + deployName + ".\n"); e.printStackTrace(messageWriter); errDeployNames.add(deployName); continue; } deployNames.add(deployName); } if (clearConfig) for (String benchName : deployNames) DeployUtil.clearConfig(benchName); if (!hasPermission) response.setStatus(HttpServletResponse.SC_FORBIDDEN); else if (cantDeployNames.size() > 0) response.setStatus(HttpServletResponse.SC_CONFLICT); else if (errDeployNames.size() > 0) response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE); else if (invalidNames.size() > 0) response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE); else if (deployNames.size() > 0) response.setStatus(HttpServletResponse.SC_CREATED); else response.setStatus(HttpServletResponse.SC_NOT_FOUND); StringBuilder b = new StringBuilder(); if (deployNames.size() > 0) { if (deployNames.size() > 1) b.append("Benchmarks/services "); else b.append("Benchmark/service "); for (int i = 0; i < deployNames.size(); i++) { if (i > 0) b.append(", "); b.append((String) deployNames.get(i)); } b.append(" deployed."); errHeaders.add(b.toString()); b.setLength(0); } if (invalidNames.size() > 0) { if (invalidNames.size() > 1) b.append("Invalid deploy files "); else b.append("Invalid deploy file "); for (int i = 0; i < invalidNames.size(); i++) { if (i > 0) b.append(", "); b.append((String) invalidNames.get(i)); } b.append(". Deploy files must have .jar extension."); errHeaders.add(b.toString()); b.setLength(0); } if (cantDeployNames.size() > 0) { if (cantDeployNames.size() > 1) b.append("Cannot deploy benchmarks/services "); else b.append("Cannot deploy benchmark/services "); for (int i = 0; i < cantDeployNames.size(); i++) { if (i > 0) b.append(", "); b.append((String) cantDeployNames.get(i)); } b.append(". Benchmark/services being used or " + "queued up for run."); errHeaders.add(b.toString()); b.setLength(0); } if (errDeployNames.size() > 0) { if (errDeployNames.size() > 1) { b.append("Error deploying benchmarks/services "); for (int i = 0; i < errDeployNames.size(); i++) { if (i > 0) b.append(", "); b.append((String) errDeployNames.get(i)); } } errDetails.add(messageBuffer.toString()); errHeaders.add(b.toString()); b.setLength(0); } if (!hasPermission) errHeaders.add("Permission denied!"); Writer writer = response.getWriter(); if (acceptHtml) writeHtml(request, writer, errHeaders, errDetails); else writeText(writer, errHeaders, errDetails); writer.flush(); writer.close(); } catch (ServletException e) { logger.log(Level.SEVERE, e.getMessage(), e); throw e; } catch (IOException e) { logger.log(Level.SEVERE, e.getMessage(), e); throw e; } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); throw new ServletException(e); } }
From source file:easyJ.http.upload.CommonsMultipartRequestHandler.java
/** * 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. * //from www . ja v a 2 s. c o m * @param request * The multipart request to be processed. * @throws ServletException * if an unrecoverable error occurs. */ 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(); // Set the maximum size before a FileUploadException will be thrown. upload.setSizeMax((int) 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) { EasyJLog.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); } } }