List of usage examples for org.apache.commons.fileupload FileItem getName
String getName();
From source file:com.github.ikidou.handler.FormHandler.java
private List<FileEntity> getFileEntities(Map<String, Object> result, List<FileItem> fileItems) throws Exception { List<FileEntity> fileEntities = new ArrayList<>(); for (FileItem fileItem : fileItems) { if (fileItem.isFormField()) { fileItem.getFieldName();//from w ww .j av a 2s .c om result.put(fileItem.getFieldName(), fileItem.getString()); if (!fileItem.isInMemory()) { fileItem.delete(); } } else { FileEntity fileEntity = new FileEntity(); fileEntity.name = fileItem.getName(); fileEntity.contentType = fileItem.getContentType(); fileEntity.size = fileItem.getSize(); fileEntity.readableSize = FileSizeUtil.toReadable(fileItem.getSize()); fileEntity.savePath = "Data/" + fileEntity.name; File file = new File(fileEntity.savePath); fileItem.write(file); fileEntities.add(fileEntity); } } return fileEntities; }
From source file:MainServer.UploadServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); DiskFileItemFactory factory = new DiskFileItemFactory(); String upload = this.getServletContext().getRealPath("/upload/"); String temp = System.getProperty("java.io.tmpdir"); factory.setSizeThreshold(1024 * 1024 * 5); factory.setRepository(new File(temp)); ServletFileUpload servleFileUplaod = new ServletFileUpload(factory); try {/*from www. ja va 2s. c o m*/ List<FileItem> list = servleFileUplaod.parseRequest(request); for (FileItem item : list) { String name = item.getFieldName(); InputStream is = item.getInputStream(); if (name.contains("content")) { System.out.println(inputStream2String(is)); } else { if (name.contains("file")) { try { inputStream2File(is, upload + "\\" + item.getName()); } catch (Exception e) { } } } } out.write("success"); } catch (FileUploadException | IOException e) { out.write("failure"); } out.flush(); out.close(); }
From source file:com.baobao121.baby.common.SimpleUploaderServlet.java
/** * Manage the Upload requests.<br> * // ww w . j a va2 s. co m * The servlet accepts commands sent in the following format:<br> * simpleUploader?Type=ResourceType<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 DOPOST ---"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String currentPath = ""; String currentDirPath = ""; String typeStr = request.getParameter("Type"); UserCommonInfo info = null; info = (UserCommonInfo) request.getSession().getAttribute(SystemConstant.USER_COMMON_INFO); if (info == null) { info = (UserCommonInfo) request.getSession().getAttribute(SystemConstant.ADMIN_INFO); } currentPath = baseDir + "images/"; currentDirPath = getServletContext().getRealPath(currentPath); if (!(new File(currentDirPath).isDirectory())) { new File(currentDirPath).mkdir(); } if (info.getObjectTableName() == null || info.getObjectTableName().equals("")) { currentPath += "admin/"; } else { if (info.getObjectTableName().equals(SystemConstant.BABY_INFO_TABLE_NAME)) { currentPath += "babyInfo/"; } if (info.getObjectTableName().equals(SystemConstant.KG_TEACHER_INFO_TABLE_NAME)) { currentPath += "teacherInfo/"; } } currentDirPath = getServletContext().getRealPath(currentPath); if (!(new File(currentDirPath).isDirectory())) { new File(currentDirPath).mkdir(); } currentPath += info.getId(); currentDirPath = getServletContext().getRealPath(currentPath); if (!(new File(currentDirPath).isDirectory())) { new File(currentDirPath).mkdir(); } if (debug) System.out.println(currentDirPath); String retVal = "0"; String newName = ""; String fileUrl = ""; String errorMessage = ""; if (enabled) { DiskFileUpload upload = new DiskFileUpload(); try { upload.setHeaderEncoding("utf-8"); 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(); InputStream is = uplFile.getInputStream(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; Calendar calendar = Calendar.getInstance(); String nameWithoutExt = String.valueOf(calendar.getTimeInMillis()); ; String ext = getExtension(fileName); fileName = nameWithoutExt + "." + ext; fileUrl = currentPath + "/" + fileName; if (extIsAllowed(typeStr, ext)) { FileOutputStream desc = new FileOutputStream(currentDirPath + "/" + fileName); changeDimension(is, desc, 450, 1000); if (info.getObjectTableName() != null && !info.getObjectTableName().equals("")) { Photo photo = new Photo(); photo.setPhotoName(fileName); PhotoAlbum album = babyAlbumDao.getMAlbumByUser(info.getId(), info.getObjectTableName()); if (album.getId() != null) { Long albumId = album.getId(); photo.setPhotoAlbumId(albumId); photo.setPhotoLink(fileUrl); photo.setDescription(""); photo.setReadCount(0L); photo.setCommentCount(0L); photo.setReadPopedom("1"); photo.setCreateTime(DateUtil.getCurrentDateTimestamp()); photo.setModifyTime(DateUtil.getCurrentDateTimestamp()); babyPhotoDao.save(photo); babyAlbumDao.updateAlbumCount(albumId); } } } else { retVal = "202"; errorMessage = ""; if (debug) System.out.println("?: " + ext); } } catch (Exception ex) { if (debug) ex.printStackTrace(); retVal = "203"; } } else { retVal = "1"; errorMessage = "??"; } out.println("<script type=\"text/javascript\">"); out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + request.getContextPath() + fileUrl + "','" + newName + "','" + errorMessage + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:com.intranet.intr.contabilidad.SupControllerGastos.java
@RequestMapping(value = "updateGastoRF.htm", method = RequestMethod.POST) public String EupdateGastoRF_post(@ModelAttribute("ga") gastosR ga, BindingResult result, HttpServletRequest request) {/*from w w w . j av a2 s . c o m*/ String mensaje = ""; String ruta = "redirect:Gastos.htm"; //MultipartFile multipart = c.getArchivo(); System.out.println("olaEnviarMAILS"); String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosfacturas"; //File file=new File(ubicacionArchivo,multipart.getOriginalFilename()); //String ubicacionArchivo="C:\\"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> partes = upload.parseRequest(request); for (FileItem item : partes) { if (gr.getIdgasto() != 0) { if (gastosRService.existe(item.getName()) == false) { System.out.println("updateeeNOMBRE FOTO: " + item.getName()); File file = new File(ubicacionArchivo, item.getName()); item.write(file); gr.setNombreimg(item.getName()); gastosRService.updateGasto(gr); } } else ruta = "redirect:Gastos.htm"; } System.out.println("Archi subido correctamente"); } catch (Exception ex) { System.out.println("Error al subir archivo" + ex.getMessage()); } return ruta; }
From source file:manager.doCreateToy.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from www . j av a2 s . com * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String categoryList = ""; String fileName = null; if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { String name = new File(item.getName()).getName(); imageFile = new File(item.getName()); fileName = name; } else { if (item.getFieldName().equals("toyID")) { toyID = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("toyName")) { toyName = item.getString(); } if (item.getFieldName().equals("description")) { description = item.getString(); } if (item.getFieldName().equals("category")) { categoryList += item.getString(); } if (item.getFieldName().equals("secondHand")) { secondHand = item.getString(); } if (item.getFieldName().equals("cashpoint")) { cashpoint = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("qty")) { qty = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("discount")) { discount = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("uploadString")) { base64String = item.getString(); } //if(item.getFieldName().equals("desc")) // desc= item.getString(); } } category = categoryList.split(";"); //File uploaded successfully //request.setAttribute("message", "File Uploaded Successfully" + desc); } catch (Exception ex) { request.setAttribute("message", "File Upload Failed due to " + ex); } } File file = imageFile; if (!(fileName == null)) { try { /* * Reading a Image file from file system */ FileInputStream imageInFile = new FileInputStream(file); byte imageData[] = new byte[(int) file.length()]; imageInFile.read(imageData); /* * Converting Image byte array into Base64 String */ String imageDataString = encodeImage(imageData); request.setAttribute("test", imageDataString); /* * Converting a Base64 String into Image byte array */ //byte[] imageByteArray = decodeImage(imageDataString); /* * Write a image byte array into file system */ //FileOutputStream imageOutFile = new FileOutputStream("C:\\Users\\Mesong\\Pictures\\Screenshots\\30.png"); //imageOutFile.write(imageByteArray); //request.setAttribute("photo", imageDataString); // toyDB toydb = new toyDB(); //Toy t = toydb.listToyByID(1); // toydb.updateToy(t.getToyID(), imageDataString, t.getCashpoint(), t.getQTY(), t.getDiscount()); imageInFile.close(); //request.getRequestDispatcher("managerPage/result.jsp").forward(request, response); //imageOutFile.close(); imgString = imageDataString; System.out.println("Image Successfully Manipulated!"); } catch (FileNotFoundException e) { out.println("Image not found" + e.getMessage()); } catch (IOException ioe) { System.out.println("Exception while reading the Image " + ioe); } } try { toyDB toydb = new toyDB(); // out.println("s"); // int toyID = Integer.parseInt(request.getParameter("toyID")); // String toyName = request.getParameter("toyName"); // String description = request.getParameter("description"); // // String toyIcon = request.getParameter("toyIcon"); // // String[] category = request.getParameterValues("category"); // String secondHand = request.getParameter("secondHand"); // if(toyIcon==null) toyIcon = ""; // int cashpoint = Integer.parseInt(request.getParameter("cashpoint")); // int qty = Integer.parseInt(request.getParameter("qty")); // int discount = Integer.parseInt(request.getParameter("discount")); //toydb.updateToy(toyID, toyName,description, toyIcon, cashpoint, qty, discount); if (!base64String.equals("")) imgString = base64String; toydb.createToy(toyName, description, imgString, cashpoint, qty, discount); //for(String c : category) // out.println(c); out.println(toyID); out.println(description); out.println(toyIcon); out.println(cashpoint); out.println(qty); out.println(discount); toyCategoryDB toyCatdb = new toyCategoryDB(); // toyCatdb.deleteToyType(toyID); for (String c : category) { toyCatdb.createToyCategory(Integer.parseInt(c), toyID); } if (!secondHand.equals("")) { secondHandDB seconddb = new secondHandDB(); SecondHand sh = seconddb.searchSecondHand(Integer.parseInt(secondHand)); int secondHandCashpoint = sh.getCashpoint(); toydb.updateToySecondHand(toyID, Integer.parseInt(secondHand)); toydb.updateToy(toyID, imgString, secondHandCashpoint, qty, discount); } else { toydb.updateToySecondHand(toyID, -1); } //out.println(imgString); response.sendRedirect("doSearchToy"); } catch (Exception e) { out.println(e.toString()); } finally { out.close(); } }
From source file:com.wabacus.system.fileupload.FileInputBoxUpload.java
public String doFileUpload(List lstFieldItems, PrintWriter out) { String pageid = mFormFieldValues.get("PAGEID"); String reportid = mFormFieldValues.get("REPORTID"); String inputboxid = mFormFieldValues.get("INPUTBOXID"); pageid = pageid == null ? "" : pageid.trim(); inputboxid = inputboxid == null ? "" : inputboxid.trim(); PageBean pbean = Config.getInstance().getPageBean(pageid); if (pbean == null) { throw new WabacusRuntimeException("?ID" + pageid + "?"); }// w ww . j av a2s. c o m ReportBean rbean = pbean.getReportChild(reportid, true); if (rbean == null) { throw new WabacusRuntimeException( "ID" + pageid + "??ID" + reportid + ""); } mFormFieldValues.put(AbsFileUploadInterceptor.REPORTID_KEY, reportid); String boxid = inputboxid; int idx = boxid.lastIndexOf("__"); if (idx > 0) { boxid = boxid.substring(0, idx); } FileBox fileboxObj = rbean.getUploadFileBox(boxid); if (fileboxObj == null) { throw new WabacusRuntimeException( "" + rbean.getPath() + "??ID" + boxid + ""); } this.interceptorObj = fileboxObj.getInterceptor(); out.println(fileboxObj.createSelectOkFunction(inputboxid, false)); String configAllowTypes = fileboxObj.getAllowTypes(); if (configAllowTypes == null) configAllowTypes = ""; List<String> lstConfigAllowTypes = getFileSuffixList(configAllowTypes); String configDisallowTypes = fileboxObj.getDisallowtypes(); if (configDisallowTypes == null) configDisallowTypes = ""; List<String> lstConfigDisallowTypes = getFileSuffixList(configDisallowTypes); String savepath = WabacusAssistant.getInstance().parseAndGetRealValue(request, fileboxObj.getSavePath(), ""); String newfilename = WabacusAssistant.getInstance().parseAndGetRealValue(request, fileboxObj.getNewfilename(), ""); String rooturl = WabacusAssistant.getInstance().parseAndGetRealValue(request, fileboxObj.getRooturl(), ""); String seperator = fileboxObj.getSeperator(); if (Tools.isEmpty(seperator)) seperator = ";"; String allSaveValues = "", saveValueTmp; boolean existUploadFile = false; List<String> lstDestFileNames = new ArrayList<String>(); FileItem item; for (Object itemObj : lstFieldItems) { item = (FileItem) itemObj; if (item.isFormField()) continue; String orginalFilename = item.getName(); if ((orginalFilename == null || orginalFilename.equals(""))) continue; orginalFilename = getFileNameFromAbsolutePath(orginalFilename); if (orginalFilename.equals("")) return "??";//?? mFormFieldValues.put(AbsFileUploadInterceptor.ALLOWTYPES_KEY, configAllowTypes); mFormFieldValues.put(AbsFileUploadInterceptor.DISALLOWTYPES_KEY, configDisallowTypes); mFormFieldValues.put(AbsFileUploadInterceptor.MAXSIZE_KEY, String.valueOf(fileboxObj.getMaxsize())); mFormFieldValues.put(AbsFileUploadInterceptor.FILENAME_KEY, getSaveFileName(orginalFilename, newfilename)); mFormFieldValues.put(AbsFileUploadInterceptor.SAVEPATH_KEY, savepath); mFormFieldValues.put(AbsFileUploadInterceptor.ROOTURL_KEY, rooturl); boolean shouldUpload = interceptorObj != null ? interceptorObj.beforeFileUpload(request, item, mFormFieldValues, out) : true; if (shouldUpload) { getRealUploadFileName(lstDestFileNames, orginalFilename); String errorMessage = doUploadFileAction(item, mFormFieldValues, orginalFilename, configAllowTypes, lstConfigAllowTypes, configDisallowTypes, lstConfigDisallowTypes); if (errorMessage != null && !errorMessage.trim().equals("")) return errorMessage; } existUploadFile = true; saveValueTmp = getSaveValue(); if (!Tools.isEmpty(saveValueTmp)) allSaveValues += saveValueTmp + seperator; } if (!existUploadFile) return "?!"; if (allSaveValues.endsWith(seperator)) allSaveValues = allSaveValues.substring(0, allSaveValues.length() - seperator.length()); out.print("<script language='javascript'>"); out.print("selectOK('" + allSaveValues + "',null,null,false);"); out.print("</script>"); return null; }
From source file:com.ephesoft.gxt.admin.server.ImportBatchClassUploadServlet.java
private void attachFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService, BatchClassService bcService, ImportBatchService imService) throws IOException { PrintWriter printWriter = resp.getWriter(); File tempZipFile = null;//from www . ja v a 2s. c o m InputStream instream = null; OutputStream out = null; String zipWorkFlowName = "", tempOutputUnZipDir = "", zipWorkflowDesc = "", zipWorkflowPriority = ""; BatchClass importBatchClass = null; if (ServletFileUpload.isMultipartContent(req)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation(); File exportSerailizationFolder = new File(exportSerailizationFolderPath); if (!exportSerailizationFolder.exists()) { exportSerailizationFolder.mkdir(); } String zipFileName = ""; String zipPathname = ""; List<FileItem> items; try { items = upload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField()) {//&& "importFile".equals(item.getFieldName())) { zipFileName = item.getName(); if (zipFileName != null) { zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1); } zipPathname = exportSerailizationFolderPath + File.separator + zipFileName; // get only the file name not whole path if (zipFileName != null) { zipFileName = FilenameUtils.getName(zipFileName); } try { instream = item.getInputStream(); tempZipFile = new File(zipPathname); if (tempZipFile.exists()) { tempZipFile.delete(); } out = new FileOutputStream(tempZipFile); byte buf[] = new byte[1024]; int len; while ((len = instream.read(buf)) > 0) { out.write(buf, 0, len); } } catch (FileNotFoundException e) { log.error("Unable to create the export folder." + e, e); printWriter.write("Unable to create the export folder.Please try again."); } catch (IOException e) { log.error("Unable to read the file." + e, e); printWriter.write("Unable to read the file.Please try again."); } finally { if (out != null) { try { out.close(); } catch (IOException ioe) { log.info("Could not close stream for file." + tempZipFile); } } if (instream != null) { try { instream.close(); } catch (IOException ioe) { log.info("Could not close stream for file." + zipFileName); } } } } } } catch (FileUploadException e) { log.error("Unable to read the form contents." + e, e); printWriter.write("Unable to read the form contents.Please try again."); } tempOutputUnZipDir = exportSerailizationFolderPath + File.separator + zipFileName.substring(0, zipFileName.lastIndexOf('.')) + System.nanoTime(); try { FileUtils.unzip(tempZipFile, tempOutputUnZipDir); } catch (Exception e) { log.error("Unable to unzip the file." + e, e); printWriter.write("Unable to unzip the file.Please try again."); tempZipFile.delete(); } String serializableFilePath = FileUtils.getFileNameOfTypeFromFolder(tempOutputUnZipDir, SERIALIZATION_EXT); InputStream serializableFileStream = null; try { serializableFileStream = new FileInputStream(serializableFilePath); importBatchClass = (BatchClass) SerializationUtils.deserialize(serializableFileStream); zipWorkFlowName = importBatchClass.getName(); zipWorkflowDesc = importBatchClass.getDescription(); zipWorkflowPriority = "" + importBatchClass.getPriority(); } catch (Exception e) { tempZipFile.delete(); log.error("Error while importing" + e, e); printWriter.write("Error while importing.Please try again."); } finally { if (serializableFileStream != null) { try { serializableFileStream.close(); } catch (IOException ioe) { log.info("Could not close stream for file." + serializableFilePath); } } } } else { log.error("Request contents type is not supported."); printWriter.write("Request contents type is not supported."); } if (tempZipFile != null) { tempZipFile.delete(); } List<String> uncList = bcService.getAssociatedUNCList(zipWorkFlowName); DeploymentService deploymentService = this.getSingleBeanOfType(DeploymentService.class); boolean isWorkflowDeployed = deploymentService.isDeployed(zipWorkFlowName); if (null != importBatchClass) { boolean isWorkflowEqual = imService.isImportWorkflowEqualDeployedWorkflow(importBatchClass, importBatchClass.getName()); printWriter.write(AdminSharedConstants.WORK_FLOW_NAME + zipWorkFlowName); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORK_FLOW_DESC + zipWorkflowDesc); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORK_FLOW_PRIORITY + zipWorkflowPriority); printWriter.append("|"); printWriter.append(AdminSharedConstants.FILE_PATH).append(tempOutputUnZipDir); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORKFLOW_DEPLOYED + isWorkflowDeployed); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORKFLOW_EQUAL + isWorkflowEqual); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORKFLOW_EXIST_IN_BATCH_CLASS + ((uncList == null || uncList.size() == 0) ? false : true)); printWriter.append("|"); } printWriter.flush(); }
From source file:net.fckeditor.connector.MyDispatcher.java
/** * Called by the connector servlet to handle a {@code POST} request. In * particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and * {@link Command#QUICK_UPLOAD QuickUpload} commands. * //w w w .j av a2s .co m * @param request * the current request instance * @return the upload response instance associated with this request */ UploadResponse doPost(final HttpServletRequest request) { logger.debug("Entering Dispatcher#doPost"); Context context = ThreadLocalData.getContext(); context.logBaseParameters(); UploadResponse uploadResponse = null; // check permissions for user actions if (!RequestCycleHandler.isFileUploadEnabled(request)) uploadResponse = UploadResponse.getFileUploadDisabledError(); // check parameters else if (!Command.isValidForPost(context.getCommandStr())) uploadResponse = UploadResponse.getInvalidCommandError(); else if (!ResourceType.isValidType(context.getTypeStr())) uploadResponse = UploadResponse.getInvalidResourceTypeError(); else if (!UtilsFile.isValidPath(context.getCurrentFolderStr())) uploadResponse = UploadResponse.getInvalidCurrentFolderError(); else { // call the Connector#fileUpload ResourceType type = context.getDefaultResourceType(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); try { List<FileItem> items = upload.parseRequest(request); // We upload just one file at the same time FileItem uplFile = items.get(0); // Some browsers transfer the entire source path not just the // filename String fileName = FilenameUtils.getName(uplFile.getName()); fileName = UUID.randomUUID().toString().replace("-", "") + "." + FilenameUtils.getExtension(fileName); logger.debug("Parameter NewFile: {}", fileName); // check the extension if (type.isDeniedExtension(FilenameUtils.getExtension(fileName))) uploadResponse = UploadResponse.getInvalidFileTypeError(); // Secure image check (can't be done if QuickUpload) else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads() && !UtilsFile.isImage(uplFile.getInputStream())) { uploadResponse = UploadResponse.getInvalidFileTypeError(); } else { String sanitizedFileName = UtilsFile.sanitizeFileName(fileName); logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName); String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(), sanitizedFileName, uplFile.getInputStream()); String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request), type, context.getCurrentFolderStr(), newFileName); if (sanitizedFileName.equals(newFileName)) uploadResponse = UploadResponse.getOK(fileUrl); else { uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName); logger.debug("Parameter NewFile (renamed): {}", newFileName); } } uplFile.delete(); } catch (InvalidCurrentFolderException e) { uploadResponse = UploadResponse.getInvalidCurrentFolderError(); } catch (WriteException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (IOException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (FileUploadException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } } logger.debug("Exiting Dispatcher#doPost"); return uploadResponse; }
From source file:ai.h2o.servicebuilder.MakePythonWarServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Long startTime = System.currentTimeMillis(); File tmpDir = null;/* w w w . j a v a2 s . co m*/ try { //create temp directory tmpDir = createTempDirectory("makeWar"); logger.debug("tmpDir " + tmpDir); // create output directories File webInfDir = new File(tmpDir.getPath(), "WEB-INF"); if (!webInfDir.mkdir()) throw new Exception("Can't create output directory (WEB-INF)"); File outDir = new File(webInfDir.getPath(), "classes"); if (!outDir.mkdir()) throw new Exception("Can't create output directory (WEB-INF/classes)"); File libDir = new File(webInfDir.getPath(), "lib"); if (!libDir.mkdir()) throw new Exception("Can't create output directory (WEB-INF/lib)"); // get input files List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); String pojofile = null; String jarfile = null; String mojofile = null; String pythonfile = null; String predictorClassName = null; String pythonenvfile = null; ArrayList<String> pojos = new ArrayList<String>(); ArrayList<String> rawfiles = new ArrayList<String>(); for (FileItem i : items) { String field = i.getFieldName(); String filename = i.getName(); if (filename != null && filename.length() > 0) { if (field.equals("pojo")) { // pojo file name, use this or a mojo file pojofile = filename; pojos.add(pojofile); predictorClassName = filename.replace(".java", ""); FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename)); logger.info("added pojo model {}", filename); } if (field.equals("jar")) { jarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename; FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename)); } if (field.equals("python")) { pythonfile = "WEB-INF" + File.separator + "python.py"; FileUtils.copyInputStreamToFile(i.getInputStream(), new File(webInfDir, "python.py")); } if (field.equals("pythonextra")) { // optional extra files for python pythonfile = "WEB-INF" + File.separator + "lib" + File.separator + filename; FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename)); } if (field.equals("mojo")) { // a raw model zip file, a mojo file (optional) mojofile = filename; rawfiles.add(mojofile); predictorClassName = filename.replace(".zip", ""); FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename)); logger.info("added mojo model {}", filename); } if (field.equals("envfile")) { // optional conda environment file pythonenvfile = filename; FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename)); logger.debug("using conda environment file {}", pythonenvfile); } } } logger.debug("jar {} pojo {} mojo {} python {} envfile {}", jarfile, pojofile, mojofile, pythonfile, pythonenvfile); if ((pojofile == null || jarfile == null) && (mojofile == null || jarfile == null)) throw new Exception("need either pojo and genmodel jar, or raw file and genmodel jar "); if (pojofile != null) { // Compile the pojo runCmd(tmpDir, Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION, "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", jarfile, "-d", outDir.getPath(), pojofile), "Compilation of pojo failed"); logger.info("compiled pojo {}", pojofile); } if (servletPath == null) throw new Exception("servletPath is null"); FileUtils.copyDirectoryToDirectory(new File(servletPath, "extra"), tmpDir); String extraPath = "extra" + File.separator; String webInfPath = extraPath + File.separator + "WEB-INF" + File.separator; String srcPath = extraPath + "src" + File.separator; copyExtraFile(servletPath, extraPath, tmpDir, "pyindex.html", "index.html"); copyExtraFile(servletPath, extraPath, tmpDir, "jquery.js", "jquery.js"); copyExtraFile(servletPath, extraPath, tmpDir, "predict.js", "predict.js"); copyExtraFile(servletPath, extraPath, tmpDir, "custom.css", "custom.css"); copyExtraFile(servletPath, webInfPath, webInfDir, "web-pythonpredict.xml", "web.xml"); FileUtils.copyDirectoryToDirectory(new File(servletPath, webInfPath + "lib"), webInfDir); FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "bootstrap"), tmpDir); FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "fonts"), tmpDir); // change the class name in the predictor template file to the predictor we have String modelCode = null; if (!pojos.isEmpty()) { FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), pojos); modelCode = "null"; } else if (!rawfiles.isEmpty()) { FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), rawfiles); modelCode = "MojoModel.load(fileName)"; } InstantiateJavaTemplateFile(tmpDir, modelCode, predictorClassName, "null", pythonenvfile == null ? "" : pythonenvfile, srcPath + "ServletUtil-TEMPLATE.java", "ServletUtil.java"); copyExtraFile(servletPath, srcPath, tmpDir, "PredictPythonServlet.java", "PredictPythonServlet.java"); copyExtraFile(servletPath, srcPath, tmpDir, "InfoServlet.java", "InfoServlet.java"); copyExtraFile(servletPath, srcPath, tmpDir, "StatsServlet.java", "StatsServlet.java"); copyExtraFile(servletPath, srcPath, tmpDir, "PingServlet.java", "PingServlet.java"); copyExtraFile(servletPath, srcPath, tmpDir, "Transform.java", "Transform.java"); copyExtraFile(servletPath, srcPath, tmpDir, "Logging.java", "Logging.java"); // compile extra runCmd(tmpDir, Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION, "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", "WEB-INF/lib/*:WEB-INF/classes:extra/WEB-INF/lib/*", "-d", outDir.getPath(), "InfoServlet.java", "StatsServlet.java", "PredictPythonServlet.java", "ServletUtil.java", "PingServlet.java", "Transform.java", "Logging.java"), "Compilation of servlet failed"); // create the war jar file Collection<File> filesc = FileUtils.listFilesAndDirs(webInfDir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); filesc.add(new File(tmpDir, "index.html")); filesc.add(new File(tmpDir, "jquery.js")); filesc.add(new File(tmpDir, "predict.js")); filesc.add(new File(tmpDir, "custom.css")); filesc.add(new File(tmpDir, "modelnames.txt")); for (String m : pojos) { filesc.add(new File(tmpDir, m)); } for (String m : rawfiles) { filesc.add(new File(tmpDir, m)); } Collection<File> dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "bootstrap"), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); filesc.addAll(dirc); dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "fonts"), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); filesc.addAll(dirc); File[] files = filesc.toArray(new File[] {}); if (files.length == 0) throw new Exception("Can't list compiler output files (out)"); byte[] resjar = createJarArchiveByteArray(files, tmpDir.getPath() + File.separator); if (resjar == null) throw new Exception("Can't create war of compiler output"); logger.info("war created from {} files, size {}", files.length, resjar.length); // send jar back ServletOutputStream sout = response.getOutputStream(); response.setContentType("application/octet-stream"); String outputFilename = predictorClassName.length() > 0 ? predictorClassName : "h2o-predictor"; response.setHeader("Content-disposition", "attachment; filename=" + outputFilename + ".war"); response.setContentLength(resjar.length); sout.write(resjar); sout.close(); response.setStatus(HttpServletResponse.SC_OK); Long elapsedMs = System.currentTimeMillis() - startTime; logger.info("Done python war creation in {}", elapsedMs); } catch (Exception e) { logger.error("doPost failed", e); // send the error message back String message = e.getMessage(); if (message == null) message = "no message"; logger.error(message); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().write(message); response.getWriter().write(Arrays.toString(e.getStackTrace())); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } finally { // if the temp directory is still there we delete it if (tmpDir != null && tmpDir.exists()) { try { FileUtils.deleteDirectory(tmpDir); } catch (IOException e) { logger.error("Can't delete tmp directory"); } } } }
From source file:com.globalsight.dispatcher.controller.TranslateXLFController.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public void uploadXLF(HttpServletRequest p_request, HttpServletResponse p_response) throws IOException, FileUploadException, JSONException { String securityCode = p_request.getParameter(JSONPN_SECURITY_CODE); Account account = accountDAO.getAccountBySecurityCode(securityCode); if (account == null) { JSONObject jsonObj = new JSONObject(); jsonObj.put(JSONPN_STATUS, STATUS_FAILED); jsonObj.put(JSONPN_ERROR_MESSAGE, "The security code is incorrect!"); logger.error("The security code is incorrect -->" + securityCode); p_response.getWriter().write(jsonObj.toString()); return;/*from www . j av a2 s . co m*/ } File fileStorage = CommonDAO.getFileStorage(); File tempDir = CommonDAO.getFolder(fileStorage, FOLDER_TEMP); String jobIDStr = "-1"; File srcFile = null; JobBO job = null; String errorMsg = null; if (ServletFileUpload.isMultipartContent(p_request)) { jobIDStr = RandomStringUtils.randomNumeric(10); List<FileItem> fileItems = new ServletFileUpload(new DiskFileItemFactory(1024 * 1024, tempDir)) .parseRequest(p_request); for (FileItem item : fileItems) { if (item.isFormField()) { } else { String fileName = item.getName(); fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1); File srcDir = CommonDAO.getFolder(fileStorage, account.getAccountName() + File.separator + jobIDStr + File.separator + XLF_SOURCE_FOLDER); srcFile = new File(srcDir, fileName); try { item.write(srcFile); logger.info("Uploaded File:" + srcFile.getAbsolutePath()); } catch (Exception e) { logger.error("Upload error with File:" + srcFile.getAbsolutePath(), e); } } } // Initial JobBO job = new JobBO(jobIDStr, account.getId(), srcFile); // Prepare data for MT String parseMsg = parseXLF(job, srcFile); if (parseMsg == null) errorMsg = checkJobData(job); else errorMsg = parseMsg; if (errorMsg == null || errorMsg.trim().length() == 0) { // Do MT doMachineTranslation(job); jobMap.put(job.getJobID(), job); } else { // Cancel Job job = null; } } JSONObject jsonObj = new JSONObject(); if (job != null) { jsonObj.put(JSONPN_JOBID, job.getJobID()); jsonObj.put(JSONPN_SOURCE_LANGUAGE, job.getSourceLanguage()); jsonObj.put(JSONPN_TARGET_LANGUAGE, job.getTargetLanguage()); jsonObj.put("sourceSegmentSize", job.getSourceSegments().length); logger.info("Created Job --> " + jsonObj.toString()); } else { jsonObj.put(JSONPN_STATUS, STATUS_FAILED); jsonObj.put(JSONPN_ERROR_MESSAGE, errorMsg); logger.error("Failed to create Job --> " + jsonObj.toString() + ", file:" + srcFile + ", account:" + account.getAccountName()); } p_response.getWriter().write(jsonObj.toString()); }