List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent
public static final boolean isMultipartContent(HttpServletRequest request)
From source file:graphvis.webui.servlets.UploadServlet.java
/** * This method receives POST from the index.jsp page and uploads file, * converts into the correct format then places in the HDFS. *///from ww w.ja v a2s. co m protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { response.setStatus(403); return; } File tempDirFileObject = new File(Configuration.tempDirectory); // Create/remove temp folder if (tempDirFileObject.exists()) { FileUtils.deleteDirectory(tempDirFileObject); } // (Re-)create temp directory tempDirFileObject.mkdir(); FileUtils.copyFile( new File(getServletContext() .getRealPath("giraph-1.1.0-SNAPSHOT-for-hadoop-2.2.0-jar-with-dependencies.jar")), new File(Configuration.tempDirectory + "/giraph-1.1.0-SNAPSHOT-for-hadoop-2.2.0-jar-with-dependencies.jar")); FileUtils.copyFile(new File(getServletContext().getRealPath("dist-graphvis.jar")), new File(Configuration.tempDirectory + "/dist-graphvis.jar")); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Sets the size threshold beyond which files are written directly to // disk. factory.setSizeThreshold(Configuration.MAX_MEMORY_SIZE); // Sets the directory used to temporarily store files that are larger // than the configured size threshold. We use temporary directory for // java factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(Configuration.MAX_REQUEST_SIZE); String fileName = ""; try { // Parse the request List<?> items = upload.parseRequest(request); Iterator<?> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { fileName = new File(item.getName()).getName(); String filePath = Configuration.tempDirectory + File.separator + fileName; File uploadedFile = new File(filePath); System.out.println(filePath); // saves the file to upload directory try { item.write(uploadedFile); } catch (Exception ex) { throw new ServletException(ex); } } } String fullFilePath = Configuration.tempDirectory + File.separator + fileName; String extension = FilenameUtils.getExtension(fullFilePath); // Load Files intoHDFS // (This is where we do the parsing.) loadIntoHDFS(fullFilePath, extension); getServletContext().setAttribute("fileName", new File(fullFilePath).getName()); getServletContext().setAttribute("fileExtension", extension); // Displays fileUploaded.jsp page after upload finished getServletContext().getRequestDispatcher("/fileUploaded.jsp").forward(request, response); } catch (FileUploadException ex) { throw new ServletException(ex); } }
From source file:com.krawler.br.spring.RConverterImpl.java
@Override public Map convert(HttpServletRequest request, BusinessProcess process) throws ProcessException { try {//from w w w .j a va 2 s . c o m df = authHandler.getDateFormatter(request); } catch (SessionExpiredException ex) { throw new ProcessException(ex); } if (ServletFileUpload.isMultipartContent(request)) { return convertWithFile(request, process.getInputParams()); } else { return convert(request, process.getInputParams()); } }
From source file:fr.opensagres.xdocreport.document.web.UploadXDocReportServlet.java
/** * Handles all requests (by default).//from ww w .ja va2 s . c o m * * @param request HttpServletRequest object containing client request * @param response HttpServletResponse object for the response */ protected void doUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request try { @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); for (Iterator<FileItem> iterator = items.iterator(); iterator.hasNext();) { FileItem fileItem = (FileItem) iterator.next(); if ("uploadfile".equals(fileItem.getFieldName())) { InputStream in = fileItem.getInputStream(); try { String reportId = generateReportId(fileItem, request); IXDocReport report = getRegistryForUpload(request).loadReport(in, reportId); // Check if report id exists in global registry getRegistry(request).checkReportId(report.getId()); reportLoaded(report, request); doForward(report, request, response); break; } catch (XDocReportException e) { throw new ServletException(e); } } } } catch (FileUploadException e) { throw new ServletException(e); } } }
From source file:br.edu.ifpb.ads.psd.projeto.servlets.UploadImagemPerfil.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w ww.j a v a2s . co m*/ * @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 { Usuario usuario = ((Usuario) request.getSession().getAttribute("usuario")); if (usuario == null) { response.sendRedirect(""); } else { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = null; try { items = (List<FileItem>) upload.parseRequest(request); } catch (FileUploadException ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } FileItem item = items.get(0); if (item != null) { String nome_arquivo = String.valueOf(new Date().getTime()) + item.getName(); String caminho = getServletContext().getRealPath("/imagens") + "\\" + usuario.getId() + "\\"; File file = new File(caminho); if (!file.exists()) { file.mkdirs(); } File uploadedFile = new File(caminho + nome_arquivo); try { item.write(uploadedFile); } catch (Exception ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } GerenciadorDeUsuario gerenciarUsuario = new GerenciadorDeUsuario(); try { gerenciarUsuario.atualizarFotoPerfil("imagens" + "/" + usuario.getId() + "/" + nome_arquivo, usuario.getId()); } catch (SQLException ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } GerenciarFotos gerenciarFotos = new GerenciarFotos(); try { gerenciarFotos.publicarFoto("imagens" + "/" + usuario.getId() + "/" + nome_arquivo, usuario); } catch (SQLException ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } try { usuario = gerenciarUsuario.getUsuario(usuario.getId()); } catch (SQLException ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } request.getSession().setAttribute("usuario", usuario); response.sendRedirect("configuracao"); } else { } } } }
From source file:com.cognifide.aet.executor.SuiteServlet.java
/** * Starts processing of the test suite defined in the XML file provided in post body. Overrides * domain specified in the suite file if one has been provided in post body. Returns JSON defined * by {@link SuiteExecutionResult}. The request's content type must be 'multipart/form-data'. * * @param request/*from w w w . ja v a 2s .c om*/ * @param response * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (ServletFileUpload.isMultipartContent(request)) { Map<String, String> requestData = getRequestData(request); String suite = requestData.get(SUITE_PARAM); String domain = requestData.get(DOMAIN_PARAM); if (StringUtils.isNotBlank(suite)) { SuiteExecutionResult suiteExecutionResult = suiteExecutor.execute(suite, domain); Gson gson = new Gson(); String responseBody = gson.toJson(suiteExecutionResult); if (suiteExecutionResult.getErrorMessage() == null) { response.setStatus(200); response.setContentType("application/json"); response.setCharacterEncoding(CharEncoding.UTF_8); response.getWriter().write(responseBody); } else { response.sendError(500, suiteExecutionResult.getErrorMessage()); } } else { response.sendError(400, "Request does not contain the test suite"); } } else { response.sendError(400, "Request content is incorrect"); } }
From source file:com.br.ifpb.servlet.UploadImagemPerfil.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w ww . j ava 2 s.com*/ * @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 { Usuario usuario = ((Usuario) request.getSession().getAttribute("usuario")); if (usuario == null) { response.sendRedirect(""); } else { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = null; try { items = (List<FileItem>) upload.parseRequest(request); } catch (FileUploadException ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } FileItem item = items.get(0); if (item != null) { String nome_arquivo = String.valueOf(new Date().getTime()) + item.getName(); String caminho = getServletContext().getRealPath("/imagens") + "\\" + usuario.getId() + "\\"; File file = new File(caminho); if (!file.exists()) { file.mkdirs(); } File uploadedFile = new File(caminho + nome_arquivo); try { item.write(uploadedFile); } catch (Exception ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } GerenciarUsuario gerenciarUsuario = new GerenciarUsuario(); try { gerenciarUsuario.atualizarFotoPerfil("imagens" + "/" + usuario.getId() + "/" + nome_arquivo, usuario.getId()); } catch (PersistenciaException ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } GerenciarFotos gerenciarFotos = new GerenciarFotos(); try { gerenciarFotos.publicarFoto("imagens" + "/" + usuario.getId() + "/" + nome_arquivo, Timestamp.valueOf(LocalDateTime.now()), usuario); } catch (PersistenciaException ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } try { usuario = gerenciarUsuario.getUsuario(usuario.getId()); } catch (PersistenciaException ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } request.getSession().setAttribute("usuario", usuario); response.sendRedirect("configuracao"); } else { } } } }
From source file:de.htwg_konstanz.ebus.wholesaler.demo.ImportXML.java
@Override public final String execute(final HttpServletRequest request, final HttpServletResponse response, final ArrayList<String> errorList) { // get the login bean from the session LoginBean loginBean = (LoginBean) request.getSession(true).getAttribute(PARAM_LOGIN_BEAN); // ensure that the user is logged in if (loginBean != null && loginBean.isLoggedIn()) { // ensure that the user is allowed to execute this action (authorization) // at this time the authorization is not fully implemented. // -> use the "Security.RESOURCE_ALL" constant which includes all resources. if (Security.getInstance().isUserAllowed(loginBean.getUser(), Security.RESOURCE_ALL, Security.ACTION_READ)) { response.setContentType("text/html;charset=UTF-8"); /*-------------------------------------- -- Start Import/*from www.jav a 2 s . c o m*/ ----------------------------------------*/ // Input Stream which has to be parsed InputStream is; // Check if the form was sended if (ServletFileUpload.isMultipartContent(request)) { try { is = upload.upload(request); // Server-Side check if a File was chosen or if it was an emty File if (is == null) { return "importxml.jsp?errormessage=File was empty!!!!!!! Or wrong file-type. only xml is allowed"; } // Returns the valid XML document ParseReportDTO report = xmlParser.validateTheXml(is); org.w3c.dom.Document doc = report.getDoc(); if (doc == null) { return "importxml.jsp?errormessage=" + report.getMessage(); } System.out.println(doc); // Reads the XML-File and saves the Products to the Database ReportDTO returnval = saveProduct.readXML(doc); // Writes the products which are already in database to the URL String notimported = ""; if (returnval.getNotImported() != null) { ListIterator<Integer> li = returnval.getNotImported().listIterator(); while (li.hasNext()) { notimported = notimported + li.next() + ","; } } if (returnval.getType()) { return "importxml.jsp?infomessage=" + returnval.getMessage(); } else { return "importxml.jsp?errormessage=" + returnval.getMessage() + "¬imported=" + notimported; } // XML File Validieeren } catch (FileUploadException | IOException | SAXException | ParserConfigurationException ex) { Logger.getLogger(ImportXML.class.getName()).log(Level.SEVERE, null, ex); } } // Rendering the import page return "importxml.jsp"; } else { // authorization failed -> show error message errorList.add("You are not allowed to perform this action!"); // redirect to the welcome page return "welcome.jsp"; } } else { // redirect to the login page return "login.jsp"; } }
From source file:com.manning.cmis.theblend.servlets.AddServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response, Session session) throws ServletException, IOException, TheBlendException { // check for multipart content boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { // we expected content -> return to add page dispatch("add.jsp", "Add something new. The Blend.", request, response); }//from w w w. j ava2s .com Map<String, Object> properties = new HashMap<String, Object>(); File uploadedFile = null; String parentId = null; String parentPath = null; ObjectId newId = null; // process the request try { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(50 * 1024 * 1024); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { String name = item.getFieldName(); if (PARAM_PARENT_ID.equalsIgnoreCase(name)) { parentId = item.getString(); } else if (PARAM_PARENT_PATH.equalsIgnoreCase(name)) { parentPath = item.getString(); } else if (PARAM_TYPE_ID.equalsIgnoreCase(name)) { properties.put(PropertyIds.OBJECT_TYPE_ID, item.getString()); } } else { String name = item.getName(); if (name == null) { name = "file"; } else { // if the browser provided a path instead of a file name, // strip off the path int x = name.lastIndexOf('/'); if (x > -1) { name = name.substring(x + 1); } x = name.lastIndexOf('\\'); if (x > -1) { name = name.substring(x + 1); } name = name.trim(); if (name.length() == 0) { name = "file"; } } properties.put(PropertyIds.NAME, name); uploadedFile = File.createTempFile("blend", "tmp"); item.write(uploadedFile); } } } catch (Exception e) { throw new TheBlendException("Upload failed: " + e, e); } if (uploadedFile == null) { throw new TheBlendException("No content!"); } try { // prepare the content stream ContentStream contentStream = null; try { String objectTypeId = (String) properties.get(PropertyIds.OBJECT_TYPE_ID); contentStream = prepareContentStream(session, uploadedFile, objectTypeId, properties); } catch (Exception e) { throw new TheBlendException("Upload failed: " + e, e); } // find the parent folder // (we don't deal with unfiled documents here) Folder parent = null; if (parentId != null) { parent = CMISHelper.getFolder(session, parentId, CMISHelper.LIGHT_OPERATION_CONTEXT, "parent folder"); } else { parent = CMISHelper.getFolderByPath(session, parentPath, CMISHelper.LIGHT_OPERATION_CONTEXT, "parent folder"); } // create the document try { newId = session.createDocument(properties, parent, contentStream, null); } catch (CmisBaseException cbe) { throw new TheBlendException("Could not create document: " + cbe.getMessage(), cbe); } finally { try { contentStream.getStream().close(); } catch (IOException ioe) { // ignore } } } finally { // delete temp file uploadedFile.delete(); } // show the newly created document redirect(HTMLHelper.encodeUrlWithId(request, "show", newId.getId()), request, response); }
From source file:com.google.reducisaurus.servlets.BaseServlet.java
@Override protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { String filecontents;// w ww. j a va 2 s. com boolean useMemcache = isMemcacheAllowed(req); if (ServletFileUpload.isMultipartContent(req)) { filecontents = collectFromFileUpload(req); } else { filecontents = collectFromFormArgs(req); } filecontents = filecontents.trim(); if (filecontents.length() == 0) { resp.setStatus(STATUS_CODE_ERROR); resp.setContentType(CONTENT_TYPE_ERROR); resp.getWriter().println("No data to parse!"); return; } final String key = getKeyForContents(filecontents); Object cachedCopy; if (useMemcache && (cachedCopy = memcache.get(key)) != null) { maybeSetHttpCacheHeaders(req, resp); render(resp, (String) cachedCopy); } else { StringReader reader = new StringReader(filecontents); Response results = process(resp, reader); if (results.isCacheable()) { maybeSetHttpCacheHeaders(req, resp); if (useMemcache) { memcache.put(key, results.getBody()); } } render(resp, results.getBody()); } }
From source file:DBMS.PicUpdateServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/* ww w. j ava 2 s .c o m*/ * @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 { response.setContentType("text/html;charset=UTF-8"); boolean isMultiPart = ServletFileUpload.isMultipartContent(request); if (isMultiPart) { ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator itr = upload.getItemIterator(request); while (itr.hasNext()) { FileItemStream item = itr.next(); if (item.isFormField()) { String fieldName = item.getFieldName(); InputStream is = item.openStream(); byte[] b = new byte[is.available()]; is.read(b); String value = new String(b); System.out.println("Getting"); } else { String path = getServletContext().getRealPath("/"); loginid lid = null; HttpSession session = request.getSession(); lid = (loginid) session.getAttribute("lid"); int id = lid.getId(); if (UpdateFileUpload.processFile(path, item, id)) { response.sendRedirect("ProfilePicUpdateSuccess.jsp"); } else response.sendRedirect("ProfilePicUpdateFailed.jsp"); } } } catch (FileUploadException e) { e.printStackTrace(); } } }