List of usage examples for org.apache.commons.fileupload.disk DiskFileItem getInputStream
public InputStream getInputStream() throws IOException
From source file:fr.ippon.wip.http.request.MultipartRequestBuilder.java
public HttpRequestBase buildHttpRequest() throws URISyntaxException { MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try {/* ww w . ja va 2 s . c om*/ for (DiskFileItem fileItem : files) { if (fileItem.isFormField()) multipartEntity.addPart(fileItem.getFieldName(), new StringBody(new String(fileItem.get()))); else { // FileBody fileBody = new FileBody(fileItem.getStoreLocation(), fileItem.getName(), fileItem.getContentType(), fileItem.getCharSet()); InputStreamBody fileBody = new InputStreamKnownSizeBody(fileItem.getInputStream(), fileItem.get().length, fileItem.getContentType(), fileItem.getName()); multipartEntity.addPart(fileItem.getFieldName(), fileBody); } } // some request may have additional parameters in a query string if (parameterMap != null) for (Entry<String, String> entry : parameterMap.entries()) multipartEntity.addPart(entry.getKey(), new StringBody(entry.getValue())); } catch (Exception e) { e.printStackTrace(); } HttpPost postRequest = new HttpPost(requestedURL); postRequest.setEntity(multipartEntity); return postRequest; }
From source file:com.liferay.portal.editor.fckeditor.receiver.impl.BaseCommandReceiver.java
public void fileUpload(CommandArgument commandArgument, HttpServletRequest request, HttpServletResponse response) {/* w w w. j av a2 s. c o m*/ InputStream inputStream = null; String returnValue = null; try { ServletFileUpload servletFileUpload = new LiferayFileUpload( new LiferayFileItemFactory(UploadServletRequestImpl.getTempDir()), request); servletFileUpload .setFileSizeMax(PrefsPropsUtil.getLong(PropsKeys.UPLOAD_SERVLET_REQUEST_IMPL_MAX_SIZE)); LiferayServletRequest liferayServletRequest = new LiferayServletRequest(request); List<FileItem> fileItems = servletFileUpload.parseRequest(liferayServletRequest); Map<String, Object> fields = new HashMap<String, Object>(); for (FileItem fileItem : fileItems) { if (fileItem.isFormField()) { fields.put(fileItem.getFieldName(), fileItem.getString()); } else { fields.put(fileItem.getFieldName(), fileItem); } } DiskFileItem diskFileItem = (DiskFileItem) fields.get("NewFile"); String fileName = StringUtil.replace(diskFileItem.getName(), CharPool.BACK_SLASH, CharPool.SLASH); String[] fileNameArray = StringUtil.split(fileName, '/'); fileName = fileNameArray[fileNameArray.length - 1]; String contentType = diskFileItem.getContentType(); if (Validator.isNull(contentType) || contentType.equals(ContentTypes.APPLICATION_OCTET_STREAM)) { contentType = MimeTypesUtil.getContentType(diskFileItem.getStoreLocation()); } if (diskFileItem.isInMemory()) { inputStream = diskFileItem.getInputStream(); } else { inputStream = new ByteArrayFileInputStream(diskFileItem.getStoreLocation(), LiferayFileItem.THRESHOLD_SIZE); } long size = diskFileItem.getSize(); returnValue = fileUpload(commandArgument, fileName, inputStream, contentType, size); } catch (Exception e) { FCKException fcke = null; if (e instanceof FCKException) { fcke = (FCKException) e; } else { fcke = new FCKException(e); } Throwable cause = fcke.getCause(); returnValue = "203"; if (cause != null) { String causeString = GetterUtil.getString(cause.toString()); if (causeString.contains("NoSuchFolderException") || causeString.contains("NoSuchGroupException")) { returnValue = "204"; } else if (causeString.contains("ImageNameException")) { returnValue = "205"; } else if (causeString.contains("FileExtensionException") || causeString.contains("FileNameException")) { returnValue = "206"; } else if (causeString.contains("PrincipalException")) { returnValue = "207"; } else if (causeString.contains("ImageSizeException") || causeString.contains("FileSizeException")) { returnValue = "208"; } else if (causeString.contains("SystemException")) { returnValue = "209"; } else { throw fcke; } } _writeUploadResponse(returnValue, response); } finally { StreamUtil.cleanUp(inputStream); } _writeUploadResponse(returnValue, response); }
From source file:org.eclipse.rap.rwt.supplemental.fileupload.internal.FileUploadProcessor.java
void handleFileUpload(HttpServletRequest request, HttpServletResponse response) throws IOException { try {/*from ww w . j a v a 2 s. com*/ DiskFileItem fileItem = readUploadedFileItem(request); if (fileItem != null) { String fileName = stripFileName(fileItem.getName()); String contentType = fileItem.getContentType(); long contentLength = fileItem.getSize(); tracker.setFileName(fileName); tracker.setContentType(contentType); FileUploadReceiver receiver = handler.getReceiver(); IFileUploadDetails details = new FileUploadDetails(fileName, contentType, contentLength); receiver.receive(fileItem.getInputStream(), details); tracker.handleFinished(); } else { String errorMessage = NO_FILE_UPLOAD_DATA_FOUND_IN_REQUEST; tracker.setException(new Exception(errorMessage)); tracker.handleFailed(); response.sendError(HttpServletResponse.SC_BAD_REQUEST, errorMessage); } } catch (FileSizeLimitExceededException exception) { // Note: Apache fileupload 1.2 will throw an exception after the // upload is finished. // Therefore we handle it in the progress listener and ignore this // kind of exceptions here // https://issues.apache.org/jira/browse/FILEUPLOAD-145 response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, exception.getMessage()); } catch (Exception exception) { tracker.setException(exception); tracker.handleFailed(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, exception.getMessage()); } }
From source file:org.jahia.admin.users.ManageUsers.java
private void processBatchCreate(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException, ServletException, JahiaException { logger.debug("Started"); long timer = System.currentTimeMillis(); FileUpload fileUpload = ((ParamBean) jParams).getFileUpload(); if (fileUpload != null) { DiskFileItem fileItem = fileUpload.getFileItems().get("csvFile"); if (fileItem == null) { logger.error("Couldn't find CSV file in form parameter name 'csvFile' aborting batch creation !"); displayUsers(request, response, session); return; }/*from w w w . ja v a2 s . co m*/ String csvSeparator = jParams.getParameter("csvSeparator"); CSVReader csvReader = new CSVReader(new InputStreamReader(fileItem.getInputStream(), "UTF-8"), csvSeparator.charAt(0)); // the first line contains the column names; String[] headerElements = csvReader.readNext(); List<String> headerElementList = Arrays.asList(headerElements); int userNamePos = headerElementList.indexOf("j:nodename"); int passwordPos = headerElementList.indexOf("j:password"); if ((userNamePos < 0) || (passwordPos < 0)) { logger.error("Couldn't find user name or password column in CSV file, aborting batch creation !"); displayUsers(request, response, session); return; } String[] lineElements = null; int errorsCreatingUsers = 0; int usersCreatedSuccessfully = 0; JahiaPasswordPolicyService pwdPolicyService = ServicesRegistry.getInstance() .getJahiaPasswordPolicyService(); JahiaUserManagerService userService = ServicesRegistry.getInstance().getJahiaUserManagerService(); while ((lineElements = csvReader.readNext()) != null) { List<String> lineElementList = Arrays.asList(lineElements); Properties properties = buildProperties(headerElementList, lineElementList); String userName = lineElementList.get(userNamePos); String password = lineElementList.get(passwordPos); if (userService.isUsernameSyntaxCorrect(userName)) { PolicyEnforcementResult evalResult = pwdPolicyService.enforcePolicyOnUserCreate(userName, password); if (evalResult.isSuccess()) { JahiaUser jahiaUser = userManager.createUser(userName, password, properties); if (jahiaUser != null) { usersCreatedSuccessfully++; logger.info("Successfully created user {}", userName); } else { errorsCreatingUsers++; logger.warn("Error creating user {}", userName); } } else { errorsCreatingUsers++; StringBuilder result = new StringBuilder(); for (String msg : evalResult.getTextMessages()) { result.append(msg).append("\n"); } logger.warn("Skipping user {}. Following password policy rules are violated\n{}", userName, result.toString()); } } else { errorsCreatingUsers++; logger.warn("Username {} is not valid. Skipping user.", userName); } } userMessage = Integer.toString(usersCreatedSuccessfully) + " " + getMessage("org.jahia.admin.userMessage.usersCreatedSuccessfully.label") + ", " + Integer.toString(errorsCreatingUsers) + " " + getMessage("org.jahia.admin.userMessage.usersNotCreatedBecauseOfErrors.label"); isError = false; } logger.info("Batch user create took " + (System.currentTimeMillis() - timer) + " ms"); displayUsers(request, response, session); }
From source file:org.jahia.bin.DocumentConverter.java
private ModelAndView handlePost(HttpServletRequest request, HttpServletResponse response) throws IOException { FileUpload fu = new FileUpload(request, settingsBean.getTmpContentDiskPath(), Integer.MAX_VALUE); if (fu.getFileItems().size() == 0) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No file was submitted"); return null; }/* w w w . java2 s .co m*/ // take the first one DiskFileItem inputFile = fu.getFileItems().values().iterator().next(); InputStream stream = null; String returnedMimeType = fu.getParameterValues("mimeType") != null ? fu.getParameterValues("mimeType")[0] : null; if (returnedMimeType == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing required parameter mimeType"); return null; } try { ServletOutputStream outputStream = response.getOutputStream(); stream = inputFile.getInputStream(); // return a file response.setContentType(returnedMimeType); response.setHeader("Content-Disposition", "attachment; filename=\"" + FilenameUtils.getBaseName(inputFile.getName()) + "." + converterService.getExtension(returnedMimeType) + "\""); converterService.convert(stream, inputFile.getContentType(), outputStream, returnedMimeType); try { outputStream.flush(); } finally { outputStream.close(); } } catch (Exception e) { logger.error( "Error converting uploaded file " + inputFile.getFieldName() + ". Cause: " + e.getMessage(), e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Exception occurred: " + e.getMessage()); } finally { IOUtils.closeQuietly(stream); fu.disposeItems(); } return null; }
From source file:org.jahia.bin.TextExtractor.java
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { if (!textExtractionService.isEnabled()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Text extraction service is not enabled."); return null; }// w ww . j a v a 2 s . c o m if (!ServletFileUpload.isMultipartContent(request)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No file was submitted"); return null; } FileUpload upload = new FileUpload(request, settingsBean.getTmpContentDiskPath(), Integer.MAX_VALUE); if (upload.getFileItems().size() == 0) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No file was submitted"); return null; } DiskFileItem inputFile = upload.getFileItems().values().iterator().next(); InputStream stream = null; try { stream = inputFile.getInputStream(); Metadata metadata = new Metadata(); metadata.set(Metadata.CONTENT_TYPE, inputFile.getContentType()); metadata.set(Metadata.RESOURCE_NAME_KEY, inputFile.getName()); long startTime = System.currentTimeMillis(); String content = textExtractionService.parse(stream, metadata); Map<String, Object> model = new HashMap<String, Object>(); Map<String, Object> properties = new HashMap<String, Object>(); for (String name : metadata.names()) { properties.put(name, metadata.isMultiValued(name) ? metadata.getValues(name) : metadata.get(name)); } model.put("metadata", properties); model.put("content", content); model.put("file", inputFile); model.put("extracted", Boolean.TRUE); model.put("extractionTime", Long.valueOf(System.currentTimeMillis() - startTime)); return new ModelAndView(view, model); } catch (Exception e) { logger.error("Error extracting text for uploaded file " + inputFile.getFieldName() + ". Cause: " + e.getMessage(), e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Exception occurred: " + e.getMessage()); } finally { IOUtils.closeQuietly(stream); for (DiskFileItem file : upload.getFileItems().values()) { file.delete(); } } return null; }
From source file:org.jahia.module.sampleBootstrapTemplate.actions.UpdateLogo.java
@Override public ActionResult doExecute(HttpServletRequest req, RenderContext renderContext, Resource resource, JCRSessionWrapper session, Map<String, List<String>> parameters, URLResolver urlResolver) throws Exception { JCRNodeWrapper logoFolder = renderContext.getSite().getNode(FILES); if (logoFolder.hasNode(BOOTSTRAP)) { logoFolder = logoFolder.getNode(BOOTSTRAP); } else {//from w ww.ja va 2s. c om logoFolder = logoFolder.addNode(BOOTSTRAP, Constants.JAHIANT_FOLDER); } if (logoFolder.hasNode(IMG)) { logoFolder = logoFolder.getNode(IMG); } else { logoFolder = logoFolder.addNode(IMG, Constants.JAHIANT_FOLDER); } JCRNodeWrapper logo; final FileUpload fileUpload = (FileUpload) req.getAttribute(FileUpload.FILEUPLOAD_ATTRIBUTE); if (fileUpload != null && fileUpload.getFileItems() != null && fileUpload.getFileItems().size() > 0) { final Map<String, DiskFileItem> stringDiskFileItemMap = fileUpload.getFileItems(); DiskFileItem itemEntry = stringDiskFileItemMap.get(stringDiskFileItemMap.keySet().iterator().next()); logo = logoFolder.uploadFile(LOGO_PNG, itemEntry.getInputStream(), JCRContentUtils.getMimeType(itemEntry.getName(), itemEntry.getContentType())); String fileExtension = FilenameUtils.getExtension(logo.getName()); final File f = File.createTempFile("logo", "." + fileExtension); imageService.createThumb(imageService.getImage(logo), f, 200, false); InputStream is = new FileInputStream(f); try { logo = logoFolder.uploadFile(LOGO_PNG, is, JCRContentUtils.getMimeType(itemEntry.getName(), itemEntry.getContentType())); } finally { IOUtils.closeQuietly(is); } session.save(); return new ActionResult(HttpServletResponse.SC_OK, null, new JSONObject().put("logoUpdate", true).put("logoUrl", logo.getUrl())); } else { String error = Messages.get("resources.sample-bootstrap-templates", "sampleBootstrapTemplates.uploadLogo.error", session.getLocale()); return new ActionResult(HttpServletResponse.SC_OK, null, new JSONObject().put("logoUpdate", false).put("errorMessage", error)); } }
From source file:org.jahia.modules.docconverter.DocumentConverterAction.java
public ActionResult doExecute(HttpServletRequest req, RenderContext renderContext, Resource resource, JCRSessionWrapper session, Map<String, List<String>> parameters, URLResolver urlResolver) throws Exception { if (converterService.isEnabled()) { // Get parameters + file final FileUpload fu = (FileUpload) req.getAttribute(FileUpload.FILEUPLOAD_ATTRIBUTE); DiskFileItem inputFile = fu.getFileItems().get("fileField"); List<String> mimeTypeList = parameters.get("mimeType"); String returnedMimeType = mimeTypeList != null ? mimeTypeList.get(0) : null; // Convert boolean conversionSucceeded = true; String failureMessage = null; File convertedFile = null; try {//w w w . j a v a 2s . c o m convertedFile = converterService.convert(inputFile.getStoreLocation(), inputFile.getContentType(), returnedMimeType); } catch (IOException ioe) { conversionSucceeded = false; failureMessage = ioe.getMessage(); } catch (OfficeException ioe) { conversionSucceeded = false; failureMessage = ioe.getMessage(); } if (convertedFile == null) { conversionSucceeded = false; } // Create a conversion node and the file node if all succeeded String originFileName = inputFile.getName(); String originMimeType = inputFile.getContentType(); String convertedFileName = FilenameUtils.getBaseName(inputFile.getName()) + "." + converterService.getExtension(returnedMimeType); JCRNodeWrapper convertedFilesNode = session.getNode(renderContext.getUser().getLocalPath() + "/files"); JCRNodeWrapper convertedFileNode; if (conversionSucceeded) { FileInputStream iStream = new FileInputStream(convertedFile); convertedFileNode = convertedFilesNode.uploadFile(convertedFileName, iStream, returnedMimeType); convertedFileNode.addMixin("jmix:convertedFile"); iStream.close(); } else { convertedFileNode = convertedFilesNode.uploadFile(convertedFileName, inputFile.getInputStream(), inputFile.getContentType()); convertedFileNode.addMixin("jmix:convertedFile"); convertedFileNode.setProperty("conversionFailedMessage", failureMessage); } convertedFileNode.setProperty("originDocName", originFileName); convertedFileNode.setProperty("originDocFormat", originMimeType); convertedFileNode.setProperty("convertedDocName", convertedFileName); convertedFileNode.setProperty("convertedDocFormat", returnedMimeType); convertedFileNode.setProperty("conversionSucceeded", conversionSucceeded); session.save(); } return new ActionResult(HttpServletResponse.SC_OK, null, new JSONObject()); }
From source file:org.okj.commons.web.fileupload.CommonsFileUploadConverter.java
/** * @see org.storevm.commons.web.fileupload.FileUploadConverter#convert(java.lang.Object) *//* ww w . ja v a 2 s.c o m*/ @Override public <T> UploadFile<T> convert(FileItem fileItem) { if (fileItem instanceof DiskFileItem) { // DiskFileItem diskFile = (DiskFileItem) fileItem; if (StringUtils.isNotBlank(diskFile.getName()) && diskFile.getSize() > 0) { UploadFile<T> uploadFile = new UploadFile<T>(); uploadFile.setContentType(diskFile.getContentType()); uploadFile.setFieldName(diskFile.getFieldName()); uploadFile.setFileName(FilenameUtils.getName(diskFile.getName())); try { File tmpFile = createTempFile(diskFile.getInputStream()); if (tmpFile != null) { uploadFile.setTmpFile(tmpFile); } return uploadFile; } catch (IOException ex) { LogUtils.error(LOGGER, "", ex); } } } return null; }
From source file:org.sakaiproject.content.tool.ResourcesHelperAction.java
private synchronized void doDragDropUpload(HttpServletRequest request, HttpServletResponse response, String fullPath) {//from w w w . java 2 s . c o m //Feel free to sent comments/warnings/advices to me at daniel.merino AT unavarra.es //Full method must be synchronized because a collection can edited and committed in two concurrent requests //Dropzone allows multiple parallel uploads so if all this process is not synchronized, InUseException is thrown //Maybe a more sophisticated concurrence can be set in the future SessionState state = getState(request); ToolSession toolSession = SessionManager.getCurrentToolSession(); ContentResourceEdit resource = null; ContentCollectionEdit collection = null; String uploadFileName = null; String collectionName = null; String resourceGroup = toolSession.getAttribute("resources.request.create_wizard_collection_id").toString(); if (!("undefined".equals(fullPath) || "".equals(fullPath))) { //Received a file that is inside an uploaded folder //Try to create a collection with this folder and to add the file inside it after File myfile = new File(fullPath); String fileName = myfile.getName(); collectionName = resourceGroup + myfile.getParent(); //AFAIK it is not possible to check undoubtedly if a collection exists //isCollection() only tests if name is valid and checkCollection() returns void type //So the procedure is to create the collection and capture thrown Exceptions collection = createCollectionIfNotExists(collectionName); if (collection == null) { addAlert(state, contentResourceBundle.getFormattedMessage("dragndrop.collection.error", new Object[] { collectionName, fileName })); return; } } try { //Now upload the received file //Test that file has been sent in request DiskFileItem uploadFile = (DiskFileItem) request.getAttribute("file"); if (uploadFile != null) { String contentType = uploadFile.getContentType(); uploadFileName = uploadFile.getName(); String extension = ""; String basename = uploadFileName.trim(); if (uploadFileName.contains(".")) { String[] parts = uploadFileName.split("\\."); basename = parts[0]; if (parts.length > 1) { extension = parts[parts.length - 1]; } for (int i = 1; i < parts.length - 1; i++) { basename += "." + parts[i]; } } if (collection != null) { logger.debug("Adding resource " + uploadFileName + " in collection " + collection.getId()); resource = ContentHostingService.addResource(collection.getId(), Validator.escapeResourceName(basename), Validator.escapeResourceName(extension), 5); } else { //Method getUniqueFileName was added to change external name of uploaded resources if they exist already in the collection, just the same way that their internal id. //However, that is not the way Resources tool works. Internal id is changed but external name is the same for every copy of the same file. //So I disable this method call, though it can be enabled again if desired. //String resourceName = getUniqueFileName(uploadFileName, resourceGroup); logger.debug( "Adding resource " + uploadFileName + " in current folder (" + resourceGroup + ")"); resource = ContentHostingService.addResource(resourceGroup, Validator.escapeResourceName(basename), Validator.escapeResourceName(extension), 5); } if (resource != null) { if (contentType != null) resource.setContentType(contentType); ResourcePropertiesEdit resourceProps = resource.getPropertiesEdit(); resourceProps.addProperty(ResourcePropertiesEdit.PROP_DISPLAY_NAME, uploadFileName); resource.setContent(uploadFile.getInputStream()); resource.setContentType(contentType); ContentHostingService.commitResource(resource, NotificationService.NOTI_NONE); if (collection != null) { ContentHostingService.commitCollection(collection); logger.debug("Collection commited: " + collection.getId()); } } else { addAlert(state, contentResourceBundle.getFormattedMessage("dragndrop.upload.error", new Object[] { uploadFileName })); return; } } else { addAlert(state, contentResourceBundle.getFormattedMessage("dragndrop.upload.error", new Object[] { uploadFileName })); return; } } catch (IdUniquenessException e) { addAlert(state, contentResourceBundle.getFormattedMessage("dragndrop.duplicated.error", new Object[] { uploadFileName, ResourcesAction.MAXIMUM_ATTEMPTS_FOR_UNIQUENESS })); return; } catch (OverQuotaException e) { addAlert(state, rb.getString("alert.over-site-upload-quota")); logger.warn("Drag and drop upload exceeded site quota: " + e, e); return; } catch (ServerOverloadException e) { addAlert(state, contentResourceBundle.getFormattedMessage("dragndrop.overload.error", new Object[] { uploadFileName })); logger.warn("Drag and drop upload overloaded the server: " + e, e); return; } catch (Exception e) { addAlert(state, contentResourceBundle.getFormattedMessage("dragndrop.upload.error", new Object[] { uploadFileName })); logger.warn("Drag and drop upload failed: " + e, e); return; } try { //Set an i18n OK message for successfully uploaded files. This message is captured by client side and written in the files of Dropzone. response.setContentType("text/plain"); response.setStatus(200); PrintWriter pw = response.getWriter(); pw.write(contentResourceBundle.getString("dragndrop.success.upload")); pw.flush(); pw.close(); } catch (Exception e) { logger.error("Exception writing response in ResourcesHelperAction"); return; } addFilenameReferenceToList(state, resource.getReference()); toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE); }