List of usage examples for org.springframework.web.multipart MultipartFile getBytes
byte[] getBytes() throws IOException;
From source file:Controller.MessageController.java
@RequestMapping(value = "/Image/Conversation/upload", method = RequestMethod.POST) public @ResponseBody String uploadImageForConversation(@RequestParam("uploadImage") MultipartFile uploadImage, HttpSession session, @RequestParam("conversationID") String bookingID, @RequestParam("replyToTripperID") int replyToTripperID) { try {/* ww w . java 2 s . c o m*/ String path = System.getProperty("catalina.base"); File folderPackage = new File(path + "/webapps/Conversation/Upload/" + bookingID); if (!folderPackage.exists()) { folderPackage.mkdirs(); } String name = uploadImage.getOriginalFilename(); FileCopyUtils.copy(uploadImage.getBytes(), new FileOutputStream(new File(folderPackage, name))); Gson gson = new Gson(); if (session != null) { AccountSession account = (AccountSession) session.getAttribute("account"); if (providerService.isProvider(account)) { gson.toJson(messageService.sendConversationMessage( "{\"content\":\"" + "/Conversation/Upload/" + bookingID + "/" + name + "\",\"type\":\"image\",\"filename\":\"" + name + "\"}", "provider", account.getId(), Integer.valueOf(bookingID), replyToTripperID)); int tripperID; try { tripperID = messageService.getTripperIDByConversationID(Integer.valueOf(bookingID)); } catch (Exception e) { tripperID = 0; } template.convertAndSend("/topic/getUnReadConvForTripper/" + tripperID, new Greeting("{\"Type\":\"conversation\",\"conversationID\":\"" + bookingID + "\"}")); } else if (tripperService.isUser(account)) { gson.toJson(messageService.sendConversationMessage( "{\"content\":\"" + "/Conversation/Upload/" + bookingID + "/" + name + "\",\"type\":\"image\",\"filename\":\"" + name + "\"}", "tripper", account.getId(), Integer.valueOf(bookingID), replyToTripperID)); int providerID; try { providerID = messageService.getProviderIDByConversationID(Integer.valueOf(bookingID)); } catch (Exception e) { providerID = 0; } template.convertAndSend("/topic/getUnReadConvForProvider/" + providerID, new Greeting("{\"Type\":\"conversation\",\"conversationID\":\"" + bookingID + "\"}")); } template.convertAndSend("/topic/chatting/" + bookingID, new Greeting("{\"Type\":\"conversation\",\"conversationID\":\"" + bookingID + "\"}")); } return "/Conversation/Upload/" + bookingID + "/" + name; } catch (Exception e) { String content = "Function: MessageController - uploadImageForConversation\n" + "***Input***\n" + "bookingID: " + bookingID + "\n" + "**********\n" + "****Error****\n" + e.getMessage() + "\n" + "**********"; errorService.logBugWithAccount(content, session, e); return "{\"result\": \"error\"}"; } }
From source file:com.virtusa.akura.staff.controller.StaffDetailsController.java
/** * Updates the staff Details.//from w w w. ja v a 2 s .co m * * @param staff the staff. * @param model the model. * @param request the request * @return the return path. * @throws AkuraAppException AkuraAppException. * @throws IOException IOException. */ private String updateStaffDetails(Staff staff, ModelMap model, HttpServletRequest request) throws AkuraAppException, IOException { Staff staffObjDb = staffService.findStaff(staff.getStaffId()); if (staff.getMultipartFile() != null) { MultipartFile multipartFile = staff.getMultipartFile(); if (multipartFile.getSize() > 0) { staff.setPhoto(multipartFile.getBytes()); } else { if (staffObjDb.getPhoto() != null && staffObjDb.getPhoto().length > 0) { staff.setPhoto(staffObjDb.getPhoto()); } } } staffService.modifyStaff(staff); // Update end date in section head when update the date of departure. if (staff.getDateOfDeparture() != null) { updateEndDateForDepartureStaff(staff.getStaffId(), staff.getDateOfDeparture()); } // Update if user login exist for this staff. UserLogin userLogin = userService.getUserLoginByIdentificationNo(staff.getRegistrationNo()); if (userLogin != null) { userLogin.setUserIdentificationNo(staff.getRegistrationNo()); userService.updateUser(userLogin); } String message = new ErrorMsgLoader().getErrorMessage(MESSAGE_RECORD_MODIFIED); model.addAttribute(MESSAGE, message); model.addAttribute(MODEL_ATT_STAFF, staff); return loadStaffDetails(request, model, request.getSession()); }
From source file:gov.gtas.services.CaseDispositionServiceImpl.java
/** * Utility method to persist attachment to each case comment * @param file//w w w . j a v a2 s .co m * @param _tempHitsDispComments * @throws Exception */ private void populateAttachmentsToCase(MultipartFile file, HitsDispositionComments _tempHitsDispComments, Long pax_id) throws Exception { Attachment attachment = new Attachment(); //Build attachment to be added to pax Set<Attachment> _tempAttachSet = new HashSet<Attachment>(); if (_tempHitsDispComments.getAttachmentSet() != null) _tempAttachSet = _tempHitsDispComments.getAttachmentSet(); attachment.setContentType(file.getContentType()); attachment.setFilename(file.getOriginalFilename()); attachment.setName(file.getName()); byte[] bytes = file.getBytes(); Blob blob = new javax.sql.rowset.serial.SerialBlob(bytes); attachment.setContent(blob); //Grab pax to add attachment to it Passenger pax = passengerRepository.findOne(pax_id); attachment.setPassenger(pax); attachmentRepository.save(attachment); _tempAttachSet.add(attachment); _tempHitsDispComments.setAttachmentSet(_tempAttachSet); }
From source file:org.catrobat.catroid.HomeController.java
@RequestMapping(value = "/*", method = RequestMethod.POST) public String Upload(@RequestParam(value = "file", required = true) MultipartFile file, Model model, HttpServletRequest request) throws IOException { if (file == null) return home(model, request); if (!isCatrobatFile(file.getOriginalFilename())) { return error(model, "Illegal file!", "File you tried to upload is not .catrobat file. Please, upload catrobat project (e. g.\"project.catrobat\")"); }//from w w w .j a v a2 s . c o m String appFolder = request.getSession().getServletContext().getRealPath("/"); String uploadFolder = getUploadFolder(request); try { createProjectDir(appFolder, uploadFolder); } catch (UploadException e1) { return error(model, "Cannot create directory for project", "Oops, it seems we have some internal error. Please, try one more time and do mot hurry."); } String filePath = appFolder + uploadFolder + "\\" + file.getOriginalFilename(); FileOutputStream outputStream = null; try { outputStream = new FileOutputStream(new File(filePath)); outputStream.write(file.getBytes()); outputStream.close(); } catch (Exception e) { return error(model, "Cannot save file", e.getStackTrace().toString()); } setPathsToSesisionAttributes(request, appFolder, uploadFolder); ZipFile zip; try { zip = new ZipFile(filePath); zip.extractAll(appFolder + uploadFolder); } catch (ZipException e) { return error(model, "Cannot unzip project file", e.getStackTrace().toString()); } return home(model, request); }
From source file:org.openmrs.module.sdmxhddataexport.web.controller.dataelement.DataElementController.java
@RequestMapping(value = "/module/sdmxhddataexport/listDataElement.form", method = RequestMethod.POST) public String deleteDataElement(@RequestParam(value = "ids", required = false) String[] ids, @RequestParam(value = "files", required = false) MultipartFile uploadItem, HttpServletRequest request, @RequestParam(value = "upload", required = false) String upload, @RequestParam(value = "IncludeQueries", required = false) String IncludeQueries, Object command, SessionStatus status) {/*w w w . j av a2 s . co m*/ String temp = ""; HttpSession httpSession = request.getSession(); Integer dataElementId = null; System.out.println(" done " + upload); if (upload != null) { System.out.println("1st part truly done"); //FileUpload file = uploadItem; String fileName = ""; if (uploadItem != null) { fileName = uploadItem.getOriginalFilename(); System.out.println("2nd part truly done " + fileName); byte[] byteArray = null; try { byteArray = uploadItem.getBytes(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("Bad file name"); e.printStackTrace(); } String data = new String(byteArray); System.out.println("3rd part truly done " + data); XPath xpath = XPathFactory.newInstance().newXPath(); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder = null; try { builder = domFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } Document doc = null; try { doc = builder.parse(uploadItem.getInputStream()); } catch (SAXException e1) { httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Unsupported Document type is uploaded "); //or we can use httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "sdmxhddataexport.UploadedFile.Wrong" ); return "redirect:/module/sdmxhddataexport/listDataElement.form"; } catch (IOException e1) { // TODO Auto-generated catch block httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "error in reading Document type "); //e1.printStackTrace(); } XPathExpression expr = null; XPathExpression exprDesc = null; XPathExpression exprQuery = null; try { expr = xpath.compile( "//*[local-name(.)='CodeList' and @id='CL_DATAELEMENT']/*[local-name(.)='Code']"); exprDesc = xpath.compile("//[local-name(.)='Description']"); exprQuery = xpath.compile("//[local-name(.)='Query']"); } catch (XPathExpressionException e) { httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Error parsing document "); } Object result = null; try { result = expr.evaluate(doc, XPathConstants.NODESET); } catch (XPathExpressionException e) { httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Error parsing document "); // e.printStackTrace(); } NodeList nodes = (NodeList) result; ArrayList<DataElement> dataElements = new ArrayList<DataElement>(); for (int i = 0; i < nodes.getLength(); i++) { boolean putItIn = false; DataElement de = new DataElement(); System.out.println(nodes.item(i).getLocalName()); NamedNodeMap nmp = nodes.item(i).getAttributes(); System.out.println(nmp.getNamedItem("value").getNodeValue() + " hellooo.."); de.setCode(nmp.getNamedItem("value").getNodeValue()); //Node tempNode = (Node)nodes.item(i); NodeList innerNodeList = nodes.item(i).getChildNodes(); System.out.println("length: " + innerNodeList.getLength()); for (int j = 0; j < innerNodeList.getLength(); j++) { if (innerNodeList.item(j).getLocalName() != null) { System.out.println("hehe " + innerNodeList.item(j).getLocalName()); if (innerNodeList.item(j).getLocalName().equals(new String("Description"))) { System.out.println("Description: " + innerNodeList.item(j).getTextContent()); de.setName(innerNodeList.item(j).getTextContent()); putItIn = true; } if (innerNodeList.item(j).getLocalName().equals(new String("Query")) && IncludeQueries != null) { System.out.println("Query: " + innerNodeList.item(j).getTextContent()); de.setSqlQuery(innerNodeList.item(j).getTextContent()); } } } if (putItIn) { boolean bool; DataElementValidator valid = new DataElementValidator(); bool = valid.fileValidate(de); if (bool == true) dataElements.add(de); } } ListIterator<DataElement> li = dataElements.listIterator(); DataElement de; while (li.hasNext()) { de = (DataElement) li.next(); System.out.println("Element 1 = " + de.getName()); de.setCreatedOn(new java.util.Date()); de.setCreatedBy(Context.getAuthenticatedUser().getGivenName()); SDMXHDDataExportService sDMXHDDataExportService = Context .getService(SDMXHDDataExportService.class); sDMXHDDataExportService.saveDataElement(de); } status.setComplete(); } return "redirect:/module/sdmxhddataexport/listDataElement.form"; } try { SDMXHDDataExportService sDMXHDDataExportService = Context.getService(SDMXHDDataExportService.class); if (ids != null && ids.length > 0) { for (String sId : ids) { dataElementId = Integer.parseInt(sId); if (dataElementId != null && dataElementId > 0 && CollectionUtils.isEmpty( sDMXHDDataExportService.listReportDataElement(null, dataElementId, null, 0, 1))) { sDMXHDDataExportService .deleteDataElement(sDMXHDDataExportService.getDataElementById(dataElementId)); } else { //temp += "We can't delete store="+store.getName()+" because that store is using please check <br/>"; temp = "This dataElement cannot be deleted as it is in use"; } } } } catch (Exception e) { httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Can not delete dataElement "); log.error(e); } httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, StringUtils.isBlank(temp) ? "sdmxhddataexport.dataElement.deleted" : temp); return "redirect:/module/sdmxhddataexport/listDataElement.form"; }
From source file:com.siblinks.ws.service.impl.ArticleServiceImpl.java
/** * {@inheritDoc}//from w w w .j a v a2 s. co m * */ @Override @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) @ResponseBody public ResponseEntity<Response> uploadFile(@RequestParam("uploadfile") final MultipartFile uploadfile) throws IOException { SimpleResponse reponse = null; BufferedOutputStream stream = null; try { String directory = ReadProperties.getProperties("directoryImageArticle"); String name = uploadfile.getContentType(); boolean status = name.contains("image"); if (directory != null && status) { RandomString randomName = new RandomString(); String filename = randomName.random(); String filepath = Paths.get(directory, filename + ".png").toString(); // Save the file locally stream = new BufferedOutputStream(new FileOutputStream(new File(filepath))); stream.write(uploadfile.getBytes()); reponse = new SimpleResponse(SibConstants.SUCCESS, filepath); } else { reponse = new SimpleResponse(SibConstants.FAILURE, "Your photos couldn't be uploaded. Photos should be saved as JPG, PNG, GIF or BMP files."); } } catch (Exception e) { logger.error(e.getMessage()); reponse = new SimpleResponse(SibConstants.FAILURE, e.getMessage()); } finally { if (stream != null) { stream.close(); } } return new ResponseEntity<Response>(reponse, HttpStatus.OK); }
From source file:Controller.MessageController.java
@RequestMapping(value = "/File/Conversation/upload", method = RequestMethod.POST) public @ResponseBody String uploadFileForConversation(@RequestParam("uploadFile") MultipartFile uploadFile, HttpSession session, @RequestParam("conversationID") String bookingID, @RequestParam("replyToTripperID") int replyToTripperID) { try {/*from w ww. j a va 2 s . com*/ String path = System.getProperty("catalina.base"); File folderPackage = new File(path + "/webapps/Conversation/Upload/" + bookingID); if (!folderPackage.exists()) { folderPackage.mkdirs(); } String name = uploadFile.getOriginalFilename(); FileCopyUtils.copy(uploadFile.getBytes(), new FileOutputStream(new File(folderPackage, name))); Gson gson = new Gson(); if (session != null) { if (FilenameUtils.getExtension(uploadFile.getOriginalFilename()).equals("png") || FilenameUtils.getExtension(uploadFile.getOriginalFilename()).equals("jpg") || FilenameUtils.getExtension(uploadFile.getOriginalFilename()).equals("gif")) { AccountSession account = (AccountSession) session.getAttribute("account"); if (providerService.isProvider(account)) { gson.toJson(messageService.sendConversationMessage( "{\"content\":\"" + "/Conversation/Upload/" + bookingID + "/" + name + "\",\"type\":\"image\",\"filename\":\"" + name + "\"}", "provider", account.getId(), Integer.valueOf(bookingID), replyToTripperID)); int tripperID; try { tripperID = messageService.getTripperIDByConversationID(Integer.valueOf(bookingID)); } catch (Exception e) { tripperID = 0; } template.convertAndSend("/topic/getUnReadConvForTripper/" + tripperID, new Greeting( "{\"Type\":\"conversation\",\"conversationID\":\"" + bookingID + "\"}")); } else if (tripperService.isUser(account)) { gson.toJson(messageService.sendConversationMessage( "{\"content\":\"" + "/Conversation/Upload/" + bookingID + "/" + name + "\",\"type\":\"image\",\"filename\":\"" + name + "\"}", "tripper", account.getId(), Integer.valueOf(bookingID), replyToTripperID)); int providerID; try { providerID = messageService.getProviderIDByConversationID(Integer.valueOf(bookingID)); } catch (Exception e) { providerID = 0; } template.convertAndSend("/topic/getUnReadConvForProvider/" + providerID, new Greeting( "{\"Type\":\"conversation\",\"conversationID\":\"" + bookingID + "\"}")); } template.convertAndSend("/topic/chatting/" + bookingID, new Greeting("{\"Type\":\"conversation\",\"conversationID\":\"" + bookingID + "\"}")); } else { AccountSession account = (AccountSession) session.getAttribute("account"); if (providerService.isProvider(account)) { gson.toJson(messageService.sendConversationMessage( "{\"content\":\"" + "/Conversation/Upload/" + bookingID + "/" + name + "\",\"type\":\"file\",\"filename\":\"" + name + "\"}", "provider", account.getId(), Integer.valueOf(bookingID), replyToTripperID)); int tripperID; try { tripperID = messageService.getTripperIDByConversationID(Integer.valueOf(bookingID)); } catch (Exception e) { tripperID = 0; } template.convertAndSend("/topic/getUnReadConvForTripper/" + tripperID, new Greeting( "{\"Type\":\"conversation\",\"conversationID\":\"" + bookingID + "\"}")); } else if (tripperService.isUser(account)) { gson.toJson(messageService.sendConversationMessage( "{\"content\":\"" + "/Conversation/Upload/" + bookingID + "/" + name + "\",\"type\":\"file\",\"filename\":\"" + name + "\"}", "tripper", account.getId(), Integer.valueOf(bookingID), replyToTripperID)); int providerID; try { providerID = messageService.getProviderIDByConversationID(Integer.valueOf(bookingID)); } catch (Exception e) { providerID = 0; } template.convertAndSend("/topic/getUnReadConvForProvider/" + providerID, new Greeting( "{\"Type\":\"conversation\",\"conversationID\":\"" + bookingID + "\"}")); } template.convertAndSend("/topic/chatting/" + bookingID, new Greeting("{\"Type\":\"conversation\",\"conversationID\":\"" + bookingID + "\"}")); } } return "/Conversation/Upload/" + bookingID + "/" + name; } catch (Exception e) { String content = "Function: MessageController - uploadFileForConversation\n" + "***Input***\n" + "bookingID: " + bookingID + "\n" + "**********\n" + "****Error****\n" + e.getMessage() + "\n" + "**********"; errorService.logBugWithAccount(content, session, e); return "{\"result\": \"error\"}"; } }
From source file:org.trpr.platform.batch.impl.spring.web.JobConfigController.java
/** * This method handles all the configuration changes: * Uploading of XML File//from www. j a va 2 s. c om * Uploading of dependency * Saving the changes in XML File */ @RequestMapping(value = "configuration/modify/jobs/{jobName}", method = RequestMethod.POST) public String editJob(ModelMap model, @RequestParam(value = "jobName") String[] jobNames, @RequestParam(defaultValue = "") String XMLFileContents, @RequestParam(defaultValue = "0") MultipartFile jobFile, @RequestParam(defaultValue = "0") MultipartFile depFile, @RequestParam(defaultValue = "0") String identifier) throws Exception { List<String> jobNameList = Arrays.asList(jobNames); //FOr getter methods, such as getJobdependency, any of the jobNames among the list would do String jobName = jobNameList.get(0); //Button 1: Upload XML if (identifier.equals("Upload file")) { String jobFileName = jobFile.getOriginalFilename(); //Check if file is empty or doesn't have an extension if (jobFile.isEmpty() || (jobFileName.lastIndexOf('.') < 0)) { model.addAttribute("XMLFileError", "File is Empty or invalid. Only .xml files can be uploaded"); } else if (!jobFileName.substring(jobFileName.lastIndexOf('.')).equals(".xml")) {//Check if file is .xml model.addAttribute("XMLFileError", "Only .xml files can be uploaded"); } else { //Read file to view byte[] buffer = jobFile.getBytes(); XMLFileContents = new String(buffer); model.addAttribute("XMLFileContents", XMLFileContents); } } else if (identifier.equals("Upload dependency")) { //Button 2: Upload dependencies String depFileName = depFile.getOriginalFilename(); if (depFile.isEmpty() || (depFileName.lastIndexOf('.') < 0)) { model.addAttribute("DepFileError", "File is Empty or invalid. Only .jar files can be uploaded"); } else if (!depFileName.substring(depFileName.lastIndexOf('.')).equals(".jar")) { //Check if file is valid model.addAttribute("DepFileError", "Only .jar files can be uploaded"); } else {//Move uploaded file //Check if file hasn't been added already if (jobConfigService.getJobDependencyList(jobName) != null && jobConfigService.getJobDependencyList(jobName).contains(depFileName)) { model.addAttribute("DepFileError", "The filename is already added. Overwriting"); } jobConfigService.addJobDependency(jobNameList, depFile.getOriginalFilename(), depFile.getBytes()); } } else { //Button 3: Save. Overwrite the modified XML File LOGGER.info("Request to deploy jobConfig file for: " + jobNameList); try { //Set XML File this.jobConfigService.setJobConfig(jobNameList, new ByteArrayResource(XMLFileContents.getBytes())); this.jobConfigService.deployJob(jobNameList); } catch (Exception e) { LOGGER.info("Error while deploying job", e); //View: Add Error and rest of the attributes //Get stacktrace as string StringWriter errors = new StringWriter(); e.printStackTrace(new PrintWriter(errors)); model.addAttribute("LoadingError", errors.toString()); if (errors.toString() == null) { model.addAttribute("LoadingError", "Unexpected error"); } model.addAttribute("XMLFileContents", XMLFileContents.trim()); model.addAttribute("jobName", jobNameList); if (jobConfigService.getJobDependencyList(jobName) != null) { model.addAttribute("dependencies", jobConfigService.getJobDependencyList(jobName)); } model.addAttribute("XMLFileContents", XMLFileContents.trim()); //Redirect return "configuration/modify/jobs/job"; } //Loading worked. Deploy to all hosts if (this.jobConfigService.getSyncService() != null) this.jobConfigService.getSyncService().deployJobToAllHosts(jobName); //Redirect to job configuration page. Load the view details model.addAttribute("SuccessMessage", "The job was successfully deployed!"); model.addAttribute("jobName", jobName); //Push jobs to all servers if (jobConfigService.getJobDependencyList(jobName) != null) { model.addAttribute("dependencies", jobConfigService.getJobDependencyList(jobName)); } model.addAttribute("XMLFileContents", XMLFileContents.trim()); String jobDirectory = this.jobConfigService.getJobStoreURI(jobName).getPath(); model.addAttribute("JobDirectoryName", jobDirectory.substring(jobDirectory.lastIndexOf('/') + 1) + "/lib"); return "configuration/jobs/job"; } //Update the view model.addAttribute("jobName", jobNameList); if (jobConfigService.getJobDependencyList(jobName) != null) { model.addAttribute("dependencies", jobConfigService.getJobDependencyList(jobName)); } model.addAttribute("XMLFileContents", XMLFileContents); //Redirect to modify page return "configuration/modify/jobs/job"; }