List of usage examples for org.apache.commons.fileupload FileItemStream openStream
InputStream openStream() throws IOException;
From source file:ca.nrc.cadc.beacon.web.resources.FileItemServerResource.java
/** * Perform the actual upload.//from w w w .ja va2 s. c o m * * @param fileItemStream The upload file item stream. * @return The URI to the new node. * @throws IOException If anything goes wrong. */ VOSURI upload(final FileItemStream fileItemStream) throws IOException, IllegalArgumentException, NodeAlreadyExistsException { final String filename = fileItemStream.getName(); if (fileValidator.validateString(filename)) { final String path = getCurrentItemURI().getPath() + "/" + URLEncoder.encode(filename, "UTF-8"); final DataNode dataNode = new DataNode(toURI(path)); // WebRT 19564: Add content type to the response of // uploaded items. final List<NodeProperty> properties = new ArrayList<>(); properties.add(new NodeProperty(VOS.PROPERTY_URI_TYPE, fileItemStream.getContentType())); properties.add(new NodeProperty(VOS.PROPERTY_URI_CONTENTLENGTH, Long.toString(getRequest().getEntity().getSize()))); dataNode.setProperties(properties); try (final InputStream inputStream = fileItemStream.openStream()) { upload(inputStream, dataNode); } return dataNode.getUri(); } else { throw new IllegalArgumentException("Name is required and cannot contain characters \n" + "outside of alphanumeric and _-()=+!,;:@&*$."); } }
From source file:com.exilant.exility.core.HtmlRequestHandler.java
/** * /* w w w . ja va2s. c o m*/ * @param req * @param formIsSubmitted * @param hasSerializedDc * @param outData * @return service data that contains all input fields * @throws ExilityException */ public ServiceData createInDataForStream(HttpServletRequest req, boolean formIsSubmitted, boolean hasSerializedDc, ServiceData outData) throws ExilityException { ServiceData inData = new ServiceData(); /** * this method is structured to handle simpler cases in the beginning if * form is not submitted, it has to be serialized data */ if (formIsSubmitted == false) { this.extractSerializedData(req, hasSerializedDc, inData); return inData; } if (hasSerializedDc == false) { this.extractParametersAndFiles(req, inData); return inData; } // it is a form submit with serialized DC in it HttpSession session = req.getSession(); try { if (ServletFileUpload.isMultipartContent(req) == false) { String txt = session.getAttribute("dc").toString(); this.extractSerializedDc(txt, inData); this.extractFilesToDc(req, inData); return inData; } // complex case of file upload etc.. ServletFileUpload fileUploader = new ServletFileUpload(); fileUploader.setHeaderEncoding("UTF-8"); FileItemIterator iterator = fileUploader.getItemIterator(req); while (iterator.hasNext()) { FileItemStream stream = iterator.next(); InputStream inStream = null; try { inStream = stream.openStream(); String fieldName = stream.getFieldName(); if (stream.isFormField()) { String fieldValue = Streams.asString(inStream); if (fieldName.equals("dc")) { this.extractSerializedDc(fieldValue, inData); } else { inData.addValue(fieldName, fieldValue); } } else { String fileContents = IOUtils.toString(inStream); inData.addValue(fieldName + HtmlRequestHandler.PATH_SUFFIX, fileContents); } inStream.close(); } finally { IOUtils.closeQuietly(inStream); } } @SuppressWarnings("rawtypes") Enumeration e = req.getSession().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); } } catch (Exception ioEx) { // nothing to do here } return inData; }
From source file:echopoint.tucana.JakartaCommonsFileUploadProvider.java
/** * @see UploadSPI#handleUpload(nextapp.echo.webcontainer.Connection , * FileUploadSelector, String, UploadProgress) *//* ww w . j a v a 2 s .c o m*/ @SuppressWarnings({ "ThrowableInstanceNeverThrown" }) public void handleUpload(final Connection conn, final FileUploadSelector uploadSelect, final String uploadIndex, final UploadProgress progress) throws Exception { final ApplicationInstance app = conn.getUserInstance().getApplicationInstance(); final DiskFileItemFactory itemFactory = new DiskFileItemFactory(); itemFactory.setRepository(getDiskCacheLocation()); itemFactory.setSizeThreshold(getMemoryCacheThreshold()); String encoding = conn.getRequest().getCharacterEncoding(); if (encoding == null) { encoding = "UTF-8"; } final ServletFileUpload upload = new ServletFileUpload(itemFactory); upload.setHeaderEncoding(encoding); upload.setProgressListener(new UploadProgressListener(progress)); long sizeLimit = uploadSelect.getUploadSizeLimit(); if (sizeLimit == 0) sizeLimit = getFileUploadSizeLimit(); if (sizeLimit != NO_SIZE_LIMIT) { upload.setSizeMax(sizeLimit); } String fileName = null; String contentType = null; try { final FileItemIterator iter = upload.getItemIterator(conn.getRequest()); if (iter.hasNext()) { final FileItemStream stream = iter.next(); if (!stream.isFormField()) { fileName = FilenameUtils.getName(stream.getName()); contentType = stream.getContentType(); final Set<String> types = uploadSelect.getContentTypeFilter(); if (!types.isEmpty()) { if (!types.contains(contentType)) { app.enqueueTask(uploadSelect.getTaskQueue(), new InvalidContentTypeRunnable( uploadSelect, uploadIndex, fileName, contentType, progress)); return; } } progress.setStatus(Status.inprogress); final FileItem item = itemFactory.createItem(fileName, contentType, false, stream.getName()); item.getOutputStream(); // initialise DiskFileItem internals uploadSelect.notifyCallback( new UploadStartEvent(uploadSelect, uploadIndex, fileName, contentType, item.getSize())); IOUtils.copy(stream.openStream(), item.getOutputStream()); app.enqueueTask(uploadSelect.getTaskQueue(), new FinishRunnable(uploadSelect, uploadIndex, fileName, item, progress)); return; } } app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName, contentType, new RuntimeException("No multi-part content!"), progress)); } catch (final FileUploadBase.SizeLimitExceededException e) { app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName, contentType, new UploadSizeLimitExceededException(e), progress)); } catch (final FileUploadBase.FileSizeLimitExceededException e) { app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName, contentType, new UploadSizeLimitExceededException(e), progress)); } catch (final MultipartStream.MalformedStreamException e) { app.enqueueTask(uploadSelect.getTaskQueue(), new CancelRunnable(uploadSelect, uploadIndex, fileName, contentType, e, progress)); } }
From source file:com.exilant.exility.core.HtmlRequestHandler.java
/** * Extract data from request object (form, data and session) * // w w w . ja v a 2 s .c om * @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.kurento.kmf.repository.internal.http.RepositoryHttpServlet.java
private void uploadMultipart(HttpServletRequest req, HttpServletResponse resp, OutputStream repoItemOutputStrem) throws IOException { log.info("Multipart detected"); ServletFileUpload upload = new ServletFileUpload(); try {// w w w.j a v a2 s.co m // Parse the request FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); try (InputStream stream = item.openStream()) { if (item.isFormField()) { // TODO What to do with this? log.info("Form field {} with value {} detected.", name, Streams.asString(stream)); } else { // TODO Must we support multiple files uploading? log.info("File field {} with file name detected.", name, item.getName()); log.info("Start to receive bytes (estimated bytes)", Integer.toString(req.getContentLength())); int bytes = IOUtils.copy(stream, repoItemOutputStrem); resp.setStatus(SC_OK); log.info("Bytes received: {}", Integer.toString(bytes)); } } } } catch (FileUploadException e) { throw new IOException(e); } }
From source file:com.liferay.faces.metal.component.inputfile.internal.InputFileDecoderCommonsImpl.java
@Override public Map<String, List<UploadedFile>> decode(FacesContext facesContext, String location) { Map<String, List<UploadedFile>> uploadedFileMap = null; ExternalContext externalContext = facesContext.getExternalContext(); String uploadedFilesFolder = getUploadedFilesFolder(externalContext, location); // Using the sessionId, determine a unique folder path and create the path if it does not exist. String sessionId = getSessionId(externalContext); // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be // created properly. sessionId = sessionId.replaceAll("[^A-Za-z0-9]", " "); File uploadedFilesPath = new File(uploadedFilesFolder, sessionId); if (!uploadedFilesPath.exists()) { uploadedFilesPath.mkdirs();//from w w w . ja v a 2 s. co m } // Initialize commons-fileupload with the file upload path. DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(uploadedFilesPath); // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted. diskFileItemFactory.setFileCleaningTracker(null); // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk // instead of staying in memory. diskFileItemFactory.setSizeThreshold(0); // Determine the max file upload size threshold (in bytes). int uploadedFileMaxSize = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext); // Parse the request parameters and save all uploaded files in a map. ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); servletFileUpload.setFileSizeMax(uploadedFileMaxSize); uploadedFileMap = new HashMap<String, List<UploadedFile>>(); UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder .getFactory(UploadedFileFactory.class); // Begin parsing the request for file parts: try { FileItemIterator fileItemIterator = null; HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest(); fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest); if (fileItemIterator != null) { int totalFiles = 0; // For each field found in the request: while (fileItemIterator.hasNext()) { try { totalFiles++; // Get the stream of field data from the request. FileItemStream fieldStream = (FileItemStream) fileItemIterator.next(); // Get field name from the field stream. String fieldName = fieldStream.getFieldName(); // Get the content-type, and file-name from the field stream. String contentType = fieldStream.getContentType(); boolean formField = fieldStream.isFormField(); String fileName = null; try { fileName = fieldStream.getName(); } catch (InvalidFileNameException e) { fileName = e.getName(); } // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the // current field is a simple form-field because the call below to diskFileItem.getString() // will fail otherwise. DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName, contentType, formField, fileName); Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true); // If the current field is a file, then if (!diskFileItem.isFormField()) { // Get the location of the temporary file that was copied from the request. File tempFile = diskFileItem.getStoreLocation(); // If the copy was successful, then if (tempFile.exists()) { // Copy the commons-fileupload temporary file to a file in the same temporary // location, but with the filename provided by the user in the upload. This has two // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying // the file, the developer can have access to a semi-permanent file, because the // commmons-fileupload DiskFileItem.finalize() method automatically deletes the // temporary one. String tempFileName = tempFile.getName(); String tempFileAbsolutePath = tempFile.getAbsolutePath(); String copiedFileName = stripIllegalCharacters(fileName); String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName, copiedFileName); File copiedFile = new File(copiedFileAbsolutePath); FileUtils.copyFile(tempFile, copiedFile); // If present, build up a map of headers. Map<String, List<String>> headersMap = new HashMap<String, List<String>>(); FileItemHeaders fileItemHeaders = fieldStream.getHeaders(); if (fileItemHeaders != null) { Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames(); if (headerNameItr != null) { while (headerNameItr.hasNext()) { String headerName = headerNameItr.next(); Iterator<String> headerValuesItr = fileItemHeaders .getHeaders(headerName); List<String> headerValues = new ArrayList<String>(); if (headerValuesItr != null) { while (headerValuesItr.hasNext()) { String headerValue = headerValuesItr.next(); headerValues.add(headerValue); } } headersMap.put(headerName, headerValues); } } } // Put a valid UploadedFile instance into the map that contains all of the // uploaded file's attributes, along with a successful status. Map<String, Object> attributeMap = new HashMap<String, Object>(); String id = Long.toString(((long) hashCode()) + System.currentTimeMillis()); String message = null; UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile( copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(), diskFileItem.getContentType(), headersMap, id, message, fileName, diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName, fileName); } else { if ((fileName != null) && (fileName.trim().length() > 0)) { Exception e = new IOException("Failed to copy the stream of uploaded file=[" + fileName + "] to a temporary file (possibly a zero-length uploaded file)"); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); String fieldName = Integer.toString(totalFiles); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in // the map so that the developer can have some idea that something went wrong. catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, "unknown", uploadedFile); } return uploadedFileMap; }
From source file:com.liferay.faces.alloy.component.inputfile.internal.InputFileDecoderCommonsImpl.java
@Override public Map<String, List<UploadedFile>> decode(FacesContext facesContext, String location) { Map<String, List<UploadedFile>> uploadedFileMap = null; ExternalContext externalContext = facesContext.getExternalContext(); String uploadedFilesFolder = getUploadedFilesFolder(externalContext, location); // Using the sessionId, determine a unique folder path and create the path if it does not exist. String sessionId = getSessionId(externalContext); // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be // created properly. sessionId = sessionId.replaceAll("[^A-Za-z0-9]", " "); File uploadedFilesPath = new File(uploadedFilesFolder, sessionId); if (!uploadedFilesPath.exists()) { uploadedFilesPath.mkdirs();/*from w w w. ja v a 2 s . c o m*/ } // Initialize commons-fileupload with the file upload path. DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(uploadedFilesPath); // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted. diskFileItemFactory.setFileCleaningTracker(null); // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk // instead of staying in memory. diskFileItemFactory.setSizeThreshold(0); // Determine the max file upload size threshold (in bytes). int uploadedFileMaxSize = WebConfigParam.UploadedFileMaxSize.getIntegerValue(externalContext); // Parse the request parameters and save all uploaded files in a map. ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); servletFileUpload.setFileSizeMax(uploadedFileMaxSize); uploadedFileMap = new HashMap<String, List<UploadedFile>>(); UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder .getFactory(externalContext, UploadedFileFactory.class); // Begin parsing the request for file parts: try { FileItemIterator fileItemIterator = null; HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest(); fileItemIterator = servletFileUpload.getItemIterator(httpServletRequest); if (fileItemIterator != null) { int totalFiles = 0; // For each field found in the request: while (fileItemIterator.hasNext()) { try { totalFiles++; // Get the stream of field data from the request. FileItemStream fieldStream = (FileItemStream) fileItemIterator.next(); // Get field name from the field stream. String fieldName = fieldStream.getFieldName(); // Get the content-type, and file-name from the field stream. String contentType = fieldStream.getContentType(); boolean formField = fieldStream.isFormField(); String fileName = null; try { fileName = fieldStream.getName(); } catch (InvalidFileNameException e) { fileName = e.getName(); } // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the // current field is a simple form-field because the call below to diskFileItem.getString() // will fail otherwise. DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName, contentType, formField, fileName); Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true); // If the current field is a file, then if (!diskFileItem.isFormField()) { // Get the location of the temporary file that was copied from the request. File tempFile = diskFileItem.getStoreLocation(); // If the copy was successful, then if (tempFile.exists()) { // Copy the commons-fileupload temporary file to a file in the same temporary // location, but with the filename provided by the user in the upload. This has two // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying // the file, the developer can have access to a semi-permanent file, because the // commmons-fileupload DiskFileItem.finalize() method automatically deletes the // temporary one. String tempFileName = tempFile.getName(); String tempFileAbsolutePath = tempFile.getAbsolutePath(); String copiedFileName = stripIllegalCharacters(fileName); String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName, copiedFileName); File copiedFile = new File(copiedFileAbsolutePath); FileUtils.copyFile(tempFile, copiedFile); // If present, build up a map of headers. Map<String, List<String>> headersMap = new HashMap<String, List<String>>(); FileItemHeaders fileItemHeaders = fieldStream.getHeaders(); if (fileItemHeaders != null) { Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames(); if (headerNameItr != null) { while (headerNameItr.hasNext()) { String headerName = headerNameItr.next(); Iterator<String> headerValuesItr = fileItemHeaders .getHeaders(headerName); List<String> headerValues = new ArrayList<String>(); if (headerValuesItr != null) { while (headerValuesItr.hasNext()) { String headerValue = headerValuesItr.next(); headerValues.add(headerValue); } } headersMap.put(headerName, headerValues); } } } // Put a valid UploadedFile instance into the map that contains all of the // uploaded file's attributes, along with a successful status. Map<String, Object> attributeMap = new HashMap<String, Object>(); String id = Long.toString(((long) hashCode()) + System.currentTimeMillis()); String message = null; UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile( copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(), diskFileItem.getContentType(), headersMap, id, message, fileName, diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName, fileName); } else { if ((fileName != null) && (fileName.trim().length() > 0)) { Exception e = new IOException("Failed to copy the stream of uploaded file=[" + fileName + "] to a temporary file (possibly a zero-length uploaded file)"); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); String fieldName = Integer.toString(totalFiles); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in // the map so that the developer can have some idea that something went wrong. catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, "unknown", uploadedFile); } return uploadedFileMap; }
From source file:ch.entwine.weblounge.contentrepository.impl.endpoint.FilesEndpoint.java
/** * Adds the resource content with language <code>language</code> to the * specified resource./* w w w .ja v a 2 s . co m*/ * * @param request * the request * @param resourceId * the resource identifier * @param languageId * the language identifier * @param is * the input stream * @return the resource */ @POST @Path("/{resource}/content/{language}") @Produces(MediaType.MEDIA_TYPE_WILDCARD) public Response addFileContent(@Context HttpServletRequest request, @PathParam("resource") String resourceId, @PathParam("language") String languageId) { Site site = getSite(request); // Check the parameters if (resourceId == null) throw new WebApplicationException(Status.BAD_REQUEST); // Extract the language Language language = LanguageUtils.getLanguage(languageId); if (language == null) { throw new WebApplicationException(Status.NOT_FOUND); } // Get the resource Resource<?> resource = loadResource(request, resourceId, null); if (resource == null || resource.contents().isEmpty()) { throw new WebApplicationException(Status.NOT_FOUND); } String fileName = null; String mimeType = null; File uploadedFile = null; try { // Multipart form encoding? if (ServletFileUpload.isMultipartContent(request)) { try { ServletFileUpload payload = new ServletFileUpload(); for (FileItemIterator iter = payload.getItemIterator(request); iter.hasNext();) { FileItemStream item = iter.next(); if (item.isFormField()) { String fieldName = item.getFieldName(); String fieldValue = Streams.asString(item.openStream()); if (StringUtils.isBlank(fieldValue)) continue; if (OPT_MIMETYPE.equals(fieldName)) { mimeType = fieldValue; } } else { // once the body gets read iter.hasNext must not be invoked // or the stream can not be read fileName = StringUtils.trim(item.getName()); mimeType = StringUtils.trim(item.getContentType()); uploadedFile = File.createTempFile("upload-", null); FileOutputStream fos = new FileOutputStream(uploadedFile); try { IOUtils.copy(item.openStream(), fos); } catch (IOException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(fos); } } } } catch (FileUploadException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (IOException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } } // Octet binary stream else { try { fileName = StringUtils.trimToNull(request.getHeader("X-File-Name")); mimeType = StringUtils.trimToNull(request.getParameter(OPT_MIMETYPE)); } catch (UnknownLanguageException e) { throw new WebApplicationException(Status.BAD_REQUEST); } InputStream is = null; FileOutputStream fos = null; try { is = request.getInputStream(); if (is == null) throw new WebApplicationException(Status.BAD_REQUEST); uploadedFile = File.createTempFile("upload-", null); fos = new FileOutputStream(uploadedFile); IOUtils.copy(is, fos); } catch (IOException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } // Has there been a file in the request? if (uploadedFile == null) throw new WebApplicationException(Status.BAD_REQUEST); // A mime type would be nice as well if (StringUtils.isBlank(mimeType)) { mimeType = detectMimeTypeFromFile(fileName, uploadedFile); if (mimeType == null) throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } // Get the current user User user = securityService.getUser(); if (user == null) throw new WebApplicationException(Status.UNAUTHORIZED); // Make sure the user has editing rights if (!SecurityUtils.userHasRole(user, SystemRole.EDITOR)) throw new WebApplicationException(Status.UNAUTHORIZED); // Try to create the resource content InputStream is = null; ResourceContent content = null; ResourceContentReader<?> reader = null; ResourceSerializer<?, ?> serializer = serializerService .getSerializerByType(resource.getURI().getType()); try { reader = serializer.getContentReader(); is = new FileInputStream(uploadedFile); content = reader.createFromContent(is, user, language, uploadedFile.length(), fileName, mimeType); } catch (IOException e) { logger.warn("Error reading resource content {} from request", resource.getURI()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (ParserConfigurationException e) { logger.warn("Error configuring parser to read resource content {}: {}", resource.getURI(), e.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (SAXException e) { logger.warn("Error parsing udpated resource {}: {}", resource.getURI(), e.getMessage()); throw new WebApplicationException(Status.BAD_REQUEST); } finally { IOUtils.closeQuietly(is); } URI uri = null; WritableContentRepository contentRepository = (WritableContentRepository) getContentRepository(site, true); try { is = new FileInputStream(uploadedFile); resource = contentRepository.putContent(resource.getURI(), content, is); uri = new URI(resource.getURI().getIdentifier()); } catch (IOException e) { logger.warn("Error writing content to resource {}: {}", resource.getURI(), e.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (IllegalStateException e) { logger.warn("Illegal state while adding content to resource {}: {}", resource.getURI(), e.getMessage()); throw new WebApplicationException(Status.PRECONDITION_FAILED); } catch (ContentRepositoryException e) { logger.warn("Error adding content to resource {}: {}", resource.getURI(), e.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (URISyntaxException e) { logger.warn("Error creating a uri for resource {}: {}", resource.getURI(), e.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(is); } // Create the response ResponseBuilder response = Response.created(uri); response.type(MediaType.MEDIA_TYPE_WILDCARD); response.tag(ResourceUtils.getETagValue(resource)); response.lastModified(ResourceUtils.getModificationDate(resource, language)); return response.build(); } finally { FileUtils.deleteQuietly(uploadedFile); } }
From source file:com.glaf.core.web.servlet.FileUploadServlet.java
public void upload(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/html;charset=UTF-8"); LoginContext loginContext = RequestUtils.getLoginContext(request); if (loginContext == null) { return;//from ww w .j a v a2 s .co m } String serviceKey = request.getParameter("serviceKey"); String type = request.getParameter("type"); if (StringUtils.isEmpty(type)) { type = "0"; } Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug("paramMap:" + paramMap); String rootDir = SystemProperties.getConfigRootPath(); InputStream inputStream = null; try { DiskFileItemFactory diskFactory = new DiskFileItemFactory(); // threshold ???? 8M diskFactory.setSizeThreshold(8 * FileUtils.MB_SIZE); // repository diskFactory.setRepository(new File(rootDir + "/temp")); ServletFileUpload upload = new ServletFileUpload(diskFactory); int maxUploadSize = conf.getInt(serviceKey + ".maxUploadSize", 0); if (maxUploadSize == 0) { maxUploadSize = conf.getInt("upload.maxUploadSize", 50);// 50MB } maxUploadSize = maxUploadSize * FileUtils.MB_SIZE; logger.debug("maxUploadSize:" + maxUploadSize); upload.setHeaderEncoding("UTF-8"); upload.setSizeMax(maxUploadSize); upload.setFileSizeMax(maxUploadSize); String uploadDir = Constants.UPLOAD_PATH; if (ServletFileUpload.isMultipartContent(request)) { logger.debug("#################start upload process#########################"); FileItemIterator iter = upload.getItemIterator(request); PrintWriter out = response.getWriter(); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { // ???? String autoCreatedDateDirByParttern = "yyyy/MM/dd"; String autoCreatedDateDir = DateFormatUtils.format(new java.util.Date(), autoCreatedDateDirByParttern); File savePath = new File(rootDir + uploadDir + autoCreatedDateDir); if (!savePath.exists()) { savePath.mkdirs(); } String fileId = UUID32.getUUID(); String fileName = savePath + "/" + fileId; BlobItem dataFile = new BlobItemEntity(); dataFile.setLastModified(System.currentTimeMillis()); dataFile.setCreateBy(loginContext.getActorId()); dataFile.setFileId(fileId); dataFile.setPath(uploadDir + autoCreatedDateDir + "/" + fileId); dataFile.setFilename(item.getName()); dataFile.setName(item.getName()); dataFile.setContentType(item.getContentType()); dataFile.setType(type); dataFile.setStatus(0); dataFile.setServiceKey(serviceKey); getBlobService().insertBlob(dataFile); inputStream = item.openStream(); FileUtils.save(fileName, inputStream); logger.debug(fileName + " save ok."); out.print(fileId); } } } } catch (Exception ex) { ex.printStackTrace(); } finally { IOUtils.close(inputStream); } }
From source file:ch.entwine.weblounge.contentrepository.impl.endpoint.FilesEndpoint.java
/** * Creates a file resource at the site's content repository by uploading * initial file content and returns the location to post updates to. * /* w ww . j a va2 s .co m*/ * @param request * the http request * @param resourceXml * the new resource * @param path * the path to store the resource at * @param mimeType * the content mime type * @return response the resource location */ @POST @Path("/uploads") @Produces(MediaType.MEDIA_TYPE_WILDCARD) public Response uploadFile(@Context HttpServletRequest request) { Site site = getSite(request); // Make sure the content repository is writable if (site.getContentRepository().isReadOnly()) { logger.warn("Attempt to write to read-only content repository {}", site); throw new WebApplicationException(Status.PRECONDITION_FAILED); } String fileName = null; Language language = null; String path = null; String mimeType = null; File uploadedFile = null; try { // Multipart form encoding? if (ServletFileUpload.isMultipartContent(request)) { try { ServletFileUpload payload = new ServletFileUpload(); for (FileItemIterator iter = payload.getItemIterator(request); iter.hasNext();) { FileItemStream item = iter.next(); String fieldName = item.getFieldName(); if (item.isFormField()) { String fieldValue = Streams.asString(item.openStream()); if (StringUtils.isBlank(fieldValue)) continue; if (OPT_PATH.equals(fieldName)) { path = fieldValue; } else if (OPT_LANGUAGE.equals(fieldName)) { try { language = LanguageUtils.getLanguage(fieldValue); } catch (UnknownLanguageException e) { throw new WebApplicationException(Status.BAD_REQUEST); } } else if (OPT_MIMETYPE.equals(fieldName)) { mimeType = fieldValue; } } else { // once the body gets read iter.hasNext must not be invoked // or the stream can not be read fileName = StringUtils.trim(item.getName()); mimeType = StringUtils.trim(item.getContentType()); uploadedFile = File.createTempFile("upload-", null); FileOutputStream fos = new FileOutputStream(uploadedFile); try { IOUtils.copy(item.openStream(), fos); } catch (IOException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(fos); } } } } catch (FileUploadException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (IOException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } } // Octet binary stream else { try { fileName = StringUtils.trimToNull(request.getHeader("X-File-Name")); path = StringUtils.trimToNull(request.getParameter(OPT_PATH)); mimeType = StringUtils.trimToNull(request.getParameter(OPT_MIMETYPE)); language = LanguageUtils.getLanguage(request.getParameter(OPT_LANGUAGE)); } catch (UnknownLanguageException e) { throw new WebApplicationException(Status.BAD_REQUEST); } InputStream is = null; FileOutputStream fos = null; try { is = request.getInputStream(); if (is == null) throw new WebApplicationException(Status.BAD_REQUEST); uploadedFile = File.createTempFile("upload-", null); fos = new FileOutputStream(uploadedFile); IOUtils.copy(is, fos); } catch (IOException e) { throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } // Has there been a file in the request? if (uploadedFile == null) throw new WebApplicationException(Status.BAD_REQUEST); // Check the filename if (fileName == null) { logger.warn("No filename found for upload, request header 'X-File-Name' not specified"); fileName = uploadedFile.getName(); } // Make sure there is a language if (language == null) { language = LanguageUtils.getPreferredLanguage(request, site); } // A mime type would be nice as well if (StringUtils.isBlank(mimeType)) { mimeType = detectMimeTypeFromFile(fileName, uploadedFile); if (mimeType == null) throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } // Set owner and date created User user = securityService.getUser(); if (user == null) throw new WebApplicationException(Status.UNAUTHORIZED); // Make sure the user has editing rights if (!SecurityUtils.userHasRole(user, SystemRole.EDITOR)) throw new WebApplicationException(Status.UNAUTHORIZED); WritableContentRepository contentRepository = (WritableContentRepository) getContentRepository(site, true); // Create the resource uri URI uri = null; InputStream is = null; Resource<?> resource = null; ResourceURI resourceURI = null; logger.debug("Adding resource to {}", resourceURI); ResourceSerializer<?, ?> serializer = serializerService.getSerializerByMimeType(mimeType); if (serializer == null) { logger.debug("No specialized resource serializer found, using regular file serializer"); serializer = serializerService.getSerializerByType(FileResource.TYPE); } // Create the resource try { is = new FileInputStream(uploadedFile); resource = serializer.newResource(site, is, user, language); resourceURI = resource.getURI(); } catch (FileNotFoundException e) { logger.warn("Error creating resource at {} from image: {}", uri, e.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(is); } // If a path has been specified, set it if (path != null && StringUtils.isNotBlank(path)) { try { if (!path.startsWith("/")) path = "/" + path; WebUrl url = new WebUrlImpl(site, path); resourceURI.setPath(url.getPath()); // Make sure the resource doesn't exist if (contentRepository.exists(new GeneralResourceURIImpl(site, url.getPath()))) { logger.warn("Tried to create already existing resource {} in site '{}'", resourceURI, site); throw new WebApplicationException(Status.CONFLICT); } } catch (IllegalArgumentException e) { logger.warn("Tried to create a resource with an invalid path '{}': {}", path, e.getMessage()); throw new WebApplicationException(Status.BAD_REQUEST); } catch (ContentRepositoryException e) { logger.warn("Resource lookup {} failed for site '{}'", resourceURI, site); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } } // Store the new resource try { uri = new URI(resourceURI.getIdentifier()); contentRepository.put(resource, true); } catch (URISyntaxException e) { logger.warn("Error creating a uri for resource {}: {}", resourceURI, e.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (IOException e) { logger.warn("Error writing new resource {}: {}", resourceURI, e.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (IllegalStateException e) { logger.warn("Illegal state while adding new resource {}: {}", resourceURI, e.getMessage()); throw new WebApplicationException(Status.PRECONDITION_FAILED); } catch (ContentRepositoryException e) { logger.warn("Error adding new resource {}: {}", resourceURI, e.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } ResourceContent content = null; ResourceContentReader<?> reader = null; try { reader = serializer.getContentReader(); is = new FileInputStream(uploadedFile); content = reader.createFromContent(is, user, language, uploadedFile.length(), fileName, mimeType); } catch (IOException e) { logger.warn("Error reading resource content {} from request", uri); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (ParserConfigurationException e) { logger.warn("Error configuring parser to read resource content {}: {}", uri, e.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (SAXException e) { logger.warn("Error parsing udpated resource {}: {}", uri, e.getMessage()); throw new WebApplicationException(Status.BAD_REQUEST); } catch (Throwable t) { logger.warn("Unknown error while trying to read resource content {}: {}", uri, t.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(is); if (content == null) { try { contentRepository.delete(resourceURI); } catch (Throwable t) { logger.error("Error deleting orphan resource {}", resourceURI, t); } } } try { is = new FileInputStream(uploadedFile); resource = contentRepository.putContent(resource.getURI(), content, is); } catch (IOException e) { logger.warn("Error writing content to resource {}: {}", uri, e.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } catch (IllegalStateException e) { logger.warn("Illegal state while adding content to resource {}: {}", uri, e.getMessage()); throw new WebApplicationException(Status.PRECONDITION_FAILED); } catch (ContentRepositoryException e) { logger.warn("Error adding content to resource {}: {}", uri, e.getMessage()); throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(is); } // Create the response ResponseBuilder response = Response.created(uri); response.type(MediaType.MEDIA_TYPE_WILDCARD); response.tag(ResourceUtils.getETagValue(resource)); response.lastModified(ResourceUtils.getModificationDate(resource)); return response.build(); } finally { FileUtils.deleteQuietly(uploadedFile); } }