List of usage examples for org.apache.commons.fileupload FileItemStream openStream
InputStream openStream() throws IOException;
From source file:fi.helsinki.lib.simplerest.CollectionLogoResource.java
@Put public Representation put(Representation logoRepresentation) { Context c = null;// ww w . ja v a2 s . c o m Collection collection; try { c = getAuthenticatedContext(); collection = Collection.find(c, this.collectionId); if (collection == null) { return errorNotFound(c, "Could not find the collection."); } } catch (SQLException e) { return errorInternal(c, e.toString()); } try { RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory()); FileItemIterator iter = rfu.getItemIterator(logoRepresentation); if (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { InputStream inputStream = item.openStream(); collection.setLogo(inputStream); Bitstream logo = collection.getLogo(); BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, item.getContentType()); logo.setFormat(bf); logo.update(); collection.update(); } } c.complete(); } catch (AuthorizeException ae) { return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED); } catch (Exception e) { return errorInternal(c, e.toString()); } return successOk("Logo set."); }
From source file:fi.helsinki.lib.simplerest.CommunityLogoResource.java
@Put public Representation put(Representation logoRepresentation) { Context c = null;/*from w w w . j a v a 2 s . c om*/ Community community; try { c = getAuthenticatedContext(); community = Community.find(c, this.communityId); if (community == null) { return errorNotFound(c, "Could not find the community."); } } catch (SQLException e) { return errorInternal(c, e.toString()); } try { RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory()); FileItemIterator iter = rfu.getItemIterator(logoRepresentation); if (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { InputStream inputStream = item.openStream(); community.setLogo(inputStream); Bitstream logo = community.getLogo(); BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, item.getContentType()); logo.setFormat(bf); logo.update(); community.update(); } } c.complete(); } catch (AuthorizeException ae) { return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED); } catch (Exception e) { return errorInternal(c, e.toString()); } return successOk("Logo set."); }
From source file:foo.domaintest.http.HttpApiModule.java
@Provides @Singleton//from w w w . ja v a 2 s .c o m Multimap<String, String> provideParameterMap(@RequestData("queryString") String queryString, @RequestData("postBody") Lazy<String> lazyPostBody, @RequestData("charset") String requestCharset, FileItemIterator multipartIterator) { // Calling request.getParameter() or request.getParameterMap() etc. consumes the POST body. If // we got the "postpayload" param we don't want to parse the body, so use only the query params. // Note that specifying both "payload" and "postpayload" will result in the "payload" param // being honored and the POST body being completely ignored. ImmutableMultimap.Builder<String, String> params = new ImmutableMultimap.Builder<>(); Multimap<String, String> getParams = parseQuery(queryString); params.putAll(getParams); if (getParams.containsKey("postpayload")) { // Treat the POST body as if it was the "payload" param. return params.put("payload", nullToEmpty(lazyPostBody.get())).build(); } // No "postpayload" so it's safe to consume the POST body and look for params there. if (multipartIterator == null) { // Handle GETs and form-urlencoded POST requests. params.putAll(parseQuery(nullToEmpty(lazyPostBody.get()))); } else { // Handle multipart/form-data requests. try { while (multipartIterator != null && multipartIterator.hasNext()) { FileItemStream item = multipartIterator.next(); try (InputStream stream = item.openStream()) { params.put(item.isFormField() ? item.getFieldName() : item.getName(), CharStreams.toString(new InputStreamReader(stream, requestCharset))); } } } catch (FileUploadException | IOException e) { // Ignore the failure and fall through to return whatever params we managed to parse. } } return params.build(); }
From source file:DBMS.PicUpdateServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from w w w . j av a2 s . c om * @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(); } } }
From source file:hrpod.web.Upload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . ja v a 2s. co m*/ * * @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.setHeader("Content-Type", "application/json"); response.setCharacterEncoding("utf8"); response.setContentType("application/json"); try (PrintWriter out = response.getWriter()) { try { String uploadType = request.getParameter("type"); IngestDataBL ingest = new IngestDataBL(); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.getName() != null) { if (uploadType.equals("resumes")) { ingest.doIngetsJobs(item.openStream()); } else if (uploadType.equals("jobs")) { ingest.doIngetsJobs(item.openStream()); } } } out.write("SUCCESS"); } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.google.dotorg.translation_workflow.servlet.UploadServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, MalformedURLException { String rawProjectId = request.getParameter("projectId"); try {//from w w w. ja v a 2s . c o m ServletFileUpload upload = new ServletFileUpload(); upload.setSizeMax(1048576); UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); Cloud cloud = Cloud.open(); int projectId = Integer.parseInt(rawProjectId); Project project = cloud.getProjectById(projectId); TextValidator nameValidator = TextValidator.BRIEF_STRING; String invalidRows = ""; int validRows = 0; try { FileItemIterator iterator = upload.getItemIterator(request); int articlesLength = 0; while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream in = item.openStream(); if (item.isFormField()) { } else { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); String fileContents = null; if (!contentType.equalsIgnoreCase("text/csv")) { logger.warning("Invalid filetype upload " + contentType); response.sendRedirect( "/project_overview?project=" + rawProjectId + "&msg=invalid_type"); } try { fileContents = IOUtils.toString(in); PersistenceManager pm = cloud.getPersistenceManager(); Transaction tx = pm.currentTransaction(); tx.begin(); String[] lines = fileContents.split("\n"); List<Translation> newTranslations = new ArrayList<Translation>(); articlesLength = lines.length; validRows = articlesLength; int lineNo = 0; for (String line : lines) { lineNo++; line = line.replaceAll("\",", "\";"); line = line.replaceAll("\"", ""); String[] fields = line.split(";"); String articleName = fields[0].replace("_", " "); articleName = nameValidator.filter(URLDecoder.decode(articleName)); try { URL url = new URL(fields[1]); String category = ""; String difficulty = ""; if (fields.length > 2) { category = nameValidator.filter(fields[2]); } if (fields.length > 3) { difficulty = nameValidator.filter(fields[3]); } Translation translation = project.createTranslation(articleName, url.toString(), category, difficulty); newTranslations.add(translation); } catch (MalformedURLException e) { validRows--; invalidRows = invalidRows + "," + lineNo; logger.warning("Invalid URL : " + fields[1]); } } pm.makePersistentAll(newTranslations); tx.commit(); } finally { IOUtils.closeQuietly(in); } } } cloud.close(); logger.info(validRows + " of " + articlesLength + " articles uploaded from csv to the project " + project.getId() + " by User :" + user.getUserId()); if (invalidRows.length() > 0) { response.sendRedirect( "/project_overview?project=" + rawProjectId + "&_invalid=" + invalidRows.substring(1)); } else { response.sendRedirect("/project_overview?project=" + rawProjectId); } /*response.sendRedirect("/project_overview?project=" + rawProjectId + "&_invalid=" + invalidRows.substring(1));*/ } catch (SizeLimitExceededException e) { logger.warning("Exceeded the maximum size (" + e.getPermittedSize() + ") of the file (" + e.getActualSize() + ")"); response.sendRedirect("/project_overview?project=" + rawProjectId + "&msg=size_exceeded"); } } catch (Exception ex) { logger.info("String " + ex.toString()); throw new ServletException(ex); } }
From source file:controllers.UploadController.java
/** * /*from w w w. j av a 2 s .c o m*/ * This upload method expects a file and simply displays the file in the * multipart upload again to the user (in the correct mime encoding). * * @param context * @return * @throws Exception */ public Result uploadFinish(Context context) throws Exception { // we are using a renderable inner class to stream the input again to // the user Renderable renderable = new Renderable() { @Override public void render(Context context, Result result) { try { // make sure the context really is a multipart context... if (context.isMultipart()) { // This is the iterator we can use to iterate over the // contents // of the request. FileItemIterator fileItemIterator = context.getFileItemIterator(); while (fileItemIterator.hasNext()) { FileItemStream item = fileItemIterator.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); String contentType = item.getContentType(); if (contentType != null) { result.contentType(contentType); } else { contentType = mimeTypes.getMimeType(name); } ResponseStreams responseStreams = context.finalizeHeaders(result); if (item.isFormField()) { System.out.println("Form field " + name + " with value " + Streams.asString(stream) + " detected."); } else { System.out.println( "File field " + name + " with file name " + item.getName() + " detected."); // Process the input stream ByteStreams.copy(stream, responseStreams.getOutputStream()); } } } } catch (IOException | FileUploadException exception) { throw new InternalServerErrorException(exception); } } }; return new Result(200).render(renderable); }
From source file:com.boundlessgeo.geoserver.api.controllers.WorkspaceController.java
@RequestMapping(value = "/{wsName}/import", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @ResponseStatus(value = HttpStatus.OK)//from ww w .j av a 2 s .com public void inport(@PathVariable String wsName, HttpServletRequest request, HttpServletResponse response) throws Exception { Catalog cat = geoServer.getCatalog(); WorkspaceInfo ws = findWorkspace(wsName, cat); // grab the uploaded file FileItemIterator files = doFileUpload(request); if (!files.hasNext()) { throw new BadRequestException("Request must contain a single file"); } Path zip = Files.createTempFile(null, null); FileItemStream item = files.next(); try (InputStream stream = item.openStream()) { IOUtils.copy(stream, zip.toFile()); } BundleImporter importer = new BundleImporter(cat, new ImportOpts(ws)); importer.unzip(zip); importer.run(); }
From source file:com.manydesigns.portofino.stripes.StreamingCommonsMultipartWrapper.java
/** * Pseudo-constructor that allows the class to perform any initialization necessary. * * @param request an HttpServletRequest that has a content-type of multipart. * @param tempDir a File representing the temporary directory that can be used to store * file parts as they are uploaded if this is desirable * @param maxPostSize the size in bytes beyond which the request should not be read, and a * FileUploadLimitExceeded exception should be thrown * @throws IOException if a problem occurs processing the request of storing temporary * files//w w w. j a va2 s . c om * @throws FileUploadLimitExceededException if the POST content is longer than the * maxPostSize supplied. */ @SuppressWarnings("unchecked") public void build(HttpServletRequest request, File tempDir, long maxPostSize) throws IOException, FileUploadLimitExceededException { try { this.charset = request.getCharacterEncoding(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(tempDir); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxPostSize); FileItemIterator iterator = upload.getItemIterator(request); Map<String, List<String>> params = new HashMap<String, List<String>>(); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); // If it's a form field, add the string value to the list if (item.isFormField()) { List<String> values = params.get(item.getFieldName()); if (values == null) { values = new ArrayList<String>(); params.put(item.getFieldName(), values); } values.add(charset == null ? IOUtils.toString(stream) : IOUtils.toString(stream, charset)); } // Else store the file param else { TempFile tempFile = TempFileService.getInstance().newTempFile(item.getContentType(), item.getName()); int size = IOUtils.copy(stream, tempFile.getOutputStream()); FileItem fileItem = new FileItem(item.getName(), item.getContentType(), tempFile, size); files.put(item.getFieldName(), fileItem); } } // Now convert them down into the usual map of String->String[] for (Map.Entry<String, List<String>> entry : params.entrySet()) { List<String> values = entry.getValue(); this.parameters.put(entry.getKey(), values.toArray(new String[values.size()])); } } catch (FileUploadBase.SizeLimitExceededException slee) { throw new FileUploadLimitExceededException(maxPostSize, slee.getActualSize()); } catch (FileUploadException fue) { IOException ioe = new IOException("Could not parse and cache file upload data."); ioe.initCause(fue); throw ioe; } }
From source file:com.sifiso.dvs.util.DocFileUtil.java
public ResponseDTO downloadPDF(HttpServletRequest request, PlatformUtil platformUtil) throws FileUploadException { logger.log(Level.INFO, "######### starting PDF DOWNLOAD process\n\n"); ResponseDTO resp = new ResponseDTO(); InputStream stream = null;/*from w w w . j av a 2 s . c o m*/ File rootDir; try { rootDir = dvsProperties.getDocumentDir(); logger.log(Level.INFO, "rootDir - {0}", rootDir.getAbsolutePath()); if (!rootDir.exists()) { rootDir.mkdir(); } } catch (Exception ex) { logger.log(Level.SEVERE, "Properties file problem", ex); resp.setMessage("Server file unavailable. Please try later"); resp.setStatusCode(114); return resp; } PatientfileDTO dto = null; Gson gson = new Gson(); File clientDir = null, surgeryDir = null, doctorDir = null; try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); stream = item.openStream(); if (item.isFormField()) { if (name.equalsIgnoreCase("JSON")) { String json = Streams.asString(stream); if (json != null) { logger.log(Level.INFO, "picture with associated json: {0}", json); dto = gson.fromJson(json, PatientfileDTO.class); if (dto != null) { surgeryDir = createSurgeryFileDirectory(rootDir, surgeryDir, dto.getDoctor().getSurgeryID()); if (dto.getDoctorID() != null) { doctorDir = createDoctorDirectory(surgeryDir, doctorDir, dto.getDoctorID()); if (dto.getClientID() != null) { clientDir = createClientDirectory(doctorDir, clientDir); } } } } else { logger.log(Level.WARNING, "JSON input seems pretty fucked up! is NULL.."); } } } else { File imageFile = null; if (dto == null) { continue; } DateTime dt = new DateTime(); String fileName = ""; if (dto.getClientID() != null) { fileName = "client" + dto.getClientID() + ".pdf"; } imageFile = new File(clientDir, fileName); writeFile(stream, imageFile); resp.setStatusCode(0); resp.setMessage("Photo downloaded from mobile app "); //add database System.out.println("filepath: " + imageFile.getAbsolutePath()); } } } catch (FileUploadException | IOException | JsonSyntaxException ex) { logger.log(Level.SEVERE, "Servlet failed on IOException, images NOT uploaded", ex); throw new FileUploadException(); } return resp; }