List of usage examples for org.apache.commons.fileupload FileItemIterator next
FileItemStream next() throws FileUploadException, IOException;
From source file:com.zimbra.cs.service.UserServletContext.java
public InputStream getRequestInputStream(long limit) throws IOException, ServiceException, UserServletException { String contentType = MimeConstants.CT_APPLICATION_OCTET_STREAM; String filename = null;/* w ww . j a va2 s . c o m*/ InputStream is = null; final long DEFAULT_MAX_SIZE = 10 * 1024 * 1024; if (limit == 0) { if (req.getParameter("lbfums") != null) { limit = Provisioning.getInstance().getLocalServer() .getLongAttr(Provisioning.A_zimbraFileUploadMaxSize, DEFAULT_MAX_SIZE); } else { limit = Provisioning.getInstance().getConfig().getLongAttr(Provisioning.A_zimbraMtaMaxMessageSize, DEFAULT_MAX_SIZE); } } boolean doCsrfCheck = false; if (req.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK) != null) { doCsrfCheck = (Boolean) req.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK); } if (ServletFileUpload.isMultipartContent(req)) { ServletFileUpload sfu = new ServletFileUpload(); try { FileItemIterator iter = sfu.getItemIterator(req); while (iter.hasNext()) { FileItemStream fis = iter.next(); if (fis.isFormField()) { is = fis.openStream(); params.put(fis.getFieldName(), new String(ByteUtil.getContent(is, -1), "UTF-8")); if (doCsrfCheck && !this.csrfAuthSucceeded) { String csrfToken = params.get(FileUploadServlet.PARAM_CSRF_TOKEN); if (UserServlet.log.isDebugEnabled()) { String paramValue = req.getParameter(UserServlet.QP_AUTH); UserServlet.log.debug( "CSRF check is: %s, CSRF token is: %s, Authentication recd with request is: %s", doCsrfCheck, csrfToken, paramValue); } if (!CsrfUtil.isValidCsrfToken(csrfToken, authToken)) { setCsrfAuthSucceeded(Boolean.FALSE); UserServlet.log.debug( "CSRF token validation failed for account: %s" + ", Auth token is CSRF enabled: %s" + "CSRF token is: %s", authToken, authToken.isCsrfTokenEnabled(), csrfToken); throw new UserServletException(HttpServletResponse.SC_UNAUTHORIZED, L10nUtil.getMessage(MsgKey.errMustAuthenticate)); } else { setCsrfAuthSucceeded(Boolean.TRUE); } } is.close(); is = null; } else { is = new UploadInputStream(fis.openStream(), limit); break; } } } catch (UserServletException e) { throw new UserServletException(e.getHttpStatusCode(), e.getMessage(), e); } catch (Exception e) { throw new UserServletException(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, e.toString()); } if (is == null) throw new UserServletException(HttpServletResponse.SC_NO_CONTENT, "No file content"); } else { ContentType ctype = new ContentType(req.getContentType()); String contentEncoding = req.getHeader("Content-Encoding"); contentType = ctype.getContentType(); filename = ctype.getParameter("name"); if (filename == null || filename.trim().equals("")) filename = new ContentDisposition(req.getHeader("Content-Disposition")).getParameter("filename"); is = new UploadInputStream(contentEncoding != null && contentEncoding.indexOf("gzip") != -1 ? new GZIPInputStream(req.getInputStream()) : req.getInputStream(), limit); } if (filename == null || filename.trim().equals("")) filename = "unknown"; else params.put(UserServlet.UPLOAD_NAME, filename); params.put(UserServlet.UPLOAD_TYPE, contentType); ZimbraLog.mailbox.info("UserServlet received file %s - %d request bytes", filename, req.getContentLength()); return is; }
From source file:fi.helsinki.lib.simplerest.CollectionsResource.java
@Post public Representation addCollection(InputRepresentation rep) { Context c = null;/*from ww w. j ava 2 s.co m*/ 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:com.webpagebytes.cms.controllers.FileController.java
public void uploadFolder(HttpServletRequest request, HttpServletResponse response, String requestUri) throws WPBException { try {//from w w w . ja va 2 s .co m ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding("UTF-8"); FileItemIterator iterator = upload.getItemIterator(request); WPBFile ownerFile = null; Map<String, WPBFile> subfolderFiles = new HashMap<String, WPBFile>(); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField() && item.getFieldName().equals("ownerExtKey")) { String ownerExtKey = Streams.asString(item.openStream()); ownerFile = getDirectory(ownerExtKey, adminStorage); } else if (!item.isFormField() && item.getFieldName().equals("file")) { String fullName = item.getName(); String directoryPath = getDirectoryFromLongName(fullName); String fileName = getFileNameFromLongName(fullName); Map<String, WPBFile> tempSubFolders = checkAndCreateSubDirectory(directoryPath, ownerFile); subfolderFiles.putAll(tempSubFolders); // delete the existing file WPBFile existingFile = getFileFromDirectory(subfolderFiles.get(directoryPath), fileName); if (existingFile != null) { deleteFile(existingFile, 0); } // create the file WPBFile file = new WPBFile(); file.setExternalKey(adminStorage.getUniqueId()); file.setFileName(fileName); file.setLastModified(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime()); file.setDirectoryFlag(0); addFileToDirectory(subfolderFiles.get(directoryPath), file, item.openStream()); } } org.json.JSONObject returnJson = new org.json.JSONObject(); returnJson.put(DATA, jsonObjectConverter.JSONFromObject(null)); httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null); } catch (Exception e) { Map<String, String> errors = new HashMap<String, String>(); errors.put("", WPBErrors.WB_CANT_UPDATE_RECORD); httpServletToolbox.writeBodyResponseAsJson(response, jsonObjectConverter.JSONObjectFromMap(null), errors); } }
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();//w ww . 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(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();// w ww . j a v a 2 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 = 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:edu.umn.msi.tropix.webgui.server.UploadController.java
@ServiceMethod(secure = true) public ModelAndView handleRequest(final HttpServletRequest request, final HttpServletResponse response) throws Exception { LOG.debug("In UploadController.handleRequest"); //final String userId = securityProvider.getUserIdForSessionId(request.getParameter("sessionId")); //Preconditions.checkState(userId != null); final String userId = userSession.getGridId(); LOG.debug("Upload by user with id " + userId); String clientId = request.getParameter("clientId"); if (!StringUtils.hasText(clientId)) { clientId = UUID.randomUUID().toString(); }/*from w w w .jav a 2s . c o m*/ final String endStr = request.getParameter("end"); final String startStr = request.getParameter("start"); final String zipStr = request.getParameter("zip"); final String lastUploadStr = request.getParameter("lastUpload"); final boolean isZip = StringUtils.hasText("zip") ? Boolean.parseBoolean(zipStr) : false; final boolean lastUploads = StringUtils.hasText(lastUploadStr) ? Boolean.parseBoolean(lastUploadStr) : true; LOG.trace("Upload request with startStr " + startStr); final StringWriter rawJsonWriter = new StringWriter(); final JSONWriter jsonWriter = new JSONWriter(rawJsonWriter); final FileItemFactory factory = new DiskFileItemFactory(); final long requestLength = StringUtils.hasText(endStr) ? Long.parseLong(endStr) : request.getContentLength(); long bytesWritten = StringUtils.hasText(startStr) ? Long.parseLong(startStr) : 0L; final ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); // Deal with international file names final FileItemIterator iter = upload.getItemIterator(request); // Setup message conditionalSampleComponent to track upload progress... final ProgressMessageSupplier supplier = new ProgressMessageSupplier(); supplier.setId(userId + "/" + clientId); supplier.setName("Upload File(s) to Web Application"); final ProgressTrackerImpl progressTracker = new ProgressTrackerImpl(); progressTracker.setUserGridId(userId); progressTracker.setCometPusher(cometPusher); progressTracker.setProgressMessageSupplier(supplier); jsonWriter.object(); jsonWriter.key("result"); jsonWriter.array(); while (iter.hasNext()) { final FileItemStream item = iter.next(); if (item.isFormField()) { continue; } File destination; InputStream inputStream = null; OutputStream outputStream = null; if (!isZip) { final String fileName = FilenameUtils.getName(item.getName()); // new File(item.getName()).getName(); LOG.debug("Handling upload of file with name " + fileName); final TempFileInfo info = tempFileStore.getTempFileInfo(fileName); recordJsonInfo(jsonWriter, info); destination = info.getTempLocation(); } else { destination = FILE_UTILS.createTempFile(); } try { inputStream = item.openStream(); outputStream = FILE_UTILS.getFileOutputStream(destination); bytesWritten += progressTrackingIoUtils.copy(inputStream, outputStream, bytesWritten, requestLength, progressTracker); if (isZip) { ZipUtilsFactory.getInstance().unzip(destination, new Function<String, File>() { public File apply(final String fileName) { final String cleanedUpFileName = FilenameUtils.getName(fileName); final TempFileInfo info = tempFileStore.getTempFileInfo(cleanedUpFileName); recordJsonInfo(jsonWriter, info); return info.getTempLocation(); } }); } } finally { IO_UTILS.closeQuietly(inputStream); IO_UTILS.closeQuietly(outputStream); if (isZip) { FILE_UTILS.deleteQuietly(destination); } } } if (lastUploads) { progressTracker.complete(); } jsonWriter.endArray(); jsonWriter.endObject(); // response.setStatus(200); final String json = rawJsonWriter.getBuffer().toString(); LOG.debug("Upload json response " + json); response.setContentType("text/html"); // GWT was attaching <pre> tag to result without this response.getOutputStream().println(json); return null; }
From source file:com.igeekinc.indelible.indeliblefs.webaccess.IndelibleWebAccessServlet.java
public void createFile(HttpServletRequest req, HttpServletResponse resp, Document buildDoc) throws IndelibleWebAccessException, IOException, ServletException, FileUploadException { boolean completedOK = false; boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(req); if (iter.hasNext()) { FileItemStream item = iter.next(); String fieldName = item.getFieldName(); FilePath dirPath = null;//from w w w .j a va 2 s. c o m if (fieldName.equals("upfile")) { try { connection.startTransaction(); String path = req.getPathInfo(); String fileName = item.getName(); if (fileName.indexOf('/') >= 0) throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null); dirPath = FilePath.getFilePath(path); FilePath reqPath = dirPath.getChild(fileName); if (reqPath == null || reqPath.getNumComponents() < 2) throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null); // Should be an absolute path reqPath = reqPath.removeLeadingComponent(); String fsIDStr = reqPath.getComponent(0); IndelibleFSVolumeIF volume = getVolume(fsIDStr); if (volume == null) throw new IndelibleWebAccessException(IndelibleWebAccessException.kVolumeNotFoundError, null); FilePath createPath = reqPath.removeLeadingComponent(); FilePath parentPath = createPath.getParent(); FilePath childPath = createPath.getPathRelativeTo(parentPath); if (childPath.getNumComponents() != 1) throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null); IndelibleFileNodeIF parentNode = volume.getObjectByPath(parentPath.makeAbsolute()); if (!parentNode.isDirectory()) throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotDirectory, null); IndelibleDirectoryNodeIF parentDirectory = (IndelibleDirectoryNodeIF) parentNode; IndelibleFileNodeIF childNode = null; childNode = parentDirectory.getChildNode(childPath.getName()); if (childNode == null) { try { CreateFileInfo childInfo = parentDirectory.createChildFile(childPath.getName(), true); childNode = childInfo.getCreatedNode(); } catch (FileExistsException e) { // Probably someone else beat us to it... childNode = parentDirectory.getChildNode(childPath.getName()); } } else { } if (childNode.isDirectory()) throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotFile, null); IndelibleFSForkIF dataFork = childNode.getFork("data", true); dataFork.truncate(0); InputStream readStream = item.openStream(); byte[] writeBuffer = new byte[1024 * 1024]; int readLength; long bytesCopied = 0; int bufOffset = 0; while ((readLength = readStream.read(writeBuffer, bufOffset, writeBuffer.length - bufOffset)) > 0) { if (bufOffset + readLength == writeBuffer.length) { dataFork.appendDataDescriptor( new CASIDMemoryDataDescriptor(writeBuffer, 0, writeBuffer.length)); bufOffset = 0; } else bufOffset += readLength; bytesCopied += readLength; } if (bufOffset != 0) { // Flush out the final stuff dataFork.appendDataDescriptor(new CASIDMemoryDataDescriptor(writeBuffer, 0, bufOffset)); } connection.commit(); completedOK = true; } catch (PermissionDeniedException e) { throw new IndelibleWebAccessException(IndelibleWebAccessException.kPermissionDenied, e); } catch (IOException e) { throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e); } catch (ObjectNotFoundException e) { throw new IndelibleWebAccessException(IndelibleWebAccessException.kPathNotFound, e); } catch (ForkNotFoundException e) { throw new IndelibleWebAccessException(IndelibleWebAccessException.kForkNotFound, e); } finally { if (!completedOK) try { connection.rollback(); } catch (IOException e) { throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e); } } listPath(dirPath, buildDoc); return; } } throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null); }
From source file:com.netflix.zuul.scriptManager.FilterScriptManagerServlet.java
private String handlePostBody(HttpServletRequest request, HttpServletResponse response) throws IOException { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); org.apache.commons.fileupload.FileItemIterator it = null; try {/* w ww .ja v a 2 s .co m*/ it = upload.getItemIterator(request); while (it.hasNext()) { FileItemStream stream = it.next(); InputStream input = stream.openStream(); // NOTE: we are going to pull the entire stream into memory // this will NOT work if we have huge scripts, but we expect these to be measured in KBs, not MBs or larger byte[] uploadedBytes = getBytesFromInputStream(input); input.close(); if (uploadedBytes.length == 0) { setUsageError(400, "ERROR: Body contained no data.", response); return null; } return new String(uploadedBytes); } } catch (FileUploadException e) { throw new IOException(e.getMessage()); } return null; }
From source file:n3phele.service.rest.impl.CommandResource.java
@Consumes(MediaType.MULTIPART_FORM_DATA) @POST// w ww . ja v a 2s.co m @Produces(MediaType.TEXT_PLAIN) @Path("import") @RolesAllowed("authenticated") public Response importer(@Context HttpServletRequest request) { try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { log.warning("Got a form field: " + item.getFieldName()); } else { log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName()); // JAXBContext jc = JAXBContext.newInstance(CommandDefinitions.class); // Unmarshaller u = jc.createUnmarshaller(); // CommandDefinitions a = (CommandDefinitions) u.unmarshal(stream); JSONJAXBContext jc = new JSONJAXBContext(CommandDefinitions.class); JSONUnmarshaller u = jc.createJSONUnmarshaller(); CommandDefinitions a = u.unmarshalFromJSON(stream, CommandDefinitions.class); StringBuilder response = new StringBuilder( "Processing " + a.getCommand().size() + " commands\n"); URI requestor = UserResource.toUser(securityContext).getUri(); for (CommandDefinition cd : a.getCommand()) { response.append(cd.getName()); response.append("....."); Command existing = null; try { if (cd.getUri() != null && cd.getUri().toString().length() != 0) { try { existing = dao.command().get(cd.getUri()); } catch (NotFoundException e1) { List<Command> others = null; try { others = dao.command().getList(cd.getName()); for (Command c : others) { if (c.getVersion().equals(cd.getVersion()) || !requestor.equals(c.getOwner())) { existing = c; } else { if (c.isPreferred() && cd.isPreferred()) { c.setPreferred(false); dao.command().update(c); } } } } catch (Exception e) { // not found } } } else { List<Command> others = null; try { others = dao.command().getList(cd.getName()); for (Command c : others) { if (c.getVersion().equals(cd.getVersion()) || !requestor.equals(c.getOwner())) { existing = c; break; } } } catch (Exception e) { // not found } } } catch (NotFoundException e) { } if (existing == null) { response.append(addCommand(cd)); } else { // update or illegal operation boolean isOwner = requestor.equals(existing.getOwner()); boolean mismatchedUri = (cd.getUri() != null && cd.getUri().toString().length() != 0) && !cd.getUri().equals(existing.getUri()); log.info("requestor is " + requestor + " owner is " + existing.getOwner() + " isOwner " + isOwner); log.info("URI in definition is " + cd.getUri() + " existing is " + existing.getUri() + " mismatchedUri " + mismatchedUri); if (!isOwner || mismatchedUri) { response.append("ignored: already exists"); } else { response.append(updateCommand(cd, existing)); response.append("\nupdated uri " + existing.getUri()); } } response.append("\n"); //response.append("</li>"); } //response.append("</ol>"); return Response.ok(response.toString()).build(); } } } catch (JAXBException e) { log.log(Level.WARNING, "JAXBException", e); } catch (FileUploadException e) { log.log(Level.WARNING, "FileUploadException", e); } catch (IOException e) { log.log(Level.WARNING, "IOException", e); } return Response.notModified().build(); }
From source file:com.exilant.exility.core.HtmlRequestHandler.java
/** * //from www. j a v a 2 s . co 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; }