List of usage examples for org.apache.commons.fileupload FileItem getInputStream
InputStream getInputStream() throws IOException;
From source file:onlinefrontlines.utils.UploadedImageManager.java
/** * Add image from http request//from w w w . ja v a 2 s.c o m * * @param prefix Prefix for the image * @param id Id for the image * @param request Request that contains the image data * @param width Max with for the image * @param height Max height for the image * @throws AddException */ @SuppressWarnings("unchecked") public void addImage(String prefix, int id, HttpServletRequest request, int width, int height) throws AddException { try { // Get files from request DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(MAX_FILE_SIZE); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(MAX_FILE_SIZE); List<FileItem> items = (List<FileItem>) upload.parseRequest(request); // Find correct attachment for (FileItem item : items) if (!item.isFormField()) { // Skip file uploads that don't have a file name - meaning that no file was selected. if (item.getName() == null || item.getName().trim().length() < 1) continue; try { // Read image to see if it is correct InputStream is = item.getInputStream(); try { BufferedImage image = ImageIO.read(is); if (image == null) throw new AddException("imageCorrupt"); if (image.getHeight() != height || image.getWidth() != width) throw new AddException("invalidResolution"); } finally { is.close(); } // Add the image is = item.getInputStream(); try { addImage(prefix, id, is, item.getContentType()); } finally { is.close(); } break; } catch (IOException e) { throw new AddException("imageCorrupt"); } } } catch (FileUploadException e) { throw new AddException("failedFileUpload"); } }
From source file:OpenProdocServ.ImpElemF.java
/** * * @param Req//w w w.j a va2 s. c om * @throws Exception */ @Override protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception { String FileName = null; InputStream FileData = null; try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000000); ServletFileUpload upload = new ServletFileUpload(factory); boolean isMultipart = ServletFileUpload.isMultipartContent(Req); List items = upload.parseRequest(Req); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { FileName = item.getName(); FileData = item.getInputStream(); break; } } DriverGeneric PDSession = SParent.getSessOPD(Req); DocumentBuilder DB = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document XMLObjects = DB.parse(FileData); NodeList OPDObjectList = XMLObjects.getElementsByTagName(ObjPD.XML_OPDObject); Node OPDObject; ObjPD Obj2Build; int Tot = 0; for (int i = 0; i < OPDObjectList.getLength(); i++) { OPDObject = OPDObjectList.item(i); Obj2Build = PDSession.BuildObj(OPDObject); Obj2Build.ProcesXMLNode(OPDObject); Tot++; } DB.reset(); out.println(UpFileStatus.SetResultOk(Req, "Total=" + Tot)); FileData.close(); } catch (Exception e) { out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage())); throw e; } }
From source file:OpenProdocServ.ImportDocF.java
/** * * @param Req//from w ww. jav a2s .c o m * @throws Exception */ @Override protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception { String FileName = null; InputStream FileData = null; HashMap<String, String> ListFields = new HashMap(); try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000000); ServletFileUpload upload = new ServletFileUpload(factory); boolean isMultipart = ServletFileUpload.isMultipartContent(Req); List items = upload.parseRequest(Req); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) ListFields.put(item.getFieldName(), item.getString()); else { FileName = item.getName(); FileData = item.getInputStream(); } } if (!isMultipart || FileData == null) { out.println("KO"); } else { ListFields = GetDat(Req); PDDocs Doc; DriverGeneric PDSession = getSessOPD(Req); String DType = (String) ListFields.get(PDDocs.fDOCTYPE); if (DType == null) Doc = new PDDocs(PDSession); else Doc = new PDDocs(PDSession, DType); Record Rec = Doc.getRecSum(); Rec.initList(); Attribute Attr = Rec.nextAttr(); while (Attr != null) { if (!List.contains(Attr.getName())) { String Val = (String) ListFields.get(Attr.getName()); if (Attr.getType() == Attribute.tBOOLEAN) { if (Val == null || Val.length() == 0 || Val.equals("0")) Attr.setValue(false); else Attr.setValue(true); } else if (Val != null) { SParent.FillAttr(Req, Attr, Val, false); } } Attr = Rec.nextAttr(); } Doc.assignValues(Rec); Doc.setParentId(ListFields.get("CurrFold")); Doc.setName(FileName); PDMimeType mt = new PDMimeType(PDSession); Doc.setMimeType(mt.SolveName(FileName)); Doc.setStream(FileData); Doc.insert(); out.println(UpFileStatus.SetResultOk(Req, "")); FileData.close(); } } catch (Exception e) { out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage())); throw e; } }
From source file:OpenProdocServ.ImportThesF.java
/** * * @param Req //from w w w.ja v a 2 s .c o m * @param response * @throws Exception */ protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception { String FileName = null; InputStream FileData = null; HashMap<String, String> ListFields = new HashMap(); try { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); boolean isMultipart = ServletFileUpload.isMultipartContent(Req); List items = upload.parseRequest(Req); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) ListFields.put(item.getFieldName(), item.getString()); else { FileName = item.getName(); FileData = item.getInputStream(); } } if (!isMultipart || FileData == null) { out.println("KO"); } else { ListFields = GetDat(Req); String NewThesId = ListFields.get("ThesNum"); String ThesName = ListFields.get("ThesName"); String RootText = ListFields.get("RootText"); String MainLanguage = ListFields.get("MainLanguage"); String SubByLang = ListFields.get("SubByLang"); String Transact = ListFields.get("Transact"); String RetainCodes = ListFields.get("RetainCodes"); DriverGeneric PDSession = getSessOPD(Req); PDThesaur Thes = new PDThesaur(PDSession); Thes.Import(ThesName, NewThesId, FileData, MainLanguage, RootText, SubByLang.equals("1"), Transact.equals("1"), RetainCodes.equals("1")); FileData.close(); out.println(UpFileStatus.SetResultOk(Req, Thes.getImportReport())); } } catch (Exception e) { out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage())); throw e; } }
From source file:OpenProdocServ.ModDocF.java
/** * * @param Req/*from ww w. j av a2s .com*/ * @throws Exception */ @Override protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception { String FileName = null; InputStream FileData = null; HashMap<String, String> ListFields = new HashMap(); try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000000); ServletFileUpload upload = new ServletFileUpload(factory); boolean isMultipart = ServletFileUpload.isMultipartContent(Req); List items = upload.parseRequest(Req); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) ListFields.put(item.getFieldName(), item.getString()); else { FileName = item.getName(); FileData = item.getInputStream(); } } if (!isMultipart || FileData == null) { out.println("KO"); } else { ListFields = GetDat(Req); PDDocs Doc; DriverGeneric PDSession = getSessOPD(Req); String DType = (String) ListFields.get(PDDocs.fDOCTYPE); if (DType == null) Doc = new PDDocs(PDSession); else Doc = new PDDocs(PDSession, DType); Doc.LoadFull((String) ListFields.get(PDDocs.fPDID)); Record Rec = Doc.getRecSum(); Rec.initList(); Attribute Attr = Rec.nextAttr(); while (Attr != null) { if (!List.contains(Attr.getName())) { String Val = (String) ListFields.get(Attr.getName()); if (Attr.getType() == Attribute.tBOOLEAN) { if (Val == null || Val.length() == 0 || Val.equals("0")) Attr.setValue(false); else Attr.setValue(true); } else if (Val != null) { SParent.FillAttr(Req, Attr, Val, false); } } Attr = Rec.nextAttr(); } Doc.assignValues(Rec); Doc.setParentId(ListFields.get("CurrFold")); Doc.setName(FileName); PDMimeType mt = new PDMimeType(PDSession); Doc.setMimeType(mt.SolveName(FileName)); Doc.setStream(FileData); Doc.update(); out.println(UpFileStatus.SetResultOk(Req, "")); } } catch (Exception e) { out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage())); throw e; } }
From source file:OpenProdocServ.Oper.java
/** * /*from w w w .ja v a2s .c o m*/ * @param request * @param response */ private void InsFile(HttpServletRequest Req, HttpServletResponse response) throws Exception { if (PDLog.isDebug()) PDLog.Debug("InsFile"); FileItem ItemFile = null; InputStream FileData = null; HashMap ListFields = new HashMap(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000000); ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(Req); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) ListFields.put(item.getFieldName(), item.getString()); else { FileData = item.getInputStream(); ItemFile = item; } } DriverGeneric PDSession = getSessOPD(Req); String Id = (String) ListFields.get("Id"); String Ver = (String) ListFields.get("Ver"); PDSession.InsertFile(Id, Ver, FileData); if (FileData != null) FileData.close(); if (ItemFile != null) ItemFile.delete(); items.clear(); // to help and speed gc PrintWriter out = response.getWriter(); Answer(Req, out, true, null, null); out.close(); }
From source file:org.activiti.rest.api.identity.UserPictureResource.java
@Put public void updateUserPicture(Representation representation) { User user = getUserFromRequest();/*from w w w .j ava2 s. c om*/ if (!MediaType.MULTIPART_FORM_DATA.isCompatible(representation.getMediaType())) { throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE.getCode(), "The request should be of type 'multipart/form-data'.", null, null); } RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory()); try { FileItem uploadItem = null; List<FileItem> items = upload.parseRepresentation(representation); String mimeType = MediaType.IMAGE_JPEG.toString(); for (FileItem fileItem : items) { if (fileItem.isFormField()) { if ("mimeType".equals(fileItem.getFieldName())) { mimeType = fileItem.getString("UTF-8"); } } else if (fileItem.getName() != null) { uploadItem = fileItem; } } if (uploadItem == null) { throw new ActivitiIllegalArgumentException("No file content was found in request body."); } int size = ((Long) uploadItem.getSize()).intValue(); // Copy file-body in a bytearray as the engine requires this ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream(size); IOUtils.copy(uploadItem.getInputStream(), bytesOutput); Picture newPicture = new Picture(bytesOutput.toByteArray(), mimeType); ActivitiUtil.getIdentityService().setUserPicture(user.getId(), newPicture); } catch (FileUploadException e) { throw new ActivitiException("Error with uploaded file: " + e.getMessage(), e); } catch (IOException e) { throw new ActivitiException("Error while reading uploaded file: " + e.getMessage(), e); } }
From source file:org.activiti.rest.api.legacy.deployment.DeploymentUploadResource.java
@Post public LegacyDeploymentResponse uploadDeployment(Representation entity) { try {//from w w w . j ava 2s . c o m if (authenticate(SecuredResource.ADMIN) == false) return null; 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; } } DeploymentBuilder deploymentBuilder = ActivitiUtil.getRepositoryService().createDeployment(); String fileName = uploadItem.getName(); if (fileName.endsWith(".bpmn20.xml") || fileName.endsWith(".bpmn")) { deploymentBuilder.addInputStream(fileName, uploadItem.getInputStream()); } else if (fileName.toLowerCase().endsWith(".bar") || fileName.toLowerCase().endsWith(".zip")) { deploymentBuilder.addZipInputStream(new ZipInputStream(uploadItem.getInputStream())); } else { throw new ActivitiIllegalArgumentException("File must be of type .bpmn20.xml, .bpmn, .bar or .zip"); } deploymentBuilder.name(fileName); Deployment deployment = deploymentBuilder.deploy(); setStatus(Status.SUCCESS_OK); return new LegacyDeploymentResponse(deployment); } catch (Exception e) { if (e instanceof ActivitiException) { throw (ActivitiException) e; } throw new ActivitiException(e.getMessage(), e); } }
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 {/*from ww w. j av a 2 s. co 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) { 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.process.BaseExecutionVariableResource.java
protected RestVariable setBinaryVariable(Representation representation, Execution execution, boolean isNew) { try {//from w w w .ja v a 2s. c o m RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory()); List<FileItem> items = upload.parseRepresentation(representation); String variableScope = null; String variableName = null; String variableType = null; FileItem uploadItem = null; for (FileItem fileItem : items) { if (fileItem.isFormField()) { if ("scope".equals(fileItem.getFieldName())) { variableScope = fileItem.getString("UTF-8"); } else if ("name".equals(fileItem.getFieldName())) { variableName = fileItem.getString("UTF-8"); } else if ("type".equals(fileItem.getFieldName())) { variableType = fileItem.getString("UTF-8"); } } else if (fileItem.getName() != null) { uploadItem = fileItem; } } // Validate input and set defaults if (uploadItem == null) { throw new ActivitiIllegalArgumentException("No file content was found in request body."); } if (variableName == null) { throw new ActivitiIllegalArgumentException("No variable name was found in request body."); } if (variableType != null) { if (!RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType) && !RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variableType)) { throw new ActivitiIllegalArgumentException( "Only 'binary' and 'serializable' are supported as variable type."); } } else { variableType = RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE; } RestVariableScope scope = RestVariableScope.LOCAL; if (variableScope != null) { scope = RestVariable.getScopeFromString(variableScope); } if (variableType.equals(RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE)) { // Use raw bytes as variable value ByteArrayOutputStream variableOutput = new ByteArrayOutputStream( ((Long) uploadItem.getSize()).intValue()); IOUtils.copy(uploadItem.getInputStream(), variableOutput); setVariable(execution, variableName, variableOutput.toByteArray(), scope, isNew); } else { // Try deserializing the object ObjectInputStream stream = new ObjectInputStream(uploadItem.getInputStream()); Object value = stream.readObject(); setVariable(execution, variableName, value, scope, isNew); stream.close(); } if (execution instanceof ProcessInstance) { return getApplication(ActivitiRestServicesApplication.class).getRestResponseFactory() .createBinaryRestVariable(this, variableName, scope, variableType, null, null, execution.getId()); } else { return getApplication(ActivitiRestServicesApplication.class).getRestResponseFactory() .createBinaryRestVariable(this, variableName, scope, variableType, null, execution.getId(), null); } } catch (FileUploadException fue) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, fue); } catch (IOException ioe) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, ioe); } catch (ClassNotFoundException ioe) { throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE.getCode(), "The provided body contains a serialized object for which the class is nog found: " + ioe.getMessage(), null, null); } }