List of usage examples for org.apache.commons.fileupload FileItemStream getName
String getName();
From source file:com.liferay.faces.bridge.context.map.MultiPartFormDataProcessorImpl.java
@Override public Map<String, Collection<UploadedFile>> process(ClientDataRequest clientDataRequest, PortletConfig portletConfig, FacesRequestParameterMap facesRequestParameterMap) { Map<String, Collection<UploadedFile>> uploadedFileMap = null; PortletSession portletSession = clientDataRequest.getPortletSession(); String uploadedFilesDir = PortletConfigParam.UploadedFilesDir.getStringValue(portletConfig); // Using the portlet sessionId, determine a unique folder path and create the path if it does not exist. String sessionId = portletSession.getId(); // 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]", StringPool.BLANK); File uploadedFilesPath = new File(uploadedFilesDir, sessionId); if (!uploadedFilesPath.exists()) { uploadedFilesPath.mkdirs();/*from ww w . j a v a2 s . c om*/ } // 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 = PortletConfigParam.UploadedFileMaxSize.getIntegerValue(portletConfig); // Parse the request parameters and save all uploaded files in a map. PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory); portletFileUpload.setFileSizeMax(uploadedFileMaxSize); uploadedFileMap = new HashMap<String, Collection<UploadedFile>>(); // FACES-271: Include name+value pairs found in the ActionRequest. Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet(); for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) { String parameterName = mapEntry.getKey(); String[] parameterValues = mapEntry.getValue(); if (parameterValues.length > 0) { for (String parameterValue : parameterValues) { facesRequestParameterMap.addValue(parameterName, parameterValue); } } } UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder .getFactory(UploadedFileFactory.class); // Begin parsing the request for file parts: try { FileItemIterator fileItemIterator = null; if (clientDataRequest instanceof ResourceRequest) { ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest; fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest)); } else { ActionRequest actionRequest = (ActionRequest) clientDataRequest; fileItemIterator = portletFileUpload.getItemIterator(actionRequest); } boolean optimizeNamespace = PortletConfigParam.OptimizePortletNamespace.getBooleanValue(portletConfig); if (fileItemIterator != null) { int totalFiles = 0; String namespace = facesRequestParameterMap.getNamespace(); // 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(); // If namespace optimization is enabled and the namespace is present in the field name, // then remove the portlet namespace from the field name. if (optimizeNamespace) { int pos = fieldName.indexOf(namespace); if (pos >= 0) { fieldName = fieldName.substring(pos + namespace.length()); } } // 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 simple form-field, then save the form field value in the map. if (diskFileItem.isFormField()) { String characterEncoding = clientDataRequest.getCharacterEncoding(); String requestParameterValue = null; if (characterEncoding == null) { requestParameterValue = diskFileItem.getString(); } else { requestParameterValue = diskFileItem.getString(characterEncoding); } facesRequestParameterMap.addValue(fieldName, requestParameterValue); } else { 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); facesRequestParameterMap.addValue(fieldName, copiedFileAbsolutePath); 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.pronoiahealth.olhie.server.rest.BookAssetUploadServiceImpl.java
/** * Receive an upload book assest// w ww .j a va 2s . c om * * @see com.pronoiahealth.olhie.server.rest.BookAssetUploadService#process2(javax.servlet.http.HttpServletRequest) */ @Override @POST @Path("/upload2") @Produces("text/html") @SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR }) public String process2(@Context HttpServletRequest req) throws ServletException, IOException, FileUploadException { try { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (isMultipart == true) { // FileItemFactory fileItemFactory = new FileItemFactory(); String description = null; String descriptionDetail = null; String hoursOfWorkStr = null; String bookId = null; String action = null; String dataType = null; String contentType = null; //String data = null; byte[] bytes = null; String fileName = null; long size = 0; ServletFileUpload fileUpload = new ServletFileUpload(); fileUpload.setSizeMax(FILE_SIZE_LIMIT); FileItemIterator iter = fileUpload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); if (item.isFormField()) { // description if (item.getFieldName().equals("description")) { description = Streams.asString(stream); } // detail if (item.getFieldName().equals("descriptionDetail")) { descriptionDetail = Streams.asString(stream); } // Work hours if (item.getFieldName().equals("hoursOfWork")) { hoursOfWorkStr = Streams.asString(stream); } // BookId if (item.getFieldName().equals("bookId")) { bookId = Streams.asString(stream); } // action if (item.getFieldName().equals("action")) { action = Streams.asString(stream); } // datatype if (item.getFieldName().equals("dataType")) { dataType = Streams.asString(stream); } } else { if (item != null) { contentType = item.getContentType(); fileName = item.getName(); item.openStream(); InputStream in = item.openStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(in, bos); bytes = bos.toByteArray(); size = bytes.length; } } } // convert the hoursOfWork int hoursOfWork = 0; if (hoursOfWorkStr != null) { try { hoursOfWork = Integer.parseInt(hoursOfWorkStr); } catch (Exception e) { log.log(Level.WARNING, "Could not conver " + hoursOfWorkStr + " to an int in BookAssetUploadServiceImpl. Converting to 0."); hoursOfWork = 0; } } // Verify that the session user is the author or co-author of // the book. They would be the only ones who could add to the // book. String userId = userToken.getUserId(); boolean isAuthor = bookDAO.isUserAuthorOrCoauthorOfBook(userId, bookId); if (isAuthor == false) { throw new Exception("The user " + userId + " is not the author or co-author of the book."); } // Add to the database bookDAO.addUpdateBookassetBytes(description, descriptionDetail, bookId, contentType, BookAssetDataType.valueOf(dataType).toString(), bytes, action, fileName, null, null, size, hoursOfWork, userId); // Tell Solr about the update queueBookEvent.fire(new QueueBookEvent(bookId, userId)); } return "OK"; } catch (Exception e) { log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e); // return "ERROR:\n" + e.getMessage(); if (e instanceof FileUploadException) { throw (FileUploadException) e; } else { throw new FileUploadException(e.getMessage()); } } }
From source file:fi.helsinki.lib.simplerest.RootCommunitiesResource.java
@Post public Representation addCommunity(InputRepresentation rep) { Context c = null;/* ww w. j a va 2 s.com*/ Community community; try { c = getAuthenticatedContext(); community = Community.create(null, c); RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory()); FileItemIterator iter = rfu.getItemIterator(rep); String name = null; String shortDescription = null; String introductoryText = null; String copyrightText = null; String sideBarText = null; Bitstream bitstream = null; String bitstreamMimeType = null; while (iter.hasNext()) { FileItemStream fileItemStream = iter.next(); if (fileItemStream.isFormField()) { String key = fileItemStream.getFieldName(); String value = IOUtils.toString(fileItemStream.openStream(), "UTF-8"); if (key.equals("name")) { name = value; } else if (key.equals("short_description")) { shortDescription = value; } else if (key.equals("introductory_text")) { introductoryText = value; } else if (key.equals("copyright_text")) { copyrightText = value; } else if (key.equals("side_bar_text")) { sideBarText = value; } else { return error(c, "Unexpected attribute: " + key, Status.CLIENT_ERROR_BAD_REQUEST); } } else { if (bitstream != null) { return error(c, "The community can have only one logo.", Status.CLIENT_ERROR_BAD_REQUEST); } // I did not manage to use FormatIdentifier.guessFormat // here, so let's do it by ourselves... I would prefer to // use the actual file content and not its name, but let's // keep the code simple... String fileName = fileItemStream.getName(); if (fileName.length() == 0) { continue; } int lastDot = fileName.lastIndexOf('.'); if (lastDot != -1) { String extension = fileName.substring(lastDot + 1); extension = extension.toLowerCase(); if (extension.equals("jpg") || extension.equals("jpeg")) { bitstreamMimeType = "image/jpeg"; } else if (extension.equals("png")) { bitstreamMimeType = "image/png"; } else if (extension.equals("gif")) { bitstreamMimeType = "image/gif"; } } if (bitstreamMimeType == null) { String err = "The logo filename extension was not recognised."; return error(c, err, Status.CLIENT_ERROR_BAD_REQUEST); } bitstream = community.setLogo(fileItemStream.openStream()); // We don't set the format of the logo (bitstream) here, // it's done in the code below... } } community.setMetadata("name", name); community.setMetadata("short_description", shortDescription); community.setMetadata("introductory_text", introductoryText); community.setMetadata("copyright_text", copyrightText); community.setMetadata("side_bar_text", sideBarText); community.update(); // Set the format (jpeg, png, or gif) of logo: Bitstream logo = community.getLogo(); if (logo != null) { BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, bitstreamMimeType); logo.setFormat(bf); logo.update(); } c.complete(); } catch (AuthorizeException ae) { return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED); } catch (Exception e) { return errorInternal(c, e.toString()); } return successCreated("Community created.", baseUrl() + CommunityResource.relativeUrl(community.getID())); }
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 {/*from w w w . j ava2 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:fi.helsinki.lib.simplerest.CollectionsResource.java
@Post public Representation addCollection(InputRepresentation rep) { Context c = null;// ww w. ja v a 2 s.com 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, "SQLException"); } String msg = null; String url = baseUrl(); try { RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory()); FileItemIterator iter = rfu.getItemIterator(rep); // Logo String bitstreamMimeType = null; byte[] logoBytes = null; // Collection String name = null; String shortDescription = null; String introductoryText = null; String copyrightText = null; String sideBarText = null; String provenanceDescription = null; String license = null; while (iter.hasNext()) { FileItemStream fileItemStream = iter.next(); if (fileItemStream.isFormField()) { String key = fileItemStream.getFieldName(); String value = IOUtils.toString(fileItemStream.openStream(), "UTF-8"); if (key.equals("name")) { name = value; } else if (key.equals("short_description")) { shortDescription = value; } else if (key.equals("introductory_text")) { introductoryText = value; } else if (key.equals("copyright_text")) { copyrightText = value; } else if (key.equals("side_bar_text")) { sideBarText = value; } else if (key.equals("provenance_description")) { provenanceDescription = value; } else if (key.equals("license")) { license = value; } else { return error(c, "Unexpected attribute: " + key, Status.CLIENT_ERROR_BAD_REQUEST); } } else { if (logoBytes != null) { return error(c, "The collection can have only one logo.", Status.CLIENT_ERROR_BAD_REQUEST); } // TODO: Refer to comments in.... String fileName = fileItemStream.getName(); if (fileName.length() == 0) { continue; } int lastDot = fileName.lastIndexOf('.'); if (lastDot != -1) { String extension = fileName.substring(lastDot + 1); extension = extension.toLowerCase(); if (extension.equals("jpg") || extension.equals("jpeg")) { bitstreamMimeType = "image/jpeg"; } else if (extension.equals("png")) { bitstreamMimeType = "image/png"; } else if (extension.equals("gif")) { bitstreamMimeType = "image/gif"; } } if (bitstreamMimeType == null) { String err = "The logo filename extension was not recognised."; return error(c, err, Status.CLIENT_ERROR_BAD_REQUEST); } InputStream inputStream = fileItemStream.openStream(); logoBytes = IOUtils.toByteArray(inputStream); } } Collection collection = community.createCollection(); collection.setMetadata("name", name); collection.setMetadata("short_description", shortDescription); collection.setMetadata("introductory_text", introductoryText); collection.setMetadata("copyright_text", copyrightText); collection.setMetadata("side_bar_text", sideBarText); collection.setMetadata("provenance_description", provenanceDescription); collection.setMetadata("license", license); if (logoBytes != null) { ByteArrayInputStream byteStream; byteStream = new ByteArrayInputStream(logoBytes); collection.setLogo(byteStream); } collection.update(); Bitstream logo = collection.getLogo(); if (logo != null) { BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, bitstreamMimeType); logo.setFormat(bf); logo.update(); } url += CollectionResource.relativeUrl(collection.getID()); c.complete(); } catch (AuthorizeException ae) { return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED); } catch (Exception e) { return errorInternal(c, e.toString()); } return successCreated("Collection created.", url); }
From source file:ch.entwine.weblounge.contentrepository.impl.endpoint.FilesEndpoint.java
/** * Adds the resource content with language <code>language</code> to the * specified resource.//ww w. jav 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.ultrapower.eoms.common.plugin.ajaxupload.AjaxMultiPartRequest.java
/** * Creates a new request wrapper to handle multi-part data using methods * adapted from Jason Pell's multipart classes (see class description). * //from w w w.j a v a2 s. c o m * @param saveDir * the directory to save off the file * @param servletRequest * the request containing the multipart * @throws java.io.IOException * is thrown if encoding fails. * @throws */ public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException { Integer delay = 3; UploadListener listener = null; DiskFileItemFactory fac = null; // Parse the request try { if (maxSize >= 0L && servletRequest.getContentLength() > maxSize) { servletRequest.setAttribute("error", "size"); FileItemIterator it = new ServletFileUpload(fac).getItemIterator(servletRequest); // handle with each file: while (it.hasNext()) { FileItemStream item = it.next(); if (item.isFormField()) { List<String> values; if (params.get(item.getFieldName()) != null) { values = params.get(item.getFieldName()); } else { values = new ArrayList<String>(); } InputStream stream = item.openStream(); values.add(Streams.asString(stream)); params.put(item.getFieldName(), values); } } return; } else { listener = new UploadListener(servletRequest, delay); fac = new MonitoredDiskFileItemFactory(listener); } // Make sure that the data is written to file fac.setSizeThreshold(0); if (saveDir != null) { fac.setRepository(new File(saveDir)); } ServletFileUpload upload = new ServletFileUpload(fac); upload.setSizeMax(maxSize); List items = upload.parseRequest(createRequestContext(servletRequest)); for (Object item1 : items) { FileItem item = (FileItem) item1; if (log.isDebugEnabled()) log.debug("Found item " + item.getFieldName()); if (item.isFormField()) { log.debug("Item is a normal form field"); List<String> values; if (params.get(item.getFieldName()) != null) { values = params.get(item.getFieldName()); } else { values = new ArrayList<String>(); } String charset = servletRequest.getCharacterEncoding(); if (charset != null) { values.add(item.getString(charset)); } else { values.add(item.getString()); } params.put(item.getFieldName(), values); } else { log.debug("Item is a file upload"); // Skip file uploads that don't have a file name - meaning // that no file was selected. if (item.getName() == null || item.getName().trim().length() < 1) { log.debug("No file has been uploaded for the field: " + item.getFieldName()); continue; } String targetFileName = item.getName(); if (!targetFileName.contains(":")) item.write(new File(targetDirectory + targetFileName)); //?Action List<FileItem> values; if (files.get(item.getFieldName()) != null) { values = files.get(item.getFieldName()); } else { values = new ArrayList<FileItem>(); } values.add(item); files.put(item.getFieldName(), values); } } } catch (Exception e) { log.error(e); errors.add(e.getMessage()); } }
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. * /*ww w . jav a 2s. c o 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); } }
From source file:ai.ilikeplaces.servlets.ServletFileUploads.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request__/*from w w w .j av a 2s. co m*/ * @param response__ * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(final HttpServletRequest request__, final HttpServletResponse response__) throws ServletException, IOException { response__.setContentType("text/html;charset=UTF-8"); Loggers.DEBUG.debug(logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0020"), request__.getLocale()); PrintWriter out = response__.getWriter(); final ResourceBundle gUI = PropertyResourceBundle.getBundle("ai.ilikeplaces.rbs.GUI"); try { fileUpload: { if (!isFileUploadPermitted()) { errorTemporarilyDisabled(out); break fileUpload; } processSignOn: { final HttpSession session = request__.getSession(false); if (session == null) { errorNoLogin(out); break fileUpload; } else if (session.getAttribute(ServletLogin.HumanUser) == null) { errorNoLogin(out); break processSignOn; } processRequestType: { @SuppressWarnings("unchecked") final HumanUserLocal sBLoggedOnUserLocal = ((SessionBoundBadRefWrapper<HumanUserLocal>) session .getAttribute(ServletLogin.HumanUser)).getBoundInstance(); try { /*Check that we have a file upload request*/ final boolean isMultipart = ServletFileUpload.isMultipartContent(request__); if (!isMultipart) { LoggerFactory.getLogger(ServletFileUploads.class.getName()).error( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0001")); errorNonMultipart(out); break processRequestType; } processRequest: { // Create a new file upload handler final ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(request__); boolean persisted = false; loop: { Long locationId = null; String photoDescription = null; String photoName = null; Boolean isPublic = null; Boolean isPrivate = null; boolean fileSaved = false; while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); String absoluteFileSystemFileName = FilePath; InputStream stream = item.openStream(); @_fix(issue = "Handle no extension files") String usersFileName = null; String randomFileName = null; if (item.isFormField()) { final String value = Streams.asString(stream); Loggers.DEBUG.debug( logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0002"), name); Loggers.DEBUG.debug( logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0003"), value); if (name.equals("locationId")) { locationId = Long.parseLong(value); Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0004"))); } if (name.equals("photoDescription")) { photoDescription = value; Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0005"))); } if (name.equals("photoName")) { photoName = value; Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0006"))); } if (name.equals("isPublic")) { if (!(value.equals("true") || value.equals("false"))) { throw new IllegalArgumentException(logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0007") + value); } isPublic = Boolean.valueOf(value); Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0008"))); } if (name.equals("isPrivate")) { if (!(value.equals("true") || value.equals("false"))) { throw new IllegalArgumentException(logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0007") + value); } isPrivate = Boolean.valueOf(value); Loggers.DEBUG.debug("HELLO, I PROPERLY RECEIVED photoName."); } } if ((!item.isFormField())) { Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0009") + name)); Loggers.DEBUG.debug((logMsgs .getString("ai.ilikeplaces.servlets.ServletFileUploads.0010") + item.getName())); // Process the input stream if (!(item.getName().lastIndexOf(".") > 0)) { errorFileType(out, item.getName()); break processRequest; } usersFileName = (item.getName().indexOf("\\") <= 1 ? item.getName() : item.getName() .substring(item.getName().lastIndexOf("\\") + 1)); final String userUploadedFileName = item.getName(); String fileExtension = "error"; if (userUploadedFileName.toLowerCase().endsWith(".jpg")) { fileExtension = ".jpg"; } else if (userUploadedFileName.toLowerCase().endsWith(".jpeg")) { fileExtension = ".jpeg"; } else if (userUploadedFileName.toLowerCase().endsWith(".png")) { fileExtension = ".png"; } else { errorFileType(out, gUI.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0019")); break processRequest; } randomFileName = getRandomFileName(locationId); randomFileName += fileExtension; final File uploadedFile = new File( absoluteFileSystemFileName += randomFileName); final FileOutputStream fos = new FileOutputStream(uploadedFile); while (true) { final int dataByte = stream.read(); if (dataByte != -1) { fos.write(dataByte); } else { break; } } fos.close(); stream.close(); fileSaved = true; } Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0011") + locationId); Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0012") + fileSaved); Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0013") + photoDescription); Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0014") + photoName); Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0015") + isPublic); if (fileSaved && (photoDescription != null)) { persistData: { handlePublicPrivateness: { if ((isPublic != null) && isPublic && (locationId != null)) { Return<PublicPhoto> r = DB .getHumanCRUDPublicPhotoLocal(true) .cPublicPhoto(sBLoggedOnUserLocal.getHumanUserId(), locationId, absoluteFileSystemFileName, photoName, photoDescription, new String(CDN + randomFileName), 4); if (r.returnStatus() == 0) { successFileName(out, usersFileName, logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0016")); } else { errorBusy(out); } } else if ((isPrivate != null) && isPrivate) { Return<PrivatePhoto> r = DB .getHumanCRUDPrivatePhotoLocal(true) .cPrivatePhoto(sBLoggedOnUserLocal.getHumanUserId(), absoluteFileSystemFileName, photoName, photoDescription, new String(CDN + randomFileName)); if (r.returnStatus() == 0) { successFileName(out, usersFileName, "private"); } else { errorBusy(out); } } else { throw UNSUPPORTED_OPERATION_EXCEPTION; } } } /*We got what we need from the loop. Lets break it*/ break loop; } } } if (!persisted) { errorMissingParameters(out); break processRequest; } } } catch (FileUploadException ex) { Loggers.EXCEPTION.error(null, ex); errorBusy(out); } } } } } catch (final Throwable t_) { Loggers.EXCEPTION.error("SORRY! I ENCOUNTERED AN EXCEPTION DURING THE FILE UPLOAD", t_); } }
From source file:ninja.uploads.DiskFileItemProvider.java
@Override public FileItem create(FileItemStream item) { File tmpFile = null;//from w w w . j a v a 2 s.c o m // do copy try (InputStream is = item.openStream()) { tmpFile = File.createTempFile("nju", null, tmpFolder); Files.copy(is, tmpFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new RuntimeException("Failed to create temporary uploaded file on disk", e); } // return final String name = item.getName(); final File file = tmpFile; final String contentType = item.getContentType(); final FileItemHeaders headers = item.getHeaders(); return new FileItem() { @Override public String getFileName() { return name; } @Override public InputStream getInputStream() { try { return new FileInputStream(file); } catch (FileNotFoundException e) { throw new RuntimeException("Failed to read temporary uploaded file from disk", e); } } @Override public File getFile() { return file; } @Override public String getContentType() { return contentType; } @Override public FileItemHeaders getHeaders() { return headers; } @Override public void cleanup() { // try to delete temporary file, silently fail on error try { file.delete(); } catch (Exception e) { } } }; }