List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent
public static final boolean isMultipartContent(HttpServletRequest request)
From source file:at.gv.egiz.pdfas.web.servlets.VerifyServlet.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)//ww w . j a v a 2 s. c om */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.info("Post verify request"); String errorUrl = PdfAsParameterExtractor.getInvokeErrorURL(request); PdfAsHelper.setErrorURL(request, response, errorUrl); StatisticEvent statisticEvent = new StatisticEvent(); statisticEvent.setStartNow(); statisticEvent.setSource(Source.WEB); statisticEvent.setOperation(Operation.VERIFY); statisticEvent.setUserAgent(UserAgentFilter.getUserAgent()); try { byte[] filecontent = null; // checks if the request actually contains upload file if (!ServletFileUpload.isMultipartContent(request)) { // No Uploaded data! if (PdfAsParameterExtractor.getPdfUrl(request) != null) { doGet(request, response); return; } else { throw new PdfAsWebException("No Signature data defined!"); } } else { // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(THRESHOLD_SIZE); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } List<?> formItems = upload.parseRequest(request); logger.debug(formItems.size() + " Items in form data"); if (formItems.size() < 1) { // No Uploaded data! // Try do get // No Uploaded data! if (PdfAsParameterExtractor.getPdfUrl(request) != null) { doGet(request, response); return; } else { throw new PdfAsWebException("No Signature data defined!"); } } else { for (int i = 0; i < formItems.size(); i++) { Object obj = formItems.get(i); if (obj instanceof FileItem) { FileItem item = (FileItem) obj; if (item.getFieldName().equals(UPLOAD_PDF_DATA)) { filecontent = item.get(); try { File f = new File(item.getName()); String name = f.getName(); logger.debug("Got upload: " + item.getName()); if (name != null) { if (!(name.endsWith(".pdf") || name.endsWith(".PDF"))) { name += ".pdf"; } logger.debug("Setting Filename in session: " + name); PdfAsHelper.setPDFFileName(request, name); } } catch (Throwable e) { logger.warn("In resolving filename", e); } if (filecontent.length < 10) { filecontent = null; } else { logger.debug("Found pdf Data! Size: " + filecontent.length); } } else { request.setAttribute(item.getFieldName(), item.getString()); logger.debug("Setting " + item.getFieldName() + " = " + item.getString()); } } else { logger.debug(obj.getClass().getName() + " - " + obj.toString()); } } } } if (filecontent == null) { if (PdfAsParameterExtractor.getPdfUrl(request) != null) { filecontent = RemotePDFFetcher.fetchPdfFile(PdfAsParameterExtractor.getPdfUrl(request)); } } if (filecontent == null) { Object sourceObj = request.getAttribute("source"); if (sourceObj != null) { String source = sourceObj.toString(); if (source.equals("internal")) { request.setAttribute("FILEERR", true); request.getRequestDispatcher("index.jsp").forward(request, response); statisticEvent.setStatus(Status.ERROR); statisticEvent.setException(new Exception("No file uploaded")); statisticEvent.setEndNow(); statisticEvent.setTimestampNow(); StatisticFrontend.getInstance().storeEvent(statisticEvent); statisticEvent.setLogged(true); return; } } throw new PdfAsException("No Signature data available"); } doVerify(request, response, filecontent, statisticEvent); } catch (Throwable e) { statisticEvent.setStatus(Status.ERROR); statisticEvent.setException(e); if (e instanceof PDFASError) { statisticEvent.setErrorCode(((PDFASError) e).getCode()); } statisticEvent.setEndNow(); statisticEvent.setTimestampNow(); StatisticFrontend.getInstance().storeEvent(statisticEvent); statisticEvent.setLogged(true); logger.warn("Generic Error: ", e); PdfAsHelper.setSessionException(request, response, e.getMessage(), e); PdfAsHelper.gotoError(getServletContext(), request, response); } }
From source file:hoot.services.ingest.MultipartSerializer.java
/** * Serializes uploaded multipart data into files. It can handle file or folder type. * /* www . jav a2s . c o m*/ * @param jobId = unique id to identify uploaded files group * @param inputType = ["FILE" | "DIR"] where DIR type is treated as FGDB * @param uploadedFiles = The list of files uploaded * @param uploadedFilesPaths = The list of uploaded files paths * @param request = The request object that holds post data * @throws Exception */ public void serializeUpload(final String jobId, String inputType, Map<String, String> uploadedFiles, Map<String, String> uploadedFilesPaths, final HttpServletRequest request) throws Exception { // Uploaded data container folder path. It is unique to each job String repFolderPath = homeFolder + "/upload/" + jobId; File dir = new File(repFolderPath); FileUtils.forceMkdir(dir); if (!ServletFileUpload.isMultipartContent(request)) { ResourceErrorHandler.handleError("Content type is not multipart/form-data", Status.BAD_REQUEST, log); } DiskFileItemFactory fileFactory = new DiskFileItemFactory(); File filesDir = new File(repFolderPath); fileFactory.setRepository(filesDir); ServletFileUpload uploader = new ServletFileUpload(fileFactory); List<FileItem> fileItemsList = uploader.parseRequest(request); Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); // If user request type is DIR then treat it as FGDB folder if (inputType.equalsIgnoreCase("DIR")) { _serializeFGDB(fileItemsList, jobId, uploadedFiles, uploadedFilesPaths); } else { // Can be shapefile or zip file _serializeUploadedFiles(fileItemsList, jobId, uploadedFiles, uploadedFilesPaths, repFolderPath); } }
From source file:com.aliasi.demo.framework.DemoServlet.java
void generateOutput(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { InputStream in = null;//from w w w.ja v a 2 s . co m OutputStream out = null; try { response.setContentType(mDemo.responseType()); out = response.getOutputStream(); @SuppressWarnings("unchecked") // bad inherited API from commons Properties properties = mapToProperties((Map<String, String[]>) request.getParameterMap()); String reqContentType = request.getContentType(); if (reqContentType == null || reqContentType.startsWith("text/plain")) { properties.setProperty("inputType", "text/plain"); String reqCharset = request.getCharacterEncoding(); if (reqCharset != null) properties.setProperty("inputCharset", reqCharset); in = request.getInputStream(); } else if (reqContentType.startsWith("application/x-www-form-urlencoded")) { String codedText = request.getParameter("inputText"); byte[] bytes = codedText.getBytes("ISO-8859-1"); in = new ByteArrayInputStream(bytes); } else if (ServletFileUpload.isMultipartContent(new ServletRequestContext(request))) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload uploader = new ServletFileUpload(factory); @SuppressWarnings("unchecked") // bad commons API List<FileItem> items = (List<FileItem>) uploader.parseRequest(request); Iterator<FileItem> it = items.iterator(); while (it.hasNext()) { log("found item"); FileItem item = it.next(); if (item.isFormField()) { String key = item.getFieldName(); String val = item.getString(); properties.setProperty(key, val); } else { byte[] bytes = item.get(); in = new ByteArrayInputStream(bytes); } } } else { System.out.println("unexpected content type"); String msg = "Unexpected request content" + reqContentType; throw new ServletException(msg); } mDemo.process(in, out, properties); } catch (FileUploadException e) { throw new ServletException(e); } finally { Streams.closeQuietly(in); Streams.closeQuietly(out); } }
From source file:ba.nwt.ministarstvo.server.fileUpload.FileUploadServlet.java
@SuppressWarnings("unchecked") @Override//from w w w. ja va2 s . co m protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ServletRequestContext ctx = new ServletRequestContext(request); if (ServletFileUpload.isMultipartContent(ctx) == false) { sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The servlet can only handle multipart requests." + " This is probably a software bug.")); return; } // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> i = items.iterator(); HashMap<String, String> params = new HashMap<String, String>(); HashMap<String, File> files = new HashMap<String, File>(); while (i.hasNext() == true) { FileItem item = i.next(); if (item.isFormField() == true) { String param = item.getFieldName(); String value = item.getString(); // System.out.println(getClass().getName() + ": param=" // + param + ", value=" + value); params.put(param, value); } else { if (item.getSize() == 0) { continue; // ignore zero-length files } File tempf = File.createTempFile(request.getRemoteAddr() + "-" + item.getFieldName() + "-", ""); item.write(tempf); files.put(item.getFieldName(), tempf); // System.out.println("Creating temporary file " // + tempf.getAbsolutePath()); } } // populate, invoke the listener, delete files if needed, // send response FileUploadAction action = (FileUploadAction) actionClass.newInstance(); BeanUtils.populate(action, params); // populate the object action.setFileList(files); FormResponse resp = action.onSubmit(this, request); if (resp.isDeleteFiles()) { Iterator<Map.Entry<String, File>> j = files.entrySet().iterator(); while (j.hasNext()) { Map.Entry<String, File> entry = j.next(); File f = entry.getValue(); f.delete(); } } sendResponse(response, resp); return; } catch (Exception e) { e.printStackTrace(); sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getClass().getName() + ": " + e.getMessage())); } }
From source file:com.openkm.servlet.admin.StampServlet.java
@SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); String action = WebUtils.getString(request, "action"); Session session = null;/* w w w . j a v a 2 s.com*/ updateSessionManager(request); try { if (ServletFileUpload.isMultipartContent(request)) { session = JCRUtils.getSession(); InputStream is = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); StampImage si = new StampImage(); for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("action")) { action = item.getString("UTF-8"); } else if (item.getFieldName().equals("si_id")) { si.setId(Integer.parseInt(item.getString("UTF-8"))); } else if (item.getFieldName().equals("si_name")) { si.setName(item.getString("UTF-8")); } else if (item.getFieldName().equals("si_description")) { si.setDescription(item.getString("UTF-8")); } else if (item.getFieldName().equals("si_layer")) { si.setLayer(Integer.parseInt(item.getString("UTF-8"))); } else if (item.getFieldName().equals("si_opacity")) { si.setOpacity(Float.parseFloat(item.getString("UTF-8"))); } else if (item.getFieldName().equals("si_expr_x")) { si.setExprX(item.getString("UTF-8")); } else if (item.getFieldName().equals("si_expr_y")) { si.setExprY(item.getString("UTF-8")); } else if (item.getFieldName().equals("si_active")) { si.setActive(true); } else if (item.getFieldName().equals("si_users")) { si.getUsers().add(item.getString("UTF-8")); } } else { is = item.getInputStream(); si.setImageMime(Config.mimeTypes.getContentType(item.getName())); si.setImageContent(SecureStore.b64Encode(IOUtils.toByteArray(is))); is.close(); } } if (action.equals("imageCreate")) { int id = StampImageDAO.create(si); // Activity log UserActivity.log(session.getUserID(), "ADMIN_STAMP_IMAGE_CREATE", Integer.toString(id), si.toString()); imageList(session, request, response); } else if (action.equals("imageEdit")) { StampImageDAO.update(si); // Activity log UserActivity.log(session.getUserID(), "ADMIN_STAMP_IMAGE_EDIT", Integer.toString(si.getId()), si.toString()); imageList(session, request, response); } else if (action.equals("imageDelete")) { StampImageDAO.delete(si.getId()); // Activity log UserActivity.log(session.getUserID(), "ADMIN_STAMP_IMAGE_DELETE", Integer.toString(si.getId()), null); imageList(session, request, response); } } } catch (LoginException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (RepositoryException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (FileUploadException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } finally { JCRUtils.logout(session); } }
From source file:com.globalsight.everest.webapp.pagehandler.administration.localepairs.LocalePairImportHandler.java
/** * Upload the properties file to FilterConfigurations/import folder * // w w w . j a v a 2 s .c o m * @param request */ private File uploadFile(HttpServletRequest request) { File f = null; try { String tmpDir = AmbFileStoragePathUtils.getFileStorageDirPath() + File.separator + "GlobalSight" + File.separator + "LocalePairs" + File.separator + "import"; boolean isMultiPart = ServletFileUpload.isMultipartContent(request); if (isMultiPart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024000); ServletFileUpload upload = new ServletFileUpload(factory); List<?> items = upload.parseRequest(request); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (!item.isFormField()) { String filePath = item.getName(); if (filePath.contains(":")) { filePath = filePath.substring(filePath.indexOf(":") + 1); } String originalFilePath = filePath.replace("\\", File.separator).replace("/", File.separator); String fileName = tmpDir + File.separator + originalFilePath; f = new File(fileName); f.getParentFile().mkdirs(); item.write(f); } } } return f; } catch (Exception e) { logger.error("File upload failed.", e); return null; } }
From source file:com.exilant.exility.core.HtmlRequestHandler.java
/** * Extract data from request object (form, data and session) * // w w w . ja va2s .com * @param req * @param formIsSubmitted * @param hasSerializedDc * @param outData * @return all input fields into a service data * @throws ExilityException */ @SuppressWarnings("resource") public ServiceData createInData(HttpServletRequest req, boolean formIsSubmitted, boolean hasSerializedDc, ServiceData outData) throws ExilityException { ServiceData inData = new ServiceData(); if (formIsSubmitted == false) { /** * most common call from client that uses serverAgent to send an * ajax request with serialized dc as data */ this.extractSerializedData(req, hasSerializedDc, inData); } else { /** * form is submitted. this is NOT from serverAgent.js. This call * would be from other .jsp files */ if (hasSerializedDc == false) { /** * client has submitted a form with form fields in that. * Traditional form submit **/ this.extractParametersAndFiles(req, inData); } else { /** * Logic got evolved over a period of time. several calling jsps * actually inspect the stream for file, and in the process they * would have extracted form fields into session. So, we extract * form fields, as well as dip into session */ HttpSession session = req.getSession(); if (ServletFileUpload.isMultipartContent(req) == false) { /** * Bit convoluted. the .jsp has already extracted files and * form fields into session. field. */ String txt = session.getAttribute("dc").toString(); this.extractSerializedDc(txt, inData); this.extractFilesToDc(req, inData); } else { /** * jsp has not touched input stream, and it wants us to do * everything. */ try { ServletFileUpload fileUploader = new ServletFileUpload(); fileUploader.setHeaderEncoding("UTF-8"); FileItemIterator iterator = fileUploader.getItemIterator(req); while (iterator.hasNext()) { FileItemStream stream = iterator.next(); String fieldName = stream.getFieldName(); InputStream inStream = null; inStream = stream.openStream(); try { if (stream.isFormField()) { String fieldValue = Streams.asString(inStream); /** * dc is a special name that contains * serialized DC */ if (fieldName.equals("dc")) { this.extractSerializedDc(fieldValue, inData); } else { inData.addValue(fieldName, fieldValue); } } else { /** * it is a file. we assume that the files * are small, and hence we carry the content * in memory with a specific naming * convention */ String fileContents = IOUtils.toString(inStream); inData.addValue(fieldName + HtmlRequestHandler.PATH_SUFFIX, fileContents); } } catch (Exception e) { Spit.out("error whiel extracting data from request stream " + e.getMessage()); } IOUtils.closeQuietly(inStream); } } catch (Exception e) { // nothing to do here } /** * read session variables */ @SuppressWarnings("rawtypes") Enumeration e = session.getAttributeNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); if (name.equals("dc")) { this.extractSerializedDc(req.getSession().getAttribute(name).toString(), inData); } String value = req.getSession().getAttribute(name).toString(); inData.addValue(name, value); System.out.println("name is: " + name + " value is: " + value); } } } } this.getStandardFields(req, inData); return inData; }
From source file:com.nominanuda.web.http.ServletHelper.java
@SuppressWarnings("unchecked") private HttpEntity buildEntity(HttpServletRequest servletRequest, final InputStream is, long contentLength, String ct, String cenc) throws IOException { if (ServletFileUpload.isMultipartContent(servletRequest)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items; try {// ww w. j av a2 s.co m items = upload.parseRequest(new HttpServletRequestWrapper(servletRequest) { public ServletInputStream getInputStream() throws IOException { return new ServletInputStream() { public int read() throws IOException { return is.read(); } public int read(byte[] arg0) throws IOException { return is.read(arg0); } public int read(byte[] b, int off, int len) throws IOException { return is.read(b, off, len); } //@Override @SuppressWarnings("unused") public boolean isFinished() { Check.illegalstate.fail(NOT_IMPLEMENTED); return false; } //@Override @SuppressWarnings("unused") public boolean isReady() { Check.illegalstate.fail(NOT_IMPLEMENTED); return false; } //@Override @SuppressWarnings("unused") public void setReadListener(ReadListener arg0) { Check.illegalstate.fail(NOT_IMPLEMENTED); } }; } }); } catch (FileUploadException e) { throw new IOException(e); } MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (FileItem i : items) { multipartEntity.addPart(i.getFieldName(), new InputStreamBody(i.getInputStream(), i.getName())); } return multipartEntity; } else { InputStreamEntity entity = new InputStreamEntity(is, contentLength); entity.setContentType(ct); if (cenc != null) { entity.setContentEncoding(cenc); } return entity; } }
From source file:com.app.framework.web.MultipartFilter.java
/** * Parse the given HttpServletRequest. If the request is a multipart * request, then all multipart request items will be processed, else the * request will be returned unchanged. During the processing of all * multipart request items, the name and value of each regular form field * will be added to the parameterMap of the HttpServletRequest. The name and * File object of each form file field will be added as attribute of the * given HttpServletRequest. If a FileUploadException has occurred when the * file size has exceeded the maximum file size, then the * FileUploadException will be added as attribute value instead of the * FileItem object.//w w w . j a v a2 s .com * * @param request The HttpServletRequest to be checked and parsed as * multipart request. * @return The parsed HttpServletRequest. * @throws ServletException If parsing of the given HttpServletRequest * fails. */ @SuppressWarnings("unchecked") // ServletFileUpload#parseRequest() does not return generic type. private HttpServletRequest parseRequest(HttpServletRequest request) throws ServletException { // Check if the request is actually a multipart/form-data request. if (!ServletFileUpload.isMultipartContent(request)) { // If not, then return the request unchanged. // Wrap the request with the parameter map which we just created and return it. return request; } // Prepare the multipart request items. // I'd rather call the "FileItem" class "MultipartItem" instead or so. What a stupid name ;) List<FileItem> multipartItems = null; try { // Parse the multipart request items. multipartItems = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); // Note: we could use ServletFileUpload#setFileSizeMax() here, but that would throw a // FileUploadException immediately without processing the other fields. So we're // checking the file size only if the items are already parsed. See processFileField(). } catch (FileUploadException e) { throw new ServletException("Cannot parse multipart request: " + e.getMessage()); } // Prepare the request parameter map. Map<String, String[]> parameterMap = new HashMap<String, String[]>(); // Loop through multipart request items. for (FileItem multipartItem : multipartItems) { if (multipartItem.isFormField()) { // Process regular form field (input type="text|radio|checkbox|etc", select, etc). processFormField(multipartItem, parameterMap); } else { // Process form file field (input type="file"). processFileField(multipartItem, request); } } // Wrap the request with the parameter map which we just created and return it. return wrapRequest(request, parameterMap); }
From source file:com.globalsight.everest.webapp.pagehandler.administration.mtprofile.MTProfileImportHandler.java
/** * Upload the properties file to FilterConfigurations/import folder * // w ww . jav a 2 s. com * @param request */ private File uploadFile(HttpServletRequest request) { File f = null; try { String tmpDir = AmbFileStoragePathUtils.getFileStorageDirPath() + File.separator + "GlobalSight" + File.separator + "MachineTranslationProfiles" + File.separator + "import"; boolean isMultiPart = ServletFileUpload.isMultipartContent(request); if (isMultiPart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024000); ServletFileUpload upload = new ServletFileUpload(factory); List<?> items = upload.parseRequest(request); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (!item.isFormField()) { String filePath = item.getName(); if (filePath.contains(":")) { filePath = filePath.substring(filePath.indexOf(":") + 1); } String originalFilePath = filePath.replace("\\", File.separator).replace("/", File.separator); String fileName = tmpDir + File.separator + originalFilePath; f = new File(fileName); f.getParentFile().mkdirs(); item.write(f); } } } return f; } catch (Exception e) { logger.error("File upload failed.", e); return null; } }