List of usage examples for org.apache.commons.fileupload DiskFileUpload setRepositoryPath
public void setRepositoryPath(String repositoryPath)
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();/* w w w . j a v a2s . co m*/ } 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.krawler.esp.servlets.ExportImportContactsServlet.java
public static String uploadDocument(HttpServletRequest request, String fileid, String userId) throws ServiceException { String result = ""; try {/*from ww w.ja 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:forseti.JSubirArchivo.java
@SuppressWarnings("rawtypes") public int processFiles(HttpServletRequest request, boolean onlyOne) // Request No debe contener parametros de formulario, sino solo los parmetro del archivo { int numFiles = 0, thisFile = 0; try {/*from www. ja v a 2 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 * m_MaxSize); // 512 K // 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(request); if (fileItems == null) { m_Error += JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 3) + " null"; return 0; } // Iteramos por cada fichero Iterator i = fileItems.iterator(); FileItem actual = null; if (onlyOne) { actual = (FileItem) i.next(); String fileName = actual.getName(); // construimos un objeto file para recuperar el trayecto completo File file = new File(fileName); // Verifica que el archivo sea de la extension esperada for (int f = 0; f < m_Files.size(); f++) { String ext = "." + getExt(f).toLowerCase(); System.out.println("Archivo: " + fileName + " Ext esperada: " + ext); if (file.getName().toLowerCase().indexOf(ext) != -1) { // nos quedamos solo con el nombre y descartamos el path file = new File(m_Path + file.getName()); // escribimos el fichero colgando del nuevo path actual.write(file); MyUploadedFiles part = (MyUploadedFiles) m_Files.elementAt(thisFile); part.m_File = file.getName(); numFiles += 1; break; } } if (numFiles == 0) m_Error += " " + JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 4) + " " + file.getName(); } else { while ((actual = (FileItem) i.next()) != null) { String fileName = actual.getName(); // construimos un objeto file para recuperar el trayecto completo File file = new File(fileName); String ext = "." + getExt(thisFile).toLowerCase(); System.out.println("Archivo: " + fileName + " Ext esperada: " + ext); // Verifica que el archivo sea de la extension esperada if (file.getName().toLowerCase().indexOf(ext) != -1) { // nos quedamos solo con el nombre y descartamos el path file = new File(m_Path + file.getName()); // escribimos el fichero colgando del nuevo path actual.write(file); MyUploadedFiles part = (MyUploadedFiles) m_Files.elementAt(thisFile); part.m_File = file.getName(); numFiles += 1; } else m_Error += " " + JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 4) + " " + file.getName() + " - " + ext; thisFile += 1; } System.out.println("Despues while"); } } catch (Exception e) { if (e != null) m_Error += " " + JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 3) + " " + e.getMessage(); //"Error al subir archivos: " + e.getMessage(); } return numFiles; }
From source file:com.sun.faban.harness.webclient.RunUploader.java
/** * Post method to upload the run./* w w w. j a v a2 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.meikai.common.web.servlet.FCKeditorConnectorServlet.java
/** * Manage the Post requests (FileUpload).<br> * //from w ww .j a v a2 s . c o m * 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./*ww w . j a v a 2 s .c o m*/ * @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.krawler.esp.servlets.importProjectPlanCSV.java
public static String uploadDocument(HttpServletRequest request, String fileid) throws ServiceException { String result = ""; try {/*from www . j a va 2s.c o m*/ String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator() + "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()); 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(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex); throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex); } catch (Exception ex) { Logger.getLogger(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex); throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex); } return result; }
From source file:com.sun.faban.harness.webclient.Deployer.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/* w w w .ja v a 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 ww w . 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); } } }
From source file:com.sun.faban.harness.webclient.CLIServlet.java
private void doSubmit(String[] reqC, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (reqC.length < 3) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Benchmark and profile not provided in request."); return;/*w ww.j av a 2 s .c o m*/ } // first is the bench name BenchmarkDescription desc = BenchmarkDescription.getDescription(reqC[1]); if (desc == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Benchmark " + reqC[1] + " not deployed."); return; } try { String user = null; String password = null; boolean hasPermission = true; ArrayList<String> runIdList = new ArrayList<String>(); DiskFileUpload fu = new DiskFileUpload(); // No maximum size fu.setSizeMax(-1); // maximum size that will be stored in memory fu.setSizeThreshold(8192); // the location for saving data larger than getSizeThreshold() fu.setRepositoryPath(Config.TMP_DIR); List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e); } for (Iterator i = fileItems.iterator(); i.hasNext();) { FileItem item = (FileItem) i.next(); String fieldName = item.getFieldName(); if (item.isFormField()) { if ("sun".equals(fieldName)) { user = item.getString(); } else if ("sp".equals(fieldName)) { password = item.getString(); } continue; } if (reqC[2] == null) // No profile break; if (desc == null) break; if (!"configfile".equals(fieldName)) continue; if (Config.SECURITY_ENABLED) { if (Config.CLI_SUBMITTER == null || Config.CLI_SUBMITTER.length() == 0 || !Config.CLI_SUBMITTER.equals(user)) { hasPermission = false; break; } if (Config.SUBMIT_PASSWORD == null || Config.SUBMIT_PASSWORD.length() == 0 || !Config.SUBMIT_PASSWORD.equals(password)) { hasPermission = false; break; } } String usrDir = Config.PROFILES_DIR + reqC[2]; File dir = new File(usrDir); if (dir.exists()) { if (!dir.isDirectory()) { logger.severe(usrDir + " should be a directory"); dir.delete(); logger.fine(dir + " deleted"); } else logger.fine("Saving parameter file to" + usrDir); } else { logger.fine("Creating new profile directory for " + reqC[2]); if (dir.mkdirs()) logger.fine("Created new profile directory " + usrDir); else logger.severe("Failed to create profile " + "directory " + usrDir); } // Save the latest config file into the profile directory String dstFile = Config.PROFILES_DIR + reqC[2] + File.separator + desc.configFileName + "." + desc.shortName; item.write(new File(dstFile)); runIdList.add(RunQ.getHandle().addRun(user, reqC[2], desc)); } response.setContentType("text/plain"); Writer writer = response.getWriter(); if (!hasPermission) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); writer.write("Permission denied!\n"); } if (runIdList.size() == 0) writer.write("No runs submitted.\n"); for (String newRunId : runIdList) { writer.write(newRunId); } 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); } }