List of usage examples for javax.servlet.http Part getContentType
public String getContentType();
From source file:org.nuxeo.ecm.platform.ui.web.util.files.FileUtils.java
/** * Creates a Blob from a {@link Part}./*from w w w .ja v a 2 s.c om*/ * <p> * Attempts to capture the underlying temporary file, if one exists. This needs to use reflection to avoid having * dependencies on the application server. * * @param part the servlet part * @return the blob * @since 7.2 */ public static Blob createBlob(Part part) throws IOException { Blob blob = null; try { // part : org.apache.catalina.core.ApplicationPart // part.fileItem : org.apache.tomcat.util.http.fileupload.disk.DiskFileItem // part.fileItem.isInMemory() : false if on disk // part.fileItem.getStoreLocation() : java.io.File Field fileItemField = part.getClass().getDeclaredField("fileItem"); fileItemField.setAccessible(true); Object fileItem = fileItemField.get(part); if (fileItem != null) { Method isInMemoryMethod = fileItem.getClass().getDeclaredMethod("isInMemory"); boolean inMemory = ((Boolean) isInMemoryMethod.invoke(fileItem)).booleanValue(); if (!inMemory) { Method getStoreLocationMethod = fileItem.getClass().getDeclaredMethod("getStoreLocation"); File file = (File) getStoreLocationMethod.invoke(fileItem); if (file != null) { // move the file to a temporary blob we own blob = Blobs.createBlobWithExtension(null); Files.move(file.toPath(), blob.getFile().toPath(), StandardCopyOption.REPLACE_EXISTING); } } } } catch (ReflectiveOperationException | SecurityException | IllegalArgumentException e) { // unknown Part implementation } if (blob == null) { // if we couldn't get to the file, use the InputStream blob = Blobs.createBlob(part.getInputStream()); } blob.setMimeType(part.getContentType()); blob.setFilename(retrieveFilename(part)); return blob; }
From source file:org.apache.servicecomb.demo.springmvc.server.CodeFirstSpringmvc.java
private String _fileUpload(MultipartFile file1, Part file2) { try (InputStream is1 = file1.getInputStream(); InputStream is2 = file2.getInputStream()) { String content1 = IOUtils.toString(is1); String content2 = IOUtils.toString(is2); return String.format("%s:%s:%s\n" + "%s:%s:%s", file1.getOriginalFilename(), file1.getContentType(), content1, file2.getSubmittedFileName(), file2.getContentType(), content2); } catch (IOException e) { throw new IllegalArgumentException(e); }//from w w w . j a va 2 s.c o m }
From source file:org.ohmage.request.Request.java
/** * Reads the HttpServletRequest for a key-value pair and returns the value * where the key is equal to the given key. * //from w w w . j a v a 2 s . com * @param httpRequest A "multipart/form-data" request that contains the * parameter that has a key value 'key'. * * @param key The key for the value we are after in the 'httpRequest'. * * @return Returns null if there is no such key in the request or if, * after reading the object, it has a length of 0. Otherwise, it * returns the value associated with the key as a byte array. * * @throws ServletException Thrown if the 'httpRequest' is not a * "multipart/form-data" request. * * @throws IOException Thrown if there is an error reading the value from * the request's input stream. * * @throws IllegalStateException Thrown if the entire request is larger * than the maximum allowed size for a * request or if the value of the requested * key is larger than the maximum allowed * size for a single value. */ protected byte[] getMultipartValue(HttpServletRequest httpRequest, String key) throws ValidationException { try { Part part = httpRequest.getPart(key); if (part == null) { return null; } // Get the input stream. InputStream partInputStream = part.getInputStream(); // Wrap the input stream in a GZIP de-compressor if it is GZIP'd. String contentType = part.getContentType(); if ((contentType != null) && contentType.contains("gzip")) { LOGGER.info("Part was GZIP'd: " + key); partInputStream = new GZIPInputStream(partInputStream); } // Parse the data. ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] chunk = new byte[4096]; int amountRead; while ((amountRead = partInputStream.read(chunk)) != -1) { outputStream.write(chunk, 0, amountRead); } if (outputStream.size() == 0) { return null; } else { return outputStream.toByteArray(); } } catch (ServletException e) { LOGGER.error("This is not a multipart/form-data POST.", e); setFailed(ErrorCode.SYSTEM_GENERAL_ERROR, "This is not a multipart/form-data POST which is what we expect for the current API call."); throw new ValidationException(e); } catch (IOException e) { LOGGER.info("There was a problem with the zipping of the data.", e); throw new ValidationException(ErrorCode.SERVER_INVALID_GZIP_DATA, "The zipped data was not valid zip data.", e); } }
From source file:org.ohmage.request.survey.SurveyUploadRequest.java
/** * Creates a new survey upload request./*from w w w . j a v a 2 s.c o m*/ * * @param httpRequest The HttpServletRequest with the parameters for this * request. * * @throws InvalidRequestException Thrown if the parameters cannot be * parsed. * * @throws IOException There was an error reading from the request. */ public SurveyUploadRequest(HttpServletRequest httpRequest) throws IOException, InvalidRequestException { super(httpRequest, false, TokenLocation.PARAMETER, null); LOGGER.info("Creating a survey upload request."); String tCampaignUrn = null; DateTime tCampaignCreationTimestamp = null; List<JSONObject> tJsonData = null; Map<UUID, Image> tImageContentsMap = null; Map<String, Video> tVideoContentsMap = null; Map<String, Audio> tAudioContentsMap = null; if (!isFailed()) { try { Map<String, String[]> parameters = getParameters(); // Validate the campaign URN String[] t = parameters.get(InputKeys.CAMPAIGN_URN); if (t == null || t.length != 1) { throw new ValidationException(ErrorCode.CAMPAIGN_INVALID_ID, "campaign_urn is missing or there is more than one."); } else { tCampaignUrn = CampaignValidators.validateCampaignId(t[0]); if (tCampaignUrn == null) { throw new ValidationException(ErrorCode.CAMPAIGN_INVALID_ID, "The campaign ID is invalid."); } } // Validate the campaign creation timestamp t = parameters.get(InputKeys.CAMPAIGN_CREATION_TIMESTAMP); if (t == null || t.length != 1) { throw new ValidationException(ErrorCode.SERVER_INVALID_TIMESTAMP, "campaign_creation_timestamp is missing or there is more than one"); } else { // Make sure it's a valid timestamp. try { tCampaignCreationTimestamp = DateTimeUtils.getDateTimeFromString(t[0]); } catch (IllegalArgumentException e) { throw new ValidationException(ErrorCode.SERVER_INVALID_DATE, e.getMessage(), e); } } byte[] surveyDataBytes = getParameter(httpRequest, InputKeys.SURVEYS); if (surveyDataBytes == null) { throw new ValidationException(ErrorCode.SURVEY_INVALID_RESPONSES, "No value found for 'surveys' parameter or multiple surveys parameters were found."); } else { LOGGER.debug(new String(surveyDataBytes)); try { tJsonData = CampaignValidators.validateUploadedJson(new String(surveyDataBytes, "UTF-8")); } catch (IllegalArgumentException e) { throw new ValidationException(ErrorCode.SURVEY_INVALID_RESPONSES, "The survey responses could not be URL decoded.", e); } } tImageContentsMap = new HashMap<UUID, Image>(); t = getParameterValues(InputKeys.IMAGES); if (t.length > 1) { throw new ValidationException(ErrorCode.SURVEY_INVALID_IMAGES_VALUE, "Multiple images parameters were given: " + InputKeys.IMAGES); } else if (t.length == 1) { LOGGER.debug("Validating the BASE64-encoded images."); Map<UUID, Image> images = SurveyResponseValidators.validateImages(t[0]); if (images != null) { tImageContentsMap.putAll(images); } } // Retrieve and validate images and videos. List<UUID> imageIds = new ArrayList<UUID>(); tVideoContentsMap = new HashMap<String, Video>(); tAudioContentsMap = new HashMap<String, Audio>(); Collection<Part> parts = null; try { // FIXME - push to base class especially because of the ServletException that gets thrown parts = httpRequest.getParts(); for (Part p : parts) { UUID id; String name = p.getName(); try { id = UUID.fromString(name); } catch (IllegalArgumentException e) { LOGGER.info("Ignoring part: " + name); continue; } String contentType = p.getContentType(); if (contentType.startsWith("image")) { imageIds.add(id); } else if (contentType.startsWith("video/")) { tVideoContentsMap.put(name, new Video(UUID.fromString(name), contentType.split("/")[1], getMultipartValue(httpRequest, name))); } else if (contentType.startsWith("audio/")) { try { tAudioContentsMap.put(name, new Audio(UUID.fromString(name), contentType.split("/")[1], getMultipartValue(httpRequest, name))); } catch (DomainException e) { throw new ValidationException(ErrorCode.SYSTEM_GENERAL_ERROR, "Could not create the Audio object.", e); } } } } catch (ServletException e) { LOGGER.info("This is not a multipart/form-post."); } catch (IOException e) { LOGGER.error("cannot parse parts", e); throw new ValidationException(e); } catch (DomainException e) { LOGGER.info("A Media object could not be built.", e); throw new ValidationException(e); } Set<UUID> stringSet = new HashSet<UUID>(imageIds); if (stringSet.size() != imageIds.size()) { throw new ValidationException(ErrorCode.IMAGE_INVALID_DATA, "a duplicate image key was detected in the multi-part upload"); } for (UUID imageId : imageIds) { Image image = ImageValidators.validateImageContents(imageId, getMultipartValue(httpRequest, imageId.toString())); if (image == null) { throw new ValidationException(ErrorCode.IMAGE_INVALID_DATA, "The image data is missing: " + imageId); } tImageContentsMap.put(imageId, image); if (LOGGER.isDebugEnabled()) { LOGGER.debug("succesfully created a BufferedImage for key " + imageId); } } } catch (ValidationException e) { e.failRequest(this); e.logException(LOGGER, true); } } this.campaignUrn = tCampaignUrn; this.campaignCreationTimestamp = tCampaignCreationTimestamp; this.jsonData = tJsonData; this.imageContentsMap = tImageContentsMap; this.videoContentsMap = tVideoContentsMap; this.audioContentsMap = tAudioContentsMap; this.owner = null; surveyResponseIds = null; }
From source file:com.contact.ContactController.java
@RequestMapping(method = RequestMethod.POST) public String create(@Valid Contact contact, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes, Locale locale, @RequestParam(value = "file", required = false) Part file) { logger.info("Creating contact"); if (bindingResult.hasErrors()) { uiModel.addAttribute("message", new Message("error", messageSource.getMessage("contact_save_fail", new Object[] {}, locale))); uiModel.addAttribute("contact", contact); return "contacts/create"; }//from w w w.j a va 2 s .c o m uiModel.asMap().clear(); redirectAttributes.addFlashAttribute("message", new Message("success", messageSource.getMessage("contact_save_success", new Object[] {}, locale))); logger.info("Contact id: " + contact.getId()); // Process upload file if (file != null) { logger.info("File name: " + file.getName()); logger.info("File size: " + file.getSize()); logger.info("File content type: " + file.getContentType()); byte[] fileContent = null; try { InputStream inputStream = file.getInputStream(); if (inputStream == null) logger.info("File inputstream is null"); fileContent = IOUtils.toByteArray(inputStream); contact.setPhoto(fileContent); } catch (IOException ex) { logger.error("Error saving uploaded file"); } contact.setPhoto(fileContent); } contactService.save(contact); return "redirect:/contacts/"; }
From source file:org.codice.ddf.rest.impl.CatalogServiceImplTest.java
private Part createPart(String name, InputStream inputStream, String contentDisposition) throws IOException { Part part = mock(Part.class); when(part.getName()).thenReturn(name); when(part.getInputStream()).thenReturn(inputStream); when(part.getHeader("Content-Disposition")).thenReturn(contentDisposition); when(part.getContentType()).thenReturn(MediaType.APPLICATION_OCTET_STREAM); return part;/*from w w w . j a v a 2 s .c o m*/ }
From source file:ips1ap101.lib.core.jsf.JSF.java
public static void validateInputFile(Part file, String label, long maxSize, String[] validTypes) { long size;//from w w w . jav a 2 s .c o m String type; String summary; FacesMessage message; List<FacesMessage> messages = new ArrayList<>(); size = file.getSize(); type = file.getContentType(); if (size < INPUT_FILE_MIN_SIZE) { summary = Bitacora.getTextoMensaje(CBM.UPLOAD_ROW_EXCEPTION_1, label, INPUT_FILE_MIN_SIZE); message = new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, null); messages.add(message); } if (size > maxSize) { summary = Bitacora.getTextoMensaje(CBM.UPLOAD_ROW_EXCEPTION_2, label, maxSize); message = new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, null); messages.add(message); } if (validTypes != null && validTypes.length > 0) { if (StringUtils.startsWithAny(type, validTypes)) { } else { summary = Bitacora.getTextoMensaje(CBM.UPLOAD_ROW_EXCEPTION_3, label, type); message = new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, null); messages.add(message); } } if (messages.isEmpty()) { } else { throw new ValidatorException(messages); } }
From source file:org.codice.ddf.rest.impl.CatalogServiceImpl.java
private Metacard parseMetacard(String transformerParam, Metacard metacard, Part part, InputStream inputStream) { String transformer = "xml"; if (transformerParam != null) { transformer = transformerParam;/*from www.jav a2 s. c o m*/ } try { MimeType mimeType = new MimeType(part.getContentType()); metacard = generateMetacard(mimeType, null, inputStream, transformer); } catch (MimeTypeParseException | MetacardCreationException e) { LOGGER.debug("Unable to parse metadata {}", part.getContentType()); } return metacard; }
From source file:org.codice.ddf.rest.impl.CatalogServiceImpl.java
@Override public BinaryContent createMetacard(HttpServletRequest httpServletRequest, String transformerParam) throws CatalogServiceException { LOGGER.trace("ENTERING: createMetacard"); InputStream stream = null;/*from w w w . ja v a 2s.c o m*/ String contentType = null; try { Part contentPart = httpServletRequest.getPart(FILE_ATTACHMENT_CONTENT_ID); if (contentPart != null) { // Example Content-Type header: // Content-Type: application/json;id=geojson if (contentPart.getContentType() != null) { contentType = contentPart.getContentType(); } // Get the file contents as an InputStream and ensure the stream is positioned // at the beginning try { stream = contentPart.getInputStream(); if (stream != null && stream.available() == 0) { stream.reset(); } } catch (IOException e) { LOGGER.info("IOException reading stream from file attachment in multipart body", e); } } else { LOGGER.debug(NO_FILE_CONTENTS_ATT_FOUND); } } catch (ServletException | IOException e) { LOGGER.info("No file contents part found: ", e); } return createMetacard(stream, contentType, transformerParam); }
From source file:com.spring.tutorial.entitites.FileUploader.java
public String upload() throws IOException, ServletException, FacebookException { OutputStream output = null;//from w ww .jav a 2s . com InputStream fileContent = null; final Part filePart; final File file; try { filePart = request.getPart("file"); fileContent = filePart.getInputStream(); MongoClient mongoClient = new MongoClient(); mongoClient = new MongoClient(); DB db = mongoClient.getDB("fou"); char[] pass = "mongo".toCharArray(); boolean auth = db.authenticate("admin", pass); file = File.createTempFile("fileToStore", "tmp"); file.deleteOnExit(); FileOutputStream fout = new FileOutputStream(file); int read = 0; byte[] bytes = new byte[1024]; while ((read = fileContent.read(bytes)) != -1) { fout.write(bytes, 0, read); } GridFS gridFS = new GridFS(db, request.getSession().getAttribute("id") + "_files"); GridFSInputFile gfsInputFile = gridFS.createFile(file); gfsInputFile.setFilename(filePart.getSubmittedFileName()); gfsInputFile.save(); DBCollection collection = db.getCollection(request.getSession().getAttribute("id") + "_files_meta"); BasicDBObject metaDocument = new BasicDBObject(); metaDocument.append("name", filePart.getSubmittedFileName()); metaDocument.append("size", filePart.getSize()); metaDocument.append("content-type", filePart.getContentType()); metaDocument.append("file-id", gfsInputFile.getId()); metaDocument.append("tags", request.getParameter("tags")); metaDocument.append("description", request.getParameter("description")); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); metaDocument.append("last_modified", dateFormat.format(new Date())); collection.insert(metaDocument); } catch (Exception e) { return "message:" + e.getMessage(); } finally { if (output != null) { output.close(); } if (fileContent != null) { fileContent.close(); } } return "success"; }