List of usage examples for org.apache.commons.fileupload FileItemStream getFieldName
String getFieldName();
From source file:com.google.appinventor.server.GalleryServlet.java
private InputStream getRequestStream(HttpServletRequest req, String expectedFieldName) throws Exception { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); // LOG.info(item.getContentType()); if (item.getFieldName().equals(expectedFieldName)) { return item.openStream(); }/*from w ww . ja va 2 s . c o m*/ } throw new IllegalArgumentException("Field " + expectedFieldName + " not found in upload"); }
From source file:com.smartgwt.extensions.fileuploader.server.TestServiceImpl.java
private void processFiles(HttpServletRequest request, HttpServletResponse response) { HashMap<String, String> args = new HashMap<String, String>(); try {/*www .j a va 2 s . co m*/ ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); FileItemStream fileItem = null; // pick up parameters first and note actual FileItem while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if (item.isFormField()) { args.put(name, Streams.asString(item.openStream())); } else { fileItem = item; } } if (fileItem != null) { args.put("contentType", fileItem.getContentType()); args.put("fileName", FileUtils.filename(fileItem.getName())); System.out.println("uploading args " + args); String context = args.get("context"); String model = args.get("model"); String xq = args.get("xq"); System.out.println(context + "," + model + "," + xq); File f = new File(args.get("fileName")); System.out.println(f.getAbsolutePath()); /* * TODO: pboysen get the state, context and fileManager and store the * stream in fileName. Parameters should be passed to locate state * and conversion options. */ response.setContentType("text/html"); response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<script>"); out.println("top.uploadComplete('" + args.get("fileName") + "');"); out.println("</script>"); out.println("</body>"); out.println("</html>"); out.flush(); } else { //TODO: add error code } } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:com.google.publicalerts.cap.validator.CapValidatorServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String input = null;// w ww . ja v a 2 s . c om String fileInput = null; String example = null; Set<CapProfile> profiles = Sets.newHashSet(); try { FileItemIterator itemItr = upload.getItemIterator(req); while (itemItr.hasNext()) { FileItemStream item = itemItr.next(); if ("input".equals(item.getFieldName())) { input = ValidatorUtil.readFully(item.openStream()); } else if (item.getFieldName().startsWith("inputfile")) { fileInput = ValidatorUtil.readFully(item.openStream()); } else if ("example".equals(item.getFieldName())) { example = ValidatorUtil.readFully(item.openStream()); } else if ("profile".equals(item.getFieldName())) { String profileCode = ValidatorUtil.readFully(item.openStream()); profiles.addAll(ValidatorUtil.parseProfiles(profileCode)); } } } catch (FileUploadException e) { throw new ServletException(e); } if (!CapUtil.isEmptyOrWhitespace(example)) { log.info("ExampleRequest: " + example); input = loadExample(example); profiles = ImmutableSet.of(); } else if (!CapUtil.isEmptyOrWhitespace(fileInput)) { log.info("FileInput"); input = fileInput; } input = (input == null) ? "" : input.trim(); if ("".equals(input)) { log.info("EmptyRequest"); doGet(req, resp); return; } ValidationResult result = capValidator.validate(input, profiles); req.setAttribute("input", input); req.setAttribute("profiles", ValidatorUtil.getProfilesJsp(profiles)); req.setAttribute("validationResult", result); req.setAttribute("lines", Arrays.asList(result.getInput().split("\n"))); req.setAttribute("timing", result.getTiming()); JSONArray alertsJs = new MapVisualizer(result.getValidAlerts()).getAlertsJs(); if (alertsJs != null) { req.setAttribute("alertsJs", alertsJs.toString()); } render(req, resp); }
From source file:foo.domaintest.email.EmailApiModule.java
/** * Provides parsed email headers from the "headers" param in a multipart/form-data request. * <p>/*from w w w . ja v a2 s .c o m*/ * Although SendGrid parses some headers for us, it doesn't parse "reply-to", so we need to do * this. Once we are doing it, it's easier to be consistent and use this as the sole source of * truth for information that originates in the headers. */ @Provides @Singleton InternetHeaders provideHeaders(FileItemIterator iterator) { try { while (iterator != null && iterator.hasNext()) { FileItemStream item = iterator.next(); // SendGrid sends us the headers in the "headers" param. if (item.getFieldName().equals("headers")) { try (InputStream stream = item.openStream()) { // SendGrid always sends headers in UTF-8 encoding. return new InternetHeaders(new ByteArrayInputStream( CharStreams.toString(new InputStreamReader(stream, UTF_8.name())).getBytes(UTF_8))); } } } } catch (MessagingException | FileUploadException | IOException e) { // If we fail parsing the headers fall through returning the empty header object below. } return new InternetHeaders(); // Parsing failed or there was no "headers" param. }
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;//w w w.j a v a2 s . c om 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; }
From source file:com.vmware.photon.controller.api.frontend.resources.vm.VmIsoAttachResource.java
private Task parseIsoDataFromRequest(HttpServletRequest request, String id) throws InternalException, ExternalException { Task task = null;//from ww w .ja v a2s. c om ServletFileUpload fileUpload = new ServletFileUpload(); List<InputStream> dataStreams = new LinkedList<>(); try { FileItemIterator iterator = fileUpload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField()) { logger.warn(String.format("The parameter '%s' is unknown in attach ISO.", item.getFieldName())); } else { InputStream fileStream = item.openStream(); dataStreams.add(fileStream); task = vmFeClient.attachIso(id, fileStream, item.getName()); } } } catch (IOException ex) { throw new IsoUploadException("Iso upload IOException", ex); } catch (FileUploadException ex) { throw new IsoUploadException("Iso upload FileUploadException", ex); } finally { for (InputStream stream : dataStreams) { try { stream.close(); } catch (IOException | NullPointerException ex) { logger.warn("Unexpected exception closing data stream.", ex); } } } if (task == null) { throw new IsoUploadException("There is no iso stream data in the iso upload request."); } return task; }
From source file:com.smartgwt.extensions.fileuploader.server.ProjectServlet.java
private void processFiles(HttpServletRequest request, HttpServletResponse response) { HashMap<String, String> args = new HashMap<String, String>(); boolean isGWT = true; try {//from www . j a v a 2 s . c o m if (log.isDebugEnabled()) log.debug(request.getParameterMap()); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); // pick up parameters first and note actual FileItem while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if (item.isFormField()) { args.put(name, Streams.asString(item.openStream())); } else { args.put("contentType", item.getContentType()); String fileName = item.getName(); int slash = fileName.lastIndexOf("/"); if (slash < 0) slash = fileName.lastIndexOf("\\"); if (slash > 0) fileName = fileName.substring(slash + 1); args.put("fileName", fileName); // upload requests can come from smartGWT (args) or // FCKEditor (request) String contextName = args.get("context"); String model = args.get("model"); String path = args.get("path"); if (contextName == null) { isGWT = false; contextName = request.getParameter("context"); model = request.getParameter("model"); path = request.getParameter("path"); if (log.isDebugEnabled()) log.debug("query=" + request.getQueryString()); } else if (log.isDebugEnabled()) log.debug(args); // the following code stores the file based on your parameters /* ProjectContext context = ContextService.get().getContext( contextName); ProjectState state = (ProjectState) request.getSession() .getAttribute(contextName); InputStream in = null; try { in = item.openStream(); state.getFileManager().storeFile( context.getModel(model), path + fileName, in); } catch (Exception e) { e.printStackTrace(); log.error("Fail to upload " + fileName + " to " + path); } finally { if (in != null) try { in.close(); } catch (Exception e) { } } */ } } // TODO: need to handle conversion options and error reporting response.setContentType("text/html"); response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); if (isGWT) { out.println("<script type=\"text/javascript\">"); out.println("if (parent.uploadComplete) parent.uploadComplete('" + args.get("fileName") + "');"); out.println("</script>"); } else out.println(getEditorResponse()); out.println("</body>"); out.println("</html>"); out.flush(); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:com.fullmetalgalaxy.server.pm.PMServlet.java
@Override protected void doPost(HttpServletRequest p_request, HttpServletResponse p_response) throws ServletException, IOException { ServletFileUpload upload = new ServletFileUpload(); try {//w w w .j a v a 2 s.co m // build message to send Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage msg = new MimeMessage(session); msg.setSubject("[FMG] no subject", "text/plain"); msg.setSender(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin")); msg.setFrom(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin")); EbAccount fromAccount = null; // Parse the request FileItemIterator iter = upload.getItemIterator(p_request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (item.isFormField()) { if ("msg".equalsIgnoreCase(item.getFieldName())) { msg.setContent(Streams.asString(item.openStream(), "UTF-8"), "text/plain"); } if ("subject".equalsIgnoreCase(item.getFieldName())) { msg.setSubject("[FMG] " + Streams.asString(item.openStream(), "UTF-8"), "text/plain"); } if ("toid".equalsIgnoreCase(item.getFieldName())) { EbAccount account = null; try { account = FmgDataStore.dao().get(EbAccount.class, Long.parseLong(Streams.asString(item.openStream(), "UTF-8"))); } catch (NumberFormatException e) { } if (account != null) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(account.getEmail(), account.getPseudo())); } } if ("fromid".equalsIgnoreCase(item.getFieldName())) { try { fromAccount = FmgDataStore.dao().get(EbAccount.class, Long.parseLong(Streams.asString(item.openStream(), "UTF-8"))); } catch (NumberFormatException e) { } if (fromAccount != null) { if (fromAccount.getAuthProvider() == AuthProvider.Google && !fromAccount.isHideEmailToPlayer()) { msg.setFrom(new InternetAddress(fromAccount.getEmail(), fromAccount.getPseudo())); } else { msg.setFrom( new InternetAddress(fromAccount.getFmgEmail(), fromAccount.getPseudo())); } } } } } // msg.addRecipients( Message.RecipientType.BCC, InternetAddress.parse( // "archive@fullmetalgalaxy.com" ) ); Transport.send(msg); } catch (Exception e) { log.error(e); p_response.sendRedirect("/genericmsg.jsp?title=Error&text=" + e.getMessage()); return; } p_response.sendRedirect("/genericmsg.jsp?title=Message envoye"); }
From source file:graphql.servlet.GraphQLServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { GraphQLContext context = createContext(Optional.of(req), Optional.of(resp)); InputStream inputStream = null; if (ServletFileUpload.isMultipartContent(req)) { ServletFileUpload upload = new ServletFileUpload(); try {/*from w w w . ja v a 2 s . c o m*/ FileItemIterator it = upload.getItemIterator(req); context.setFiles(Optional.of(it)); while (inputStream == null && it.hasNext()) { FileItemStream stream = it.next(); if (stream.getFieldName().contentEquals("graphql")) { inputStream = stream.openStream(); } } if (inputStream == null) { throw new ServletException("no query found"); } } catch (FileUploadException e) { throw new ServletException("no query found"); } } else { // this is not a multipart request inputStream = req.getInputStream(); } Request request = new ObjectMapper().readValue(inputStream, Request.class); Map<String, Object> variables = request.variables; if (variables == null) { variables = new HashMap<>(); } query(request.query, request.operationName, variables, getSchema(), req, resp, context); }
From source file:freedots.web.MusicXML2BrailleServlet.java
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { Score score = null;//from w ww .j a v a 2s . c o m BrailleEncoding brailleEncoding = BrailleEncoding.UnicodeBraille; int width = 40, height = 25; InputStream stream = null; ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { final FileItemStream item = iterator.next(); if (item.getFieldName().compareTo("file.xml") == 0) { String extension = "xml"; if (item.getName().endsWith(".mxl")) extension = "mxl"; score = parseMusicXML(item.openStream(), extension); } else if (item.getFieldName().compareTo("encoding") == 0) { final BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream())); final String line = reader.readLine(); if (line != null) { try { brailleEncoding = Enum.valueOf(BrailleEncoding.class, line); } catch (IllegalArgumentException e) { LOG.info("Unknown encoding " + line + ", falling back to default"); } } } else if (item.getFieldName().compareTo("width") == 0) { final BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream())); final String line = reader.readLine(); if (line != null && !line.isEmpty()) { try { final int value = Integer.parseInt(line); if (value >= MIN_COLUMNS_PER_LINE && value <= MAX_COLUMNS_PER_LINE) width = value; } catch (NumberFormatException e) { LOG.info("Not a proper number: " + line + ", falling back to default"); } } } else if (item.getFieldName().compareTo("height") == 0) { final BufferedReader reader = new BufferedReader(new InputStreamReader(item.openStream())); final String line = reader.readLine(); if (line != null && !line.isEmpty()) { try { final int value = Integer.parseInt(line); if (value >= MIN_LINES_PER_PAGE && value <= MAX_LINES_PER_PAGE) height = value; } catch (NumberFormatException e) { LOG.info("Not a proper number: " + line + ", falling back to default"); } } } } } catch (org.apache.commons.fileupload.FileUploadException e) { LOG.info("FileUploadException error"); resp.sendError(500); } if (score != null) { writeResult(score, width, height, Method.SectionBySection, brailleEncoding, resp); } else { resp.sendRedirect("/"); } }