List of usage examples for org.apache.commons.fileupload FileItem getContentType
String getContentType();
null
if not defined. From source file:org.activiti.rest.api.legacy.TaskAttachmentAddResource.java
@Put public AttachmentResponse addAttachment(Representation entity) { if (authenticate() == false) return null; String taskId = (String) getRequest().getAttributes().get("taskId"); try {/* w w w.jav a2 s. c om*/ RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory()); List<FileItem> items = upload.parseRepresentation(entity); FileItem uploadItem = null; for (FileItem fileItem : items) { if (fileItem.getName() != null) { uploadItem = fileItem; } } String fileName = uploadItem.getName(); Attachment attachment = ActivitiUtil.getTaskService().createAttachment(uploadItem.getContentType(), taskId, null, fileName, fileName, uploadItem.getInputStream()); return new AttachmentResponse(attachment); } catch (Exception e) { if (e instanceof ActivitiException) { throw (ActivitiException) e; } throw new ActivitiException("Unable to add new attachment to task " + taskId); } }
From source file:org.activiti.rest.api.task.TaskAttachmentAddResource.java
@Put public AttachmentResponse addAttachment(Representation entity) { if (authenticate() == false) return null; String taskId = (String) getRequest().getAttributes().get("taskId"); try {//from w w w. j av a 2 s . c o m RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory()); List<FileItem> items = upload.parseRepresentation(entity); FileItem uploadItem = null; for (FileItem fileItem : items) { if (fileItem.getName() != null) { uploadItem = fileItem; } } String fileName = uploadItem.getName(); Attachment attachment = ActivitiUtil.getTaskService().createAttachment(uploadItem.getContentType(), taskId, null, fileName, fileName, uploadItem.getInputStream()); return new AttachmentResponse(attachment); } catch (Exception e) { throw new ActivitiException("Unable to add new attachment to task " + taskId); } }
From source file:org.activityinfo.server.attachment.AppEngineAttachmentService.java
@Override public void upload(String key, FileItem fileItem, InputStream uploadingStream) { try {//from w w w . j a v a 2s .c om GSFileOptionsBuilder builder = new GSFileOptionsBuilder().setBucket("activityinfo-attachments") .setKey(key).setContentDisposition("attachment; filename=\"" + fileItem.getName() + "\"") .setMimeType(fileItem.getContentType()); FileService fileService = FileServiceFactory.getFileService(); AppEngineFile writableFile = fileService.createNewGSFile(builder.build()); boolean lock = true; FileWriteChannel writeChannel = fileService.openWriteChannel(writableFile, lock); OutputStream os = Channels.newOutputStream(writeChannel); ByteStreams.copy(fileItem.getInputStream(), os); os.flush(); writeChannel.closeFinally(); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.activityinfo.server.attachment.AttachmentServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from w ww . ja v a 2 s .c o m*/ String key = request.getParameter("blobId"); Integer siteId = Integer.valueOf(request.getParameter("siteId")); FileItem fileItem = getFirstUploadFile(request); String fileName = fileItem.getName(); InputStream uploadingStream = fileItem.getInputStream(); service.upload(key, fileItem, uploadingStream); CreateSiteAttachment siteAttachment = new CreateSiteAttachment(); siteAttachment.setSiteId(siteId); siteAttachment.setBlobId(key); siteAttachment.setFileName(fileName); siteAttachment.setBlobSize(fileItem.getSize()); siteAttachment.setContentType(fileItem.getContentType()); dispatcher.execute(siteAttachment); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Error handling upload", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:org.aeroivr.rsmc.web.controller.SetVoiceXMLApplicationPageController.java
@Override protected void pagePost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final SetVoiceXMLApplicationView view = ServiceLocator.getInstance() .getSetVoiceXMLApplicationView(getViewsFolder()); try {/*from w w w. ja v a 2 s. c o m*/ final ServletFileUpload upload = ServiceLocator.getInstance().getServletFileUpload(); final List<FileItem> items = upload.parseRequest(request); FileItem fileItem = null; for (final FileItem item : items) { if (!item.isFormField()) { fileItem = item; break; } } if (null == fileItem) { setError("WAR file should be uploaded"); } else { if (0 == fileItem.getContentType().compareTo("application/x-zip-compressed")) { try { processUploadedFile(fileItem); } catch (final Exception ex) { throw new ServletException("Error occured during " + "file upload", ex); } } else { setError("You should upload WAR type of file"); } } } catch (final FileUploadException ex) { setError("File upload error: " + ex.getMessage()); } renderView(request, response, view); }
From source file:org.aeroivr.rsmc.web.controller.SetVoiceXMLApplicationPageControllerTest.java
public void testPagePostWithFile() throws Exception { PagePostTestParameters<SetVoiceXMLApplicationPageController> testParams = new PagePostTestParameters<SetVoiceXMLApplicationPageController>(); pagePostInitTest(SetVoiceXMLApplicationPageController.class, testParams); testParams.getResponseMock().getWriter(); expectLastCall().andReturn(testParams.getPrintWriterMock()).once(); final ServletFileUpload servletFileUploadMock = testParams.getControl().createMock(ServletFileUpload.class); final List<FileItem> fileItems = new ArrayList<FileItem>(); FileItem fileItemMock = testParams.getControl().createMock(FileItem.class); final File fileMock = testParams.getControl().createMock(File.class); final File webAppFolderMock = testParams.getControl().createMock(File.class); fileItems.add(fileItemMock);/*from w w w .j a va2s .c om*/ testParams.getServiceLocatorMock().getServletFileUpload(); expectLastCall().andReturn(servletFileUploadMock).once(); servletFileUploadMock.parseRequest(testParams.getRequestMock()); expectLastCall().andReturn(fileItems).once(); fileItemMock.isFormField(); expectLastCall().andReturn(false).once(); fileItemMock.getContentType(); expectLastCall().andReturn("application/x-zip-compressed").once(); testParams.getControllerMock().getServletContext(); expectLastCall().andReturn(testParams.getServletContextMock()).once(); testParams.getServletContextMock().getRealPath(eq("/")); expectLastCall().andReturn(null).atLeastOnce(); testParams.getServiceLocatorMock().getTempFileWithUniqueName("temp_", ".war"); expectLastCall().andReturn(fileMock).once(); testParams.getServiceLocatorMock().getFile(null); expectLastCall().andReturn(webAppFolderMock).once(); webAppFolderMock.getParent(); expectLastCall().andReturn("/").once(); testParams.getControl().replay(); ServiceLocator.load(testParams.getServiceLocatorMock()); testParams.getControllerMock().doPost(testParams.getRequestMock(), testParams.getResponseMock()); testParams.getControl().verify(); }
From source file:org.alfresco.web.app.servlet.JBPMDeployProcessServlet.java
/** * Retrieve the JBPM Process Designer deployment archive from the request * //from w w w . ja v a 2s . co 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.hupa.server.utils.TestUtils.java
/** * Creates a client side mock smtp message. * It is possible to say the number of attachments we want. * * @param registry//from www . java2 s . com * @param nfiles * @return * @throws AddressException * @throws MessagingException * @throws IOException */ public static SmtpMessage createMockSMTPMessage(FileItemRegistry registry, int nfiles) throws AddressException, MessagingException, IOException { ArrayList<MessageAttachment> attachments = new ArrayList<MessageAttachment>(); for (int i = 1; i <= nfiles; i++) { FileItem fileItem; fileItem = TestUtils.createMockFileItem("uploadedFile_" + i + ".bin"); registry.add(fileItem); MessageAttachment msgAttach = new MessageAttachmentImpl(); msgAttach.setName(fileItem.getFieldName()); msgAttach.setContentType(fileItem.getContentType()); msgAttach.setSize((int) fileItem.getSize()); attachments.add(msgAttach); } SmtpMessage smtpMessage = new SmtpMessageImpl(); smtpMessage.setFrom("Test user <from@dom.com>"); smtpMessage.setTo(Arrays.asList("to@dom.com")); smtpMessage.setCc(Arrays.asList("cc@dom.com")); smtpMessage.setBcc(Arrays.asList("bcc@dom.com")); smtpMessage.setSubject("Subject"); smtpMessage.setText("<div>Body</div>"); smtpMessage.setMessageAttachments(attachments); return smtpMessage; }
From source file:org.apache.jackrabbit.demo.blog.servlet.BlogAddControllerServlet.java
/** * This methods handles POST requests and adds the blog entries according to the parameters in the * request. Request must be multi-part encoded. */// w ww . j av a2s . c om protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List parameters = null; String title = null; String content = null; FileItem image = null; FileItem video = null; // Check whether the request is multipart encoded if (ServletFileUpload.isMultipartContent(request)) { DefaultFileItemFactory fileItemFactory = new DefaultFileItemFactory(); ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory); try { // Parse the request and get the paramter set parameters = fileUpload.parseRequest(request); Iterator paramIter = parameters.iterator(); // Resolve the parameter set while (paramIter.hasNext()) { FileItem item = (FileItem) paramIter.next(); if (item.getFieldName().equalsIgnoreCase("title")) { title = item.getString(); } else if (item.getFieldName().equalsIgnoreCase("content")) { content = item.getString(); } else if (item.getFieldName().equalsIgnoreCase("image")) { image = item; } else if (item.getFieldName().equalsIgnoreCase("video")) { video = item; } } } catch (FileUploadException e) { throw new ServletException("Error occured in processing the multipart request", e); } } else { throw new ServletException("Request is not a multi-part encoded request"); } try { //log in to the repository and aquire a session Session session = repository.login(new SimpleCredentials("username", "password".toCharArray())); String username = (String) request.getSession().getAttribute("username"); // Only logged in users are allowed to create blog entries if (username == null) { //set the attributes which are required by user messae page request.setAttribute("msgTitle", "Authentication Required"); request.setAttribute("msgBody", "Only logged in users are allowed to add blog entries."); request.setAttribute("urlText", "go back to login page"); request.setAttribute("url", "/jackrabbit-jcr-demo/blog/index.jsp"); //forward the request to user massage page RequestDispatcher requestDispatcher = this.getServletContext() .getRequestDispatcher("/blog/userMessage.jsp"); requestDispatcher.forward(request, response); return; } Node blogRootNode = session.getRootNode().getNode("blogRoot"); Node userNode = blogRootNode.getNode(username); // Node to hold the current year Node yearNode; // Node to hold the current month Node monthNode; // Node to hold the blog entry to be added Node blogEntryNode; // Holds the name of the blog entry node String nodeName; // createdOn property of the blog entry is set to the current time. Calendar calendar = Calendar.getInstance(); String year = calendar.get(Calendar.YEAR) + ""; String month = calendar.get(Calendar.MONTH) + ""; // check whether node exists for current year under usernode and creates a one if not exist if (userNode.hasNode(year)) { yearNode = userNode.getNode(year); } else { yearNode = userNode.addNode(year, "nt:folder"); } // check whether node exists for current month under the current year and creates a one if not exist if (yearNode.hasNode(month)) { monthNode = yearNode.getNode(month); } else { monthNode = yearNode.addNode(month, "nt:folder"); } if (monthNode.hasNode(title)) { nodeName = createUniqueName(title, monthNode); } else { nodeName = title; } // creates a blog entry under the current month blogEntryNode = monthNode.addNode(nodeName, "blog:blogEntry"); blogEntryNode.setProperty("blog:title", title); blogEntryNode.setProperty("blog:content", content); Value date = session.getValueFactory().createValue(Calendar.getInstance()); blogEntryNode.setProperty("blog:created", date); blogEntryNode.setProperty("blog:rate", 0); // If the blog entry has an image if (image.getSize() > 0) { if (image.getContentType().startsWith("image")) { Node imageNode = blogEntryNode.addNode("image", "nt:file"); Node contentNode = imageNode.addNode("jcr:content", "nt:resource"); contentNode.setProperty("jcr:data", image.getInputStream()); contentNode.setProperty("jcr:mimeType", image.getContentType()); contentNode.setProperty("jcr:lastModified", date); } else { session.refresh(false); //set the attributes which are required by user messae page request.setAttribute("msgTitle", "Unsupported image format"); request.setAttribute("msgBody", "The image you attached in not supported"); request.setAttribute("urlText", "go back to new blog entry page"); request.setAttribute("url", "/jackrabbit-jcr-demo/blog/addBlogEntry.jsp"); //forward the request to user massage page RequestDispatcher requestDispatcher = this.getServletContext() .getRequestDispatcher("/blog/userMessage.jsp"); requestDispatcher.forward(request, response); return; } } // If the blog entry has a video if (video.getSize() > 0) { if (video.getName().endsWith(".flv") || video.getName().endsWith(".FLV")) { Node imageNode = blogEntryNode.addNode("video", "nt:file"); Node contentNode = imageNode.addNode("jcr:content", "nt:resource"); contentNode.setProperty("jcr:data", video.getInputStream()); contentNode.setProperty("jcr:mimeType", video.getContentType()); contentNode.setProperty("jcr:lastModified", date); } else { session.refresh(false); //set the attributes which are required by user messae page request.setAttribute("msgTitle", "Unsupported video format"); request.setAttribute("msgBody", "Only Flash videos (.flv) are allowed as video attachement. click <a href=\"www.google.com\">here</a> to covert the videos online."); request.setAttribute("urlText", "go back to new blog entry page"); request.setAttribute("url", "/jackrabbit-jcr-demo/blog/addBlogEntry.jsp"); //forward the request to user massage page RequestDispatcher requestDispatcher = this.getServletContext() .getRequestDispatcher("/blog/userMessage.jsp"); requestDispatcher.forward(request, response); return; } } // persist the changes done session.save(); //set the attributes which are required by user messae page request.setAttribute("msgTitle", "Blog entry added succesfully"); request.setAttribute("msgBody", "Blog entry titled \"" + title + "\" was successfully added to your blog space"); request.setAttribute("urlText", "go back to my blog page"); request.setAttribute("url", "/jackrabbit-jcr-demo/blog/view"); //forward the request to user massage page RequestDispatcher requestDispatcher = this.getServletContext() .getRequestDispatcher("/blog/userMessage.jsp"); requestDispatcher.forward(request, response); } catch (RepositoryException e) { throw new ServletException("Repository error occured", e); } finally { if (session != null) { session.logout(); } } }
From source file:org.apache.myfaces.custom.fileupload.HtmlFileUploadRendererTest.java
public void testUploadedFileDefaultMemoryImplSerializable() throws Exception { String fieldName = "inputFile"; String contentType = "someType"; MockControl control = MockControl.createControl(FileItem.class); FileItem item = (FileItem) control.getMock(); item.getName();/* ww w .j ava 2 s. c om*/ control.setReturnValue(fieldName, 1); item.getContentType(); control.setReturnValue(contentType, 1); item.getSize(); control.setReturnValue(0, 1); item.getInputStream(); control.setReturnValue(new InputStream() { public int read() throws IOException { return -1; } }, 1); item.delete(); control.setVoidCallable(1); control.replay(); UploadedFileDefaultMemoryImpl original = new UploadedFileDefaultMemoryImpl(item); ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(original); oos.close(); byte[] serializedArray = out.toByteArray(); InputStream in = new ByteArrayInputStream(serializedArray); ObjectInputStream ois = new ObjectInputStream(in); UploadedFileDefaultMemoryImpl copy = (UploadedFileDefaultMemoryImpl) ois.readObject(); assertEquals(original.getName(), copy.getName()); assertEquals(original.getContentType(), copy.getContentType()); assertEquals(copy.getSize(), 0); copy.getStorageStrategy().deleteFileContents(); }