List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent
public static final boolean isMultipartContent(HttpServletRequest request)
From source file:hoot.services.controllers.ingest.BasemapResource.java
@POST @Path("/upload") @Produces(MediaType.TEXT_PLAIN)/* ww w . java2s .c o m*/ public Response processUpload(@QueryParam("INPUT_NAME") final String inputName, @QueryParam("PROJECTION") final String projection, @Context HttpServletRequest request) { String groupId = UUID.randomUUID().toString(); JSONArray jobsArr = new JSONArray(); try { File uploadDir = new File(homeFolder + "/upload/"); uploadDir.mkdir(); String repFolderPath = homeFolder + "/upload/" + groupId; File dir = new File(repFolderPath); dir.mkdir(); if (!ServletFileUpload.isMultipartContent(request)) { throw new ServletException("Content type is not multipart/form-data"); } DiskFileItemFactory fileFactory = new DiskFileItemFactory(); File filesDir = new File(repFolderPath); fileFactory.setRepository(filesDir); ServletFileUpload uploader = new ServletFileUpload(fileFactory); Map<String, String> uploadedFiles = new HashMap<String, String>(); Map<String, String> uploadedFilesPaths = new HashMap<String, String>(); List<FileItem> fileItemsList = uploader.parseRequest(request); Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); while (fileItemsIterator.hasNext()) { FileItem fileItem = fileItemsIterator.next(); String fileName = fileItem.getName(); String uploadedPath = repFolderPath + "/" + fileName; File file = new File(uploadedPath); fileItem.write(file); String[] nameParts = fileName.split("\\."); if (nameParts.length > 1) { String extension = nameParts[nameParts.length - 1].toLowerCase(); String filename = nameParts[0]; if (_basemapRasterExt.get(extension) != null) { uploadedFiles.put(filename, extension); uploadedFilesPaths.put(filename, fileName); log.debug("Saving uploaded:" + filename); } } } Iterator it = uploadedFiles.entrySet().iterator(); while (it.hasNext()) { String jobId = UUID.randomUUID().toString(); Map.Entry pairs = (Map.Entry) it.next(); String fName = pairs.getKey().toString(); String ext = pairs.getValue().toString(); log.debug("Preparing Basemap Ingest for :" + fName); String inputFileName = ""; String bmName = inputName; if (bmName != null && bmName.length() > 0) { bmName = bmName; } else { bmName = fName; } inputFileName = uploadedFilesPaths.get(fName); try { JSONArray commandArgs = new JSONArray(); JSONObject arg = new JSONObject(); arg.put("INPUT", "upload/" + groupId + "/" + inputFileName); commandArgs.add(arg); arg = new JSONObject(); arg.put("INPUT_NAME", bmName); commandArgs.add(arg); arg = new JSONObject(); arg.put("RASTER_OUTPUT_DIR", _tileServerPath + "/BASEMAP"); commandArgs.add(arg); arg = new JSONObject(); if (projection != null && projection.length() > 0) { arg.put("PROJECTION", projection); } else { arg.put("PROJECTION", "auto"); } commandArgs.add(arg); arg = new JSONObject(); arg.put("JOB_PROCESSOR_DIR", _ingestStagingPath + "/BASEMAP"); commandArgs.add(arg); String argStr = createBashPostBody(commandArgs); postJobRquest(jobId, argStr); JSONObject res = new JSONObject(); res.put("jobid", jobId); res.put("name", bmName); jobsArr.add(res); } catch (Exception ex) { ResourceErrorHandler.handleError("Error processing upload: " + ex.getMessage(), Status.INTERNAL_SERVER_ERROR, log); } } } catch (Exception ex) { ResourceErrorHandler.handleError("Error processing upload: " + ex.getMessage(), Status.INTERNAL_SERVER_ERROR, log); } return Response.ok(jobsArr.toJSONString(), MediaType.APPLICATION_JSON).build(); }
From source file:com.ephesoft.gxt.admin.server.DocumentTypeLearnFileServlet.java
@SuppressWarnings("unchecked") private void attachFile(HttpServletRequest req, HttpServletResponse resp) throws IOException { BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class); if (ServletFileUpload.isMultipartContent(req)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); String exportSerailizationFolderPath = batchSchemaService.getBaseFolderLocation() + File.separator + "tempLearnFile"; File exportSerailizationFolder = new File(exportSerailizationFolderPath); if (!exportSerailizationFolder.exists()) { exportSerailizationFolder.mkdirs(); } else {//from w w w . j a v a 2 s . com FileUtils.deleteContents(exportSerailizationFolderPath, false); exportSerailizationFolder.mkdirs(); } String learnFileName = null; String pathToLearnFile = null; String learnFileExtension = null; List<FileItem> items; try { items = upload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField()) { learnFileName = item.getName(); if (learnFileName != null) { learnFileName = learnFileName.substring(learnFileName.lastIndexOf(File.separator) + 1); learnFileExtension = learnFileName.substring(learnFileName.lastIndexOf(".") + 1); } pathToLearnFile = EphesoftStringUtil.concatenate(exportSerailizationFolderPath, File.separator, learnFileName); int numberOfPages = 0; File learnedFile = new File(pathToLearnFile); batchClassIdentifier = req.getParameter(DocumentTypeConstants.BATCH_CLASS_ID_REQ_PARAMETER); documentType = req.getParameter(DocumentTypeConstants.DOCUMENT_TYPE_REQ_PARAMETER); try { item.write(learnedFile); if (learnFileExtension.equalsIgnoreCase(FileType.PDF.getExtension())) { numberOfPages = PDFUtil.getPDFPageCount(pathToLearnFile); converPDFTotiffFile(pathToLearnFile, numberOfPages); copySinglePageFilesToLearnFolder(exportSerailizationFolderPath, learnFileName); } else if (learnFileExtension.equalsIgnoreCase(FileType.TIF.getExtension()) || learnFileExtension.equalsIgnoreCase(FileType.TIFF.getExtension())) { numberOfPages = TIFFUtil.getTIFFPageCount(pathToLearnFile); if (numberOfPages != 1) { convertMultiPageTiffToSinglePageTiff(pathToLearnFile, numberOfPages); copySinglePageFilesToLearnFolder(exportSerailizationFolderPath, learnFileName); } else { copyFilesFromTempToLearnFolders(exportSerailizationFolderPath, learnFileName, FIRST_PAGE); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } catch (FileUploadException e) { log.error("Unable to read the form contents." + e, e); } } }
From source file:com.flipkart.poseidon.core.PoseidonServlet.java
protected void doRequest(HttpMethod method, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException { PoseidonRequest request = new PoseidonRequest(httpRequest); request.setAttribute(METHOD, method); if (ServletFileUpload.isMultipartContent(httpRequest)) { handleFileUpload(request, httpRequest); } else {/*from w ww. ja va 2s .c o m*/ StringBuffer requestBuffer = new StringBuffer(); String line; try { BufferedReader reader = httpRequest.getReader(); while ((line = reader.readLine()) != null) requestBuffer.append(line); } catch (Exception e) { logger.debug("301: Couldn't read body" + e.getMessage()); } request.setAttribute(BODY, requestBuffer.toString()); } PoseidonResponse response = new PoseidonResponse(); response.setContentType(application.getDefaultMediaType()); try { buildResponse(request, response, httpResponse); } catch (ProcessingException exception) { logger.warn("301: " + exception.getMessage()); redirect(response, httpResponse); } catch (BadRequestException exception) { badRequest(response, httpResponse, exception); } catch (ElementNotFoundException exception) { elementNotFound(response, httpResponse, exception); } catch (Throwable exception) { internalError(response, httpResponse, exception); } }
From source file:com.flaptor.clusterfest.deploy.DeployModule.java
@SuppressWarnings("unchecked") public String doPage(String page, HttpServletRequest request, HttpServletResponse response) { List<NodeDescriptor> nodes = new ArrayList<NodeDescriptor>(); String[] nodesParam = request.getParameterValues("node"); if (nodesParam != null) { for (String idx : nodesParam) { nodes.add(ClusterManager.getInstance().getNodes().get(Integer.parseInt(idx))); }// w ww . jav a2s . co m } request.setAttribute("nodes", nodes); if (ServletFileUpload.isMultipartContent(request)) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); String name = null; byte[] content = null; String path = null; // Parse the request try { List<FileItem> items = upload.parseRequest(request); String message = ""; for (FileItem item : items) { String fieldName = item.getFieldName(); if (fieldName.equals("node")) { NodeDescriptor node = ClusterManager.getInstance().getNodes() .get(Integer.parseInt(item.getString())); if (!node.isReachable()) message += node + " is unreachable<br/>"; if (getModuleNode(node) != null) nodes.add(node); else message += node + " is not registered as deployable<br/>"; } if (fieldName.equals("path")) path = item.getString(); if (fieldName.equals("file")) { name = item.getName(); content = IOUtil.readAllBinary(item.getInputStream()); } } List<Pair<NodeDescriptor, Throwable>> errors = deployFiles(nodes, path, name, content); if (errors != null && errors.size() > 0) { request.setAttribute("deployCorrect", false); request.setAttribute("deployErrors", errors); } else request.setAttribute("deployCorrect", true); request.setAttribute("message", message); } catch (Exception e) { throw new RuntimeException(e); } } return "deploy.vm"; }
From source file:mx.org.cedn.avisosconagua.engine.processors.Pronostico.java
@Override public void processForm(HttpServletRequest request, String[] parts, String currentId) throws ServletException, IOException { HashMap<String, String> parametros = new HashMap<>(); boolean fileflag = false; AvisosException aex = null;//from w w w. j a va2s . c o m if (ServletFileUpload.isMultipartContent(request)) { try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(MAX_SIZE); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(MAX_SIZE); List<FileItem> items = upload.parseRequest(request); String filename = null; for (FileItem item : items) { if (!item.isFormField() && item.getSize() > 0) { filename = processUploadedFile(item, currentId); parametros.put(item.getFieldName(), filename); } else { //System.out.println("item:" + item.getFieldName() + "=" + item.getString()); parametros.put(item.getFieldName(), new String(item.getString().getBytes("ISO8859-1"), "UTF-8")); } } } catch (FileUploadException fue) { fue.printStackTrace(); fileflag = true; aex = new AvisosException("El archivo sobrepasa el tamao de " + MAX_SIZE + " bytes", fue); } } else { for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) { try { parametros.put(entry.getKey(), new String(request.getParameter(entry.getKey()).getBytes("ISO8859-1"), "UTF-8")); } catch (UnsupportedEncodingException ue) { //No debe llegar a este punto assert false; } } } BasicDBObject anterior = (BasicDBObject) MongoInterface.getInstance().getAdvice(currentId).get(parts[3]); procesaImagen(parametros, anterior); MongoInterface.getInstance().savePlainData(currentId, parts[3], parametros); if (fileflag) { throw aex; } }
From source file:net.morphbank.mbsvc3.webservices.RestfulService.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); MorphbankConfig.SYSTEM_LOGGER.info("starting post"); response.setContentType("text/xml"); System.err.println("<!-- persistence: " + MorphbankConfig.getPersistenceUnit() + " -->"); MorphbankConfig.SYSTEM_LOGGER.info("<!-- filepath: " + filepath + " -->"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // response.setContentType("text/html"); try {/*ww w.j a va 2 s . c om*/ // Process the uploaded items List<?> /* FileItem */ items = upload.parseRequest(request); Iterator<?> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { MorphbankConfig.SYSTEM_LOGGER.info("Form field " + item.getFieldName()); // processFormField(item); } else { // processUploadedFile(item); String paramName = item.getFieldName(); String fileName = item.getName(); InputStream stream = item.getInputStream(); // Reader reader = new InputStreamReader(stream); if ("uploadFileXml".equals(paramName)) { MorphbankConfig.SYSTEM_LOGGER.info("Processing file " + fileName); processRequest(stream, out, fileName); MorphbankConfig.SYSTEM_LOGGER.info("Processing complete"); } else { // Process the input stream MorphbankConfig.SYSTEM_LOGGER .info("Upload field name " + item.getFieldName() + " ignored!"); } } } } catch (FileUploadException e) { e.printStackTrace(); } }
From source file:com.github.tomakehurst.wiremock.servlet.HttpServletRequestAdapter.java
@Override public boolean isMultipartRequest() { return ServletFileUpload.isMultipartContent(request); }
From source file:com.arcadian.loginservlet.StudentAssignmentServlet.java
/** * Handles the HTTP//from ww w . ja va 2s . c o m * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!ServletFileUpload.isMultipartContent(request)) { throw new ServletException("Content type is not multipart/form-data"); } response.setContentType("text/html"); PrintWriter out = response.getWriter(); try { List<FileItem> fileItemsList = uploader.parseRequest(request); Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); String assignmentid = ""; String filename = ""; while (fileItemsIterator.hasNext()) { FileItem fileItem = fileItemsIterator.next(); System.out.println(fileItem); if (fileItem.isFormField()) { String name = fileItem.getFieldName(); String value = fileItem.getString(); if (name.equalsIgnoreCase("assignmentid")) { assignmentid = value; } System.out.println("Assignment id==" + assignmentid); } if (fileItem.getName() != null) { File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileItem.getName()); System.out.println("Absolute Path at server=" + file.getAbsolutePath()); fileItem.write(file); filename = fileItem.getName(); } } assignmentFoldetService = new AssignmentFolderService(); assignmentFoldetService.updateAssignmentFolder(username, assignmentid, filename); } catch (FileUploadException e) { System.out.println("Exception in file upload" + e); } catch (Exception ex) { Logger.getLogger(CourseContentServlet.class.getName()).log(Level.SEVERE, null, ex); } processRequest(request, response); }
From source file:net.morphbank.mbsvc3.webservices.Uploader.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); MorphbankConfig.SYSTEM_LOGGER.info("starting post"); MorphbankConfig.ensureWorkingConnection(); this.resetVariables(); MorphbankConfig.SYSTEM_LOGGER.info("<!-- persistence: " + MorphbankConfig.getPersistenceUnit() + " -->"); MorphbankConfig.SYSTEM_LOGGER.info("<!-- filepath: " + folderPath + " -->"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); response.setContentType("text/html"); try {/*from w ww. j a va 2 s.c o m*/ // String folderPath = ""; // Process the uploaded items List<?> /* FileItem */ items = upload.parseRequest(request); Iterator<?> iter = items.iterator(); boolean testPassed = false; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { processFormField(item); } else { if (testPassed = checkFilesBeforeUpload(item)) { String fileName = item.getName(); // folderPath = saveTempFile(item); saveTempFile(item); InputStream stream = item.getInputStream(); MorphbankConfig.SYSTEM_LOGGER.info("Processing file " + fileName); processRequest(stream, out, fileName, folderPath); MorphbankConfig.SYSTEM_LOGGER.info("Processing complete"); } } } this.htmlPresentation(request, response, folderPath, testPassed); out.close(); } catch (FileUploadException e) { e.printStackTrace(); out.close(); } }
From source file:com.arcadian.loginservlet.LecturesServlet.java
/** * Handles the HTTP/*ww w . j av a 2s. com*/ * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!ServletFileUpload.isMultipartContent(request)) { throw new ServletException("Content type is not multipart/form-data"); } response.setContentType("text/html"); PrintWriter out = response.getWriter(); try { List<FileItem> fileItemsList = uploader.parseRequest(request); Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); String lectureid = ""; String lecturename = ""; String subjectid = ""; String classname = ""; while (fileItemsIterator.hasNext()) { FileItem fileItem = fileItemsIterator.next(); if (fileItem.isFormField()) { String name = fileItem.getFieldName(); System.out.println(name); String value = fileItem.getString(); System.out.println(value); if (name.equalsIgnoreCase("lectureid")) { lectureid = value; } if (name.equalsIgnoreCase("lecturename")) { lecturename = value; } if (name.equalsIgnoreCase("subjectid")) { subjectid = value; } if (name.equalsIgnoreCase("semname")) { classname = value; } } if (fileItem.getName() != null) { File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileItem.getName()); System.out.println("Absolute Path at server=" + file.getAbsolutePath()); fileItem.write(file); lecturesService = new LecturesService(); lecturesService.updateLectures(lectureid, lecturename, classname, subjectid, username, fileItem.getName()); } } } catch (FileUploadException e) { System.out.println("Exception in file upload" + e); } catch (Exception ex) { Logger.getLogger(CourseContentServlet.class.getName()).log(Level.SEVERE, null, ex); } processRequest(request, response); }