List of usage examples for org.apache.commons.fileupload FileUploadException FileUploadException
public FileUploadException(String msg)
FileUploadException
with specified detail message. From source file:com.alibaba.citrus.service.upload.impl.cfu.AbstractFileItem.java
/** * A convenience method to write an uploaded item to disk. The client code * is not concerned with whether or not the item is stored in memory, or on * disk in a temporary location. They just want to write the uploaded item * to a file.//w ww. j av a2 s . co m * <p/> * This implementation first attempts to rename the uploaded item to the * specified destination file, if the item was originally written to disk. * Otherwise, the data will be copied to the specified file. * <p/> * This method is only guaranteed to work <em>once</em>, the first time it * is invoked for a particular item. This is because, in the event that the * method renames a temporary file, that file will no longer be available to * copy or rename again at a later time. * * @param file The <code>File</code> into which the uploaded item should be * stored. * @throws Exception if an error occurs. */ public void write(File file) throws Exception { // if (file != null) { file.getParentFile().mkdirs(); } if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { // Save the length of the file size = outputFile.length(); /* * The uploaded file is being stored on disk in a temporary * location so move it to the desired file. */ if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(outputFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } if (out != null) { try { out.close(); } catch (IOException e) { // ignore } } } } } else { /* * For whatever reason we cannot write the file to disk. */ throw new FileUploadException("Cannot write uploaded file to disk!"); } } }
From source file:com.buddycloud.mediaserver.business.dao.MediaDAO.java
/** * Uploads media from web form./* w ww. jav a 2 s. com*/ * @param userId user that is uploading the media. * @param entityId channel where the media will belong. * @param form web form containing the media. * @param isAvatar if the media to be uploaded is an avatar. * @return media's metadata, if the upload ends with success * @throws FileUploadException the is something wrong with the request. * @throws UserNotAllowedException the user {@link userId} is now allowed to upload media in this channel. */ public String insertWebFormMedia(String userId, String entityId, Form form, boolean isAvatar) throws FileUploadException, UserNotAllowedException { LOGGER.debug("User '" + userId + "' trying to upload web-form media on: " + entityId); boolean isUserAllowed = pubsub.matchUserCapability(userId, entityId, new OwnerDecorator(new ModeratorDecorator(new PublisherDecorator()))); if (!isUserAllowed) { LOGGER.debug("User '" + userId + "' not allowed to uploade file on: " + entityId); throw new UserNotAllowedException(userId); } // get form fields String fileName = form.getFirstValue(Constants.NAME_FIELD); String title = form.getFirstValue(Constants.TITLE_FIELD); String description = form.getFirstValue(Constants.DESC_FIELD); String data = form.getFirstValue(Constants.DATA_FIELD); if (data == null) { throw new FileUploadException("Must provide the file data."); } byte[] dataArray = Base64.decode(data); String contentType = form.getFirstValue(Constants.TYPE_FIELD); if (contentType == null) { throw new FileUploadException("Must provide a " + Constants.TYPE_FIELD + " for the uploaded file."); } // storing Media media = storeMedia(fileName, title, description, XMPPUtils.getBareId(userId), entityId, contentType, dataArray, isAvatar); LOGGER.debug("Media sucessfully added. Media ID: " + media.getId()); return gson.toJson(media); }
From source file:com.buddycloud.mediaserver.business.dao.MediaDAO.java
/** * Uploads media./*ww w. j a va 2s . co m*/ * @param userId user that is uploading the media. * @param entityId channel where the media will belong. * @param request media file and required upload fields. * @param isAvatar if the media to be uploaded is an avatar. * @return media's metadata, if the upload ends with success * @throws FileUploadException the is something wrong with the request. * @throws UserNotAllowedException the user {@link userId} is now allowed to upload media in this channel. */ public String insertFormDataMedia(String userId, String entityId, Request request, boolean isAvatar) throws FileUploadException, UserNotAllowedException { LOGGER.debug("User '" + userId + "' trying to upload form-data media in: " + entityId); boolean isUserAllowed = pubsub.matchUserCapability(userId, entityId, new OwnerDecorator(new ModeratorDecorator(new PublisherDecorator()))); if (!isUserAllowed) { LOGGER.debug("User '" + userId + "' not allowed to upload file in: " + entityId); throw new UserNotAllowedException(userId); } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold( Integer.valueOf(configuration.getProperty(MediaServerConfiguration.MEDIA_SIZE_LIMIT_PROPERTY))); List<FileItem> items = null; try { RestletFileUpload upload = new RestletFileUpload(factory); items = upload.parseRequest(request); } catch (Throwable e) { throw new FileUploadException("Invalid request data."); } // get form fields String fileName = getFormFieldContent(items, Constants.NAME_FIELD); String title = getFormFieldContent(items, Constants.TITLE_FIELD); String description = getFormFieldContent(items, Constants.DESC_FIELD); String contentType = getFormFieldContent(items, Constants.TYPE_FIELD); FileItem fileField = getFileFormField(items); if (fileField == null) { throw new FileUploadException("Must provide the file data."); } byte[] dataArray = fileField.get(); if (contentType == null) { if (fileField.getContentType() != null) { contentType = fileField.getContentType(); } else { throw new FileUploadException("Must provide a " + Constants.TYPE_FIELD + " for the uploaded file."); } } // storing Media media = storeMedia(fileName, title, description, XMPPUtils.getBareId(userId), entityId, contentType, dataArray, isAvatar); LOGGER.debug("Media sucessfully added. Media ID: " + media.getId()); return gson.toJson(media); }
From source file:com.buddycloud.mediaserver.business.dao.MediaDAO.java
protected Media storeMedia(String fileName, String title, String description, String author, String entityId, String mimeType, byte[] data, final boolean isAvatar) throws FileUploadException { String directory = getDirectory(entityId); mkdir(directory);/* ww w . j a va 2 s . c o m*/ // TODO assert id uniqueness String mediaId = RandomStringUtils.randomAlphanumeric(20); String filePath = directory + File.separator + mediaId; File file = new File(filePath); LOGGER.debug("Storing new media: " + file.getAbsolutePath()); try { FileOutputStream out = FileUtils.openOutputStream(file); out.write(data); out.close(); } catch (IOException e) { LOGGER.error("Error while storing file: " + filePath, e); throw new FileUploadException(e.getMessage()); } final Media media = createMedia(mediaId, fileName, title, description, author, entityId, mimeType, file, isAvatar); // store media's metadata new Thread() { public void start() { try { dataSource.storeMedia(media); if (isAvatar) { if (dataSource.getEntityAvatarId(media.getEntityId()) != null) { dataSource.updateEntityAvatar(media.getEntityId(), media.getId()); } else { dataSource.storeAvatar(media); } } } catch (MetadataSourceException e) { // do nothing LOGGER.error("Database error", e); } } }.start(); return media; }
From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java
public void uploadCustomReportTemplate(HttpServletRequest request, BaseReportInfo report, String templateName, List<FileItem> multipartItems) throws DisallowedException, ObjectNotFoundException, CantDoThatException, FileUploadException { if (!(this.authManager.getAuthenticator().loggedInUserAllowedTo(request, PrivilegeType.VIEW_TABLE_DATA, report.getParentTable()))) { throw new DisallowedException(this.authManager.getLoggedInUser(request), PrivilegeType.VIEW_TABLE_DATA, report.getParentTable()); }/* w w w . j a va 2s . co m*/ if (!FileUpload.isMultipartContent(new ServletRequestContext(request))) { throw new CantDoThatException("To upload a template, the form must be posted as multi-part form data"); } CompanyInfo company = this.getAuthManager().getCompanyForLoggedInUser(request); // strip extension String rinsedFileName = templateName.toLowerCase().replaceAll("\\..*$", ""); rinsedFileName = Helpers.rinseString(rinsedFileName).replace(" ", "_"); String uploadFolderName = this.getDataManagement().getWebAppRoot() + "WEB-INF/templates/uploads/" + company.getInternalCompanyName() + "/" + report.getInternalReportName(); File uploadFolder = new File(uploadFolderName); if (!uploadFolder.exists()) { if (!uploadFolder.mkdirs()) { throw new CantDoThatException("Error creating upload folder " + uploadFolderName); } } for (FileItem item : multipartItems) { // if item is a file if (!item.isFormField()) { long fileSize = item.getSize(); if (fileSize == 0) { throw new CantDoThatException("An empty file was submitted, no upload done"); } String filePath = uploadFolderName + "/" + rinsedFileName + ".vm"; File selectedFile = new File(filePath); try { item.write(selectedFile); } catch (Exception ex) { // Catching a general exception?! This is because the third // party // library throws a raw exception. Not very good throw new FileUploadException("Error writing file: " + ex.getMessage()); } } } }
From source file:com.gtwm.pb.model.manageData.DataManagement.java
/** * Upload a file for a particular field in a particular record. If a file * with the same name already exists, rename the old one to avoid * overwriting. Reset the last modified time of the old one so the rename * doesn't muck this up. Maintaining the file timestamp is useful for * version history//from w ww . j a v a2s. co m */ private void uploadFile(HttpServletRequest request, FileField field, FileValue fileValue, int rowId, List<FileItem> multipartItems) throws CantDoThatException, FileUploadException { if (rowId < 0) { throw new CantDoThatException("Row ID " + rowId + " invalid"); } if (!FileUpload.isMultipartContent(new ServletRequestContext(request))) { throw new CantDoThatException("To upload a file, the form must be posted as multi-part form data"); } if (fileValue.toString().contains("/")) { throw new CantDoThatException( "Filename contains a slash character which is not allowed, no upload done"); } if (fileValue.toString().contains("'") || fileValue.toString().contains("\"")) { throw new CantDoThatException("Filename must not contain quote marks"); } // Put the file in a unique folder per row ID. // This is in the format table ID / field ID / row ID String uploadFolderName = this.getWebAppRoot() + "uploads/" + field.getTableContainingField().getInternalTableName() + "/" + field.getInternalFieldName() + "/" + rowId; File uploadFolder = new File(uploadFolderName); if (!uploadFolder.exists()) { if (!uploadFolder.mkdirs()) { throw new CantDoThatException("Error creating upload folder " + uploadFolderName); } } for (FileItem item : multipartItems) { // if item is a file if (!item.isFormField()) { long fileSize = item.getSize(); if (fileSize == 0) { throw new CantDoThatException("An empty file was submitted, no upload done"); } String filePath = uploadFolderName + "/" + fileValue.toString(); File selectedFile = new File(filePath); String extension = ""; if (filePath.contains(".")) { extension = filePath.replaceAll("^.*\\.", "").toLowerCase(); } if (selectedFile.exists()) { // rename the existing file to something else so we don't // overwrite it String basePath = filePath; int fileNum = 1; if (basePath.contains(".")) { basePath = basePath.substring(0, basePath.length() - extension.length() - 1); } String renamedFileName = basePath + "-" + fileNum; if (!extension.equals("")) { renamedFileName += "." + extension; } File renamedFile = new File(renamedFileName); while (renamedFile.exists()) { fileNum++; renamedFileName = basePath + "-" + fileNum; if (!extension.equals("")) { renamedFileName += "." + extension; } renamedFile = new File(renamedFileName); } // Keep the original timestamp long lastModified = selectedFile.lastModified(); if (!selectedFile.renameTo(renamedFile)) { throw new FileUploadException("Rename of existing file from '" + selectedFile + "' to '" + renamedFile + "' failed"); } if (!renamedFile.setLastModified(lastModified)) { throw new FileUploadException("Error setting the last modified date of " + renamedFile); } // I think a File object's name is inviolable but just in // case selectedFile = new File(filePath); } try { item.write(selectedFile); } catch (Exception ex) { // Catching a general exception?! This is because the // library throws a raw exception. Not very good throw new FileUploadException("Error writing file: " + ex.getMessage()); } // Record upload speed long requestStartTime = request.getSession().getLastAccessedTime(); float secondsToUpload = (System.currentTimeMillis() - requestStartTime) / ((float) 1000); if (secondsToUpload > 10) { // Only time reasonably long uploads otherwise we'll amplify // errors float uploadSpeed = ((float) fileSize) / secondsToUpload; this.updateUploadSpeed(uploadSpeed); } if (extension.equals("jpg") || extension.equals("jpeg") || extension.equals("png")) { // image.png -> image.png.40.png String thumb40Path = filePath + "." + 40 + "." + extension; String thumb500Path = filePath + "." + 500 + "." + extension; File thumb40File = new File(thumb40Path); File thumb500File = new File(thumb500Path); int midSize = 500; if (field.getAttachmentType().equals(AttachmentType.PROFILE_PHOTO)) { midSize = 250; } try { BufferedImage originalImage = ImageIO.read(selectedFile); int height = originalImage.getHeight(); int width = originalImage.getWidth(); // Conditional resize if ((height > midSize) || (width > midSize)) { Thumbnails.of(selectedFile).size(midSize, midSize).toFile(thumb500File); } else { FileUtils.copyFile(selectedFile, thumb500File); } // Allow files that are up to 60 px tall as long as the // width is no > 40 px Thumbnails.of(selectedFile).size(40, 60).toFile(thumb40File); } catch (IOException ioex) { throw new FileUploadException("Error generating thumbnail: " + ioex.getMessage()); } } else if (extension.equals("pdf")) { // Convert first page to PNG with imagemagick ConvertCmd convert = new ConvertCmd(); IMOperation op = new IMOperation(); op.addImage(); // Placeholder for input PDF op.resize(500, 500); op.addImage(); // Placeholder for output PNG try { // [0] means convert only first page convert.run(op, new Object[] { filePath + "[0]", filePath + "." + 500 + ".png" }); } catch (IOException ioex) { throw new FileUploadException("IO error while converting PDF to PNG: " + ioex); } catch (InterruptedException iex) { throw new FileUploadException("Interrupted while converting PDF to PNG: " + iex); } catch (IM4JavaException im4jex) { throw new FileUploadException("Problem converting PDF to PNG: " + im4jex); } } } } }
From source file:org.alfresco.web.app.servlet.JBPMDeployProcessServlet.java
/** * Retrieve the JBPM Process Designer deployment archive from the request * //from w ww. j ava 2s.c o m * @param request the request * @return the input stream onto the deployment archive * @throws WorkflowException * @throws FileUploadException * @throws IOException */ private InputStream getDeploymentArchive(HttpServletRequest request) throws FileUploadException, IOException { if (!FileUpload.isMultipartContent(request)) { throw new FileUploadException("Not a multipart request"); } GPDUpload fileUpload = new GPDUpload(); List list = fileUpload.parseRequest(request); Iterator iterator = list.iterator(); if (!iterator.hasNext()) { throw new FileUploadException("No process file in the request"); } FileItem fileItem = (FileItem) iterator.next(); if (fileItem.getContentType().indexOf("application/x-zip-compressed") == -1) { throw new FileUploadException("Not a process archive"); } return fileItem.getInputStream(); }
From source file:org.apache.axis2.builder.MultipartFormDataBuilder.java
private MultipleEntryHashMap getParameterMap(RequestContext request, String charSetEncoding) throws FileUploadException { MultipleEntryHashMap parameterMap = new MultipleEntryHashMap(); List items = parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { DiskFileItem diskFileItem = (DiskFileItem) iter.next(); boolean isFormField = diskFileItem.isFormField(); Object value;// w w w . j a v a2 s .c o m try { if (isFormField) { value = getTextParameter(diskFileItem, charSetEncoding); } else { value = getFileParameter(diskFileItem); } } catch (Exception ex) { throw new FileUploadException(ex.getMessage()); } parameterMap.put(diskFileItem.getFieldName(), value); } return parameterMap; }
From source file:org.eclipse.rtp.httpdeployer.feature.FeatureServlet.java
@Override public Document parseMultipartPostRequest(HttpServletRequest request) throws Exception { List<FileItem> files = HttpDeployerUtils.parseMultipartRequest(request); if (files.size() != 2) { throw new FileUploadException("Files not found"); }/* ww w . jav a2 s . c o m*/ InputStream repository = getRepositoryFromMultipart(files); repositoryManager.addRepository(repository); Document feature = getFeatureRequestFromMultipart(files); Document installRequest = parseRequest(feature, XmlConstants.XML_ELEMENT_FEATURE, Action.INSTALL); return installRequest; }
From source file:org.eclipse.rtp.httpdeployer.repository.RepositoryServlet.java
@Override public Document parseMultipartPostRequest(HttpServletRequest req) throws FileUploadException, IOException { RequestResults result = new RequestResults(); List<FileItem> files = HttpDeployerUtils.parseMultipartRequest(req); if (files.size() != 1) { throw new FileUploadException("File not found"); }/*from www. j a v a2s . c om*/ try { InputStream repository = files.get(0).getInputStream(); result.addResult(new RepositoryModificationResult( repositoryManager.addRepository(repository).toString(), null, Action.ADD)); } catch (InvalidRepositoryException e) { result.addResult(new RepositoryModificationResult("local", e.getMessage(), Action.ADD)); } // delete temporary files for (FileItem item : files) { item.delete(); } return result.getDocument(); }