List of usage examples for org.springframework.web.multipart MultipartFile getInputStream
@Override
InputStream getInputStream() throws IOException;
From source file:com.wavemaker.tools.project.AbstractDeploymentManager.java
@Override public FileUploadResponse importFromZip(MultipartFile file, boolean isTemplate) throws IOException { FileUploadResponse response = new FileUploadResponse(); org.springframework.core.io.Resource tmpDir = this.projectManager.getTmpDir(); // Write the zip file to outputFile String originalName = file.getOriginalFilename(); int upgradeIndex = originalName.indexOf("-upgrade-"); if (upgradeIndex > 0) { originalName = originalName.substring(0, upgradeIndex) + ".zip"; }/*from w w w .j a v a 2 s . c o m*/ org.springframework.core.io.Resource outputFile = tmpDir.createRelative(originalName); OutputStream fos = this.fileSystem.getOutputStream(outputFile); FileCopyUtils.copy(file.getInputStream(), fos); org.springframework.core.io.Resource finalProjectFolder; try { // returns null if fails to unzip; need a handler for this... org.springframework.core.io.Resource projectFolder = com.wavemaker.tools.project.ResourceManager .unzipFile(this.fileSystem, outputFile); // If there is only one folder in what we think is the // projectFolder, open that one folder because that must be the real // project folder // Filter out private folders generated by OS or svn, etc... // (__MACOS, .svn, etc...) List<org.springframework.core.io.Resource> listings = this.fileSystem.listChildren(projectFolder); if (listings.size() == 1) { org.springframework.core.io.Resource listing = listings.get(0); if (StringUtils.getFilenameExtension(listing.getFilename()) == null && !listing.getFilename().startsWith(".") && !listing.getFilename().startsWith("_")) { projectFolder = listing; } } // Verify that this looks like a project folder we unzipped com.wavemaker.tools.project.Project project = new com.wavemaker.tools.project.Project(projectFolder, this.fileSystem); org.springframework.core.io.Resource testExistenceFile = project.getWebAppRoot() .createRelative("pages/"); if (!testExistenceFile.exists()) { throw new WMRuntimeException( "That didn't look like a project folder; if it was, files were missing"); } com.wavemaker.tools.io.File indexhtml = project.getWebAppRootFolder().getFile("index.html"); String indexstring = project.readFile(indexhtml); int endIndex = indexstring.lastIndexOf("({domNode: \"wavemakerNode\""); int startIndex = indexstring.lastIndexOf(" ", endIndex); String newProjectName = indexstring.substring(startIndex + 1, endIndex); // Get a File to point to where we're going to place this imported // project if (isTemplate) { this.fileSystem.getTemplatesFolder().createIfMissing(); } finalProjectFolder = (isTemplate ? this.fileSystem.getTemplatesDir() : this.projectManager.getBaseProjectDir()).createRelative(newProjectName + "/"); if (isTemplate && finalProjectFolder.exists()) { this.fileSystem.deleteFile(finalProjectFolder); } System.out.println("FINAL PATH: " + finalProjectFolder.getURI().toString()); String finalname = finalProjectFolder.getFilename(); String originalFinalname = finalname; // If there is already a project at that location, rename the // project int i = -1; do { i++; finalProjectFolder = (isTemplate ? this.fileSystem.getTemplatesDir() : this.projectManager.getBaseProjectDir()) .createRelative(finalname + (i > 0 ? "" + i : "") + "/"); } while (finalProjectFolder.exists()); finalname = finalProjectFolder.getFilename(); // OK, now finalname has the name of the new project, // finalProjectFolder has the full path to the new project // Move the project into the project folder this.fileSystem.rename(projectFolder, finalProjectFolder); // If we renamed the project (i.e. if i got incremented) then we // need to make some corrections if (i > 0) { // Correction 1: Rename the js file com.wavemaker.tools.project.Project finalProject = new com.wavemaker.tools.project.Project( finalProjectFolder, this.fileSystem); File jsFile = finalProject.getWebAppRootFolder().getFile(originalFinalname + ".js"); File newJsFile = finalProject.getWebAppRootFolder().getFile(finalname + ".js"); jsFile.rename(newJsFile.getName()); // Correction 2: Change the class name in the js file com.wavemaker.tools.project.ResourceManager.ReplaceTextInProjectFile(finalProject, newJsFile, originalFinalname, finalname); // Corection3: Change the constructor in index.html File index_html = finalProject.getWebAppRootFolder().getFile("index.html"); com.wavemaker.tools.project.ResourceManager.ReplaceTextInProjectFile(finalProject, index_html, "new " + originalFinalname + "\\(\\{domNode", "new " + finalname + "({domNode"); // Correction 4: Change the pointer to the js script read in by // index.html com.wavemaker.tools.project.ResourceManager.ReplaceTextInProjectFile(finalProject, index_html, "\\\"" + originalFinalname + "\\.js\\\"", '"' + finalname + ".js\""); // Correction 5: Change the title com.wavemaker.tools.project.ResourceManager.ReplaceTextInProjectFile(finalProject, index_html, "\\<title\\>" + originalFinalname + "\\<\\/title\\>", "<title>" + finalname + "</title>"); } } finally { // If the user uploaded a zipfile that had many high level folders, // they could make a real mess of things, // so just purge the tmp folder after we're done this.fileSystem.deleteFile(tmpDir); } System.out.println("C"); response.setPath(finalProjectFolder.getFilename()); response.setError(""); response.setWidth(""); response.setHeight(""); return response; }
From source file:edu.unc.lib.dl.admin.controller.IngestController.java
@RequestMapping(value = "ingest/{pid}", method = RequestMethod.POST) public @ResponseBody Map<String, ? extends Object> ingestPackageController(@PathVariable("pid") String pid, @RequestParam("type") String type, @RequestParam(value = "name", required = false) String name, @RequestParam("file") MultipartFile ingestFile, HttpServletRequest request, HttpServletResponse response) {/* w w w. j a va 2 s . c o m*/ String destinationUrl = swordUrl + "collection/" + pid; HttpClient client = HttpClientUtil.getAuthenticatedClient(destinationUrl, swordUsername, swordPassword); client.getParams().setAuthenticationPreemptive(true); PostMethod method = new PostMethod(destinationUrl); // Set SWORD related headers for performing ingest method.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString()); method.addRequestHeader("Packaging", type); method.addRequestHeader("On-Behalf-Of", GroupsThreadStore.getUsername()); method.addRequestHeader("Content-Type", ingestFile.getContentType()); method.addRequestHeader("Content-Length", Long.toString(ingestFile.getSize())); method.addRequestHeader("mail", request.getHeader("mail")); method.addRequestHeader("Content-Disposition", "attachment; filename=" + ingestFile.getOriginalFilename()); if (name != null && name.trim().length() > 0) method.addRequestHeader("Slug", name); // Setup the json response Map<String, Object> result = new HashMap<String, Object>(); result.put("action", "ingest"); result.put("destination", pid); try { method.setRequestEntity( new InputStreamRequestEntity(ingestFile.getInputStream(), ingestFile.getSize())); client.executeMethod(method); response.setStatus(method.getStatusCode()); // Object successfully "create", or at least queued if (method.getStatusCode() == 201) { Header location = method.getResponseHeader("Location"); String newPid = location.getValue(); newPid = newPid.substring(newPid.lastIndexOf('/')); result.put("pid", newPid); } else if (method.getStatusCode() == 401) { // Unauthorized result.put("error", "Not authorized to ingest to container " + pid); } else if (method.getStatusCode() == 400 || method.getStatusCode() >= 500) { // Server error, report it to the client result.put("error", "A server error occurred while attempting to ingest \"" + ingestFile.getName() + "\" to " + pid); // Inspect the SWORD response, extracting the stacktrace InputStream entryPart = method.getResponseBodyAsStream(); Abdera abdera = new Abdera(); Parser parser = abdera.getParser(); Document<Entry> entryDoc = parser.parse(entryPart); Object rootEntry = entryDoc.getRoot(); String stackTrace; if (rootEntry instanceof FOMExtensibleElement) { stackTrace = ((org.apache.abdera.parser.stax.FOMExtensibleElement) entryDoc.getRoot()) .getExtension(SWORD_VERBOSE_DESCRIPTION).getText(); result.put("errorStack", stackTrace); } else { stackTrace = ((Entry) rootEntry).getExtension(SWORD_VERBOSE_DESCRIPTION).getText(); result.put("errorStack", stackTrace); } log.warn("Failed to upload ingest package file " + ingestFile.getName() + " from user " + GroupsThreadStore.getUsername(), stackTrace); } return result; } catch (Exception e) { log.warn("Encountered an unexpected error while ingesting package " + ingestFile.getName() + " from user " + GroupsThreadStore.getUsername(), e); result.put("error", "A server error occurred while attempting to ingest \"" + ingestFile.getName() + "\" to " + pid); return result; } finally { method.releaseConnection(); try { ingestFile.getInputStream().close(); } catch (IOException e) { log.warn("Failed to close ingest package file", e); } } }
From source file:com.tela.pms.PatientController.java
/** * createPatient will edit a new patient and update in the cloud db *//*from www . j a v a 2 s. c om*/ @RequestMapping(value = "/editPatient", method = RequestMethod.POST) public String editPatient(HttpServletRequest request, HttpServletResponse response, Model model, @RequestParam("file") MultipartFile file) { //Retrieving requests String patientId = request.getParameter("id"); System.out.println(patientId); int id = Integer.parseInt(patientId); String patientName = request.getParameter("patientName"); String age = request.getParameter("age"); String nic = request.getParameter("nic"); String address = request.getParameter("address"); String gender = request.getParameter("gender"); String contactNo = request.getParameter("contactNo"); String email = request.getParameter("email"); String tags = request.getParameter("tags"); String createdAt = request.getParameter("patient_CreatedAt"); String imagePath = request.getParameter("patient_Photo"); String existingimagePath = request.getParameter("existingimagePath"); System.out.println("**** img path " + imagePath); if (nic.equals("") || nic == null) { nic = "Not Available"; } if (address.equals("") || address == null) { address = "Not Available"; } if (contactNo.equals("") || contactNo == null) { contactNo = "Not Available"; } if (email.equals("") || email == null) { email = "Not@Available"; } if (tags.equals("") || tags == null) { tags = "Not Available"; } //Creating a new patient Patient patient = new Patient(); //Retrieving uploaded files MultipartFile patientPhoto = file; if (patientPhoto.getSize() != 0 && patientPhoto.getOriginalFilename() != null) { File cloud_file = null; try { cloud_file = convertFile(patientPhoto); } catch (IOException e1) { logger.info("something went wrong in coverting the file @" + new Date()); e1.printStackTrace(); } String extension = FilenameUtils.getExtension(patientPhoto.getOriginalFilename()); Long fileSize = patientPhoto.getSize(); if (extension.equals("JPG") || extension.equals("jpg") || extension.equals("jpeg") || extension.equals("JPEG")) { try { File catalinaBase = new File(System.getProperty("catalina.base")).getAbsoluteFile(); logger.info("catalinaBase:" + catalinaBase.getAbsolutePath()); InputStream inputStream = patientPhoto.getInputStream(); String imageId = "patient-" + Integer.toString(id); String fileName = imageId + ".jpg"; File newFile = new File(catalinaBase, "webapps/pms/WEB-INF/views/images/Uploaded_images/Patients/" + fileName); if (!newFile.exists()) { newFile.createNewFile(); } OutputStream outputStream = new FileOutputStream(newFile); int read = 0; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } imagePath = "resources/images/Uploaded_images/Patients/" + fileName; logger.info("Patient image successfully uploaded to local repo @" + new Date()); } catch (FileNotFoundException e) { logger.info("something went wrong when patient photo uploading @" + new Date()); e.printStackTrace(); } catch (IOException e) { logger.info("something went wrong when patient photo uploading @" + new Date()); e.printStackTrace(); } } else { logger.info("Uploaded file is not a jpg or png " + new Date()); if (gender.equals("Female")) { imagePath = "resources/images/patient-female.png"; } else { imagePath = "resources/images/patient-male.png"; } } } else { if (existingimagePath.contains("patient-male") || existingimagePath.contains("patient-female")) { if (gender.equals("Female")) { imagePath = "resources/images/patient-female.png"; } else { imagePath = "resources/images/patient-male.png"; } } } //Updating patient info patient.setPatient_Id(id); patient.setPatient_Name(patientName); patient.setPatient_Age(age); patient.setPatient_Address(address); patient.setPatient_ContactNo(contactNo); patient.setPatient_Gender(gender); patient.setPatient_Email(email); patient.setPatient_NIC(nic); patient.setPatient_Photo(imagePath); patient.setPatient_CreatedAt(createdAt); patient.setPatient_tags(tags); //Calling patient service and updating patient patientService.updatePatient(patient); //System.out.println(patientName+" "+age+" "+patientPhoto.getOriginalFilename()+" "+nic+" "+address+" "+gender+" "+contactNo+" "+email); String view = "patient"; Patient editedPatient = patientService.findPatientById(id); model.addAttribute("patient", editedPatient); List<Prescription> prescriptions = prescriptionService.retrieveAllPrescriptionsByPatientId(id); model.addAttribute("prescriptions", prescriptions); logger.info("Edited Patient " + id + " retrieved @ " + new Date()); logger.info("Prescription list " + prescriptions + " retrieved @ " + new Date()); model.addAttribute("status", "<strong>Successfully </strong> updated the patient! "); model.addAttribute("style", "style=\"display:block;margin-top: 5px;\""); return view; }
From source file:com.devnexus.ting.web.controller.admin.SpeakerController.java
@RequestMapping(value = "/s/admin/{eventKey}/speaker/{speakerId}", method = RequestMethod.POST) public String editSpeaker(@PathVariable("eventKey") String eventKey, @PathVariable("speakerId") Long speakerId, @RequestParam MultipartFile pictureFile, @Valid Speaker speakerForm, BindingResult result, HttpServletRequest request, ModelMap model, RedirectAttributes redirectAttributes) { if (request.getParameter("cancel") != null) { return "redirect:/s/admin/{eventKey}/speakers"; }// www. j a va2 s. c om if (result.hasErrors()) { return "/admin/add-speaker"; } final Speaker speakerFromDb = businessService.getSpeakerWithPicture(speakerId); speakerFromDb.setBio(speakerForm.getBio()); speakerFromDb.setTwitterId(speakerForm.getTwitterId()); speakerFromDb.setGooglePlusId(speakerForm.getGooglePlusId()); speakerFromDb.setLinkedInId(speakerForm.getLinkedInId()); speakerFromDb.setLanyrdId(speakerForm.getLanyrdId()); speakerFromDb.setGithubId(speakerForm.getGithubId()); speakerFromDb.setFirstName(speakerForm.getFirstName()); speakerFromDb.setLastName(speakerForm.getLastName()); speakerFromDb.setCompany(speakerForm.getCompany()); if (pictureFile != null && pictureFile.getSize() > 0) { final FileData pictureData; if (speakerFromDb.getPicture() == null) { pictureData = new FileData(); } else { pictureData = speakerFromDb.getPicture(); } try { pictureData.setFileData(IOUtils.toByteArray(pictureFile.getInputStream())); pictureData.setFileSize(pictureFile.getSize()); pictureData.setFileModified(new Date()); pictureData.setName(pictureFile.getOriginalFilename()); pictureData.setType(pictureFile.getContentType()); } catch (IOException e) { throw new IllegalStateException(e); } speakerFromDb.setPicture(pictureData); } businessService.saveSpeaker(speakerFromDb); redirectAttributes.addFlashAttribute("successMessage", String.format("The speaker '%s' was edited successfully.", speakerFromDb.getFirstLastName())); return "redirect:/s/admin/{eventKey}/speakers"; }
From source file:org.opentravel.pubs.controllers.AdminController.java
@RequestMapping({ "/DoUploadSpecification.html", "/DoUploadSpecification.htm" }) public String doUploadSpecificationPage(HttpSession session, Model model, RedirectAttributes redirectAttrs, @ModelAttribute("specificationForm") SpecificationForm specificationForm, @RequestParam(value = "archiveFile", required = false) MultipartFile archiveFile) { String targetPage = "uploadSpecification"; try {/* ww w .j a va 2s.c o m*/ if (specificationForm.isProcessForm()) { PublicationType publicationType = resolvePublicationType(specificationForm.getSpecType()); PublicationState publicationState = (specificationForm.getPubState() == null) ? null : PublicationState.valueOf(specificationForm.getPubState()); Publication publication = new PublicationBuilder() .setName(StringUtils.trimString(specificationForm.getName())).setType(publicationType) .setState(publicationState).build(); try { if (!archiveFile.isEmpty()) { DAOFactoryManager.getFactory().newPublicationDAO().publishSpecification(publication, archiveFile.getInputStream()); model.asMap().clear(); redirectAttrs.addAttribute("publication", publication.getName()); redirectAttrs.addAttribute("specType", publication.getType()); targetPage = "redirect:/admin/ViewSpecification.html"; } else { ValidationResults vResults = ModelValidator.validate(publication); // An archive file must be provided on initial creation of a publication vResults.add(publication, "archiveFilename", "Archive File is Required"); if (vResults.hasViolations()) { throw new ValidationException(vResults); } } } catch (ValidationException e) { addValidationErrors(e, model); } catch (Throwable t) { log.error("An error occurred while publishing the spec: ", t); setErrorMessage(t.getMessage(), model); } } } catch (Throwable t) { log.error("Error during publication controller processing.", t); setErrorMessage(DEFAULT_ERROR_MESSAGE, model); } return applyCommonValues(model, targetPage); }
From source file:org.opentravel.pubs.controllers.AdminController.java
@RequestMapping({ "/DoUpdateCodeList.html", "/DoUpdateCodeList.htm" }) public String doUpdateCodeListPage(HttpSession session, Model model, RedirectAttributes redirectAttrs, @ModelAttribute("codeListForm") CodeListForm codeListForm, @RequestParam(value = "archiveFile", required = false) MultipartFile archiveFile) { String targetPage = "updateSpecification"; try {/*from w ww .jav a2s.co m*/ if (codeListForm.isProcessForm()) { CodeListDAO cDao = DAOFactoryManager.getFactory().newCodeListDAO(); CodeList codeList = cDao.getCodeList(codeListForm.getCodeListId()); try { codeList.setReleaseDate(CodeList.labelFormat.parse(codeListForm.getReleaseDateLabel())); ValidationResults vResults = ModelValidator.validate(codeList); // Before we try to update the contents of the spefication, validate the // publication object to see if there are any errors. if (vResults.hasViolations()) { throw new ValidationException(vResults); } if (!archiveFile.isEmpty()) { cDao.updateCodeList(codeList, archiveFile.getInputStream()); } model.asMap().clear(); redirectAttrs.addAttribute("releaseDate", codeList.getReleaseDateLabel()); targetPage = "redirect:/admin/ViewCodeList.html"; } catch (ParseException e) { ValidationResults vResult = new ValidationResults(); vResult.add(codeList, "releaseDate", "Invalid release date"); addValidationErrors(vResult, model); } catch (ValidationException e) { addValidationErrors(e, model); } catch (Throwable t) { log.error("An error occurred while updating the spec: ", t); setErrorMessage(t.getMessage(), model); } } } catch (Throwable t) { log.error("Error during publication controller processing.", t); setErrorMessage(DEFAULT_ERROR_MESSAGE, model); } return applyCommonValues(model, targetPage); }
From source file:org.openmrs.module.conceptmanagementapps.api.impl.ConceptManagementAppsServiceImpl.java
/** * @see org.openmrs.module.conceptmanagementapps.api.ConceptManagementAppsService#uploadSpreadsheet(org.springframework.web.multipart.MultipartFile) *//* w ww .j av a 2 s . c o m*/ @Transactional public FileDownload uploadSpreadsheet(MultipartFile spreadsheetFile) throws APIException { List<String> fileLines = new ArrayList<String>(); ICsvMapReader mapReader = null; FileDownload fileShowingErrors = null; boolean hasErrors = false; String errorReason = null; try { mapReader = new CsvMapReader(new InputStreamReader(spreadsheetFile.getInputStream()), CsvPreference.STANDARD_PREFERENCE); final String[] header = mapReader.getHeader(true); final CellProcessor[] processors = getSpreadsheetProcessors(); String delimiter = ","; fileLines.add("errors - delete this column to resubmit" + delimiter + "map type" + delimiter + "source name" + delimiter + "source code" + delimiter + "concept Id" + delimiter + "concept uuid" + delimiter + "preferred name" + delimiter + "description" + delimiter + "class" + delimiter + "datatype" + delimiter + "all existing mappings"); for (Map<String, Object> mapList = mapReader.read(header, processors); mapList != null; mapList = mapReader.read(header, processors)) { errorReason = " "; errorReason = getInitialErrorsBeforeTryingToSaveConcept(mapList); String line = mapReader.getUntokenizedRow(); fileLines.add(errorReason + "," + line); if (StringUtils.isNotEmpty(errorReason) && StringUtils.isNotBlank(errorReason)) { hasErrors = true; } } fileShowingErrors = writeToFile(fileLines); } catch (APIException e) { log.error(e); throw new APIException( "error on row " + mapReader.getRowNumber() + "," + mapReader.getUntokenizedRow() + e); } catch (FileNotFoundException e) { log.error(e); } catch (IOException e) { log.error(e); } finally { if (mapReader != null) { try { mapReader.close(); } catch (IOException e) { log.error(e); } } } //if there are no errors then go ahead and pass through again and save if (!hasErrors) { setMapAndSaveConcept(spreadsheetFile); return null; } return fileShowingErrors; }
From source file:aiai.ai.launchpad.snippet.SnippetController.java
@PostMapping(value = "/snippet-upload-from-file") public String uploadSnippet(MultipartFile file, final RedirectAttributes redirectAttributes) { String originFilename = file.getOriginalFilename(); if (originFilename == null) { redirectAttributes.addFlashAttribute("errorMessage", "#422.01 name of uploaded file is null"); return "redirect:/launchpad/snippets"; }//w ww . j a va 2s .c om int idx; if ((idx = originFilename.lastIndexOf('.')) == -1) { redirectAttributes.addFlashAttribute("errorMessage", "#422.02 '.' wasn't found, bad filename: " + originFilename); return "redirect:/launchpad/snippets"; } String ext = originFilename.substring(idx).toLowerCase(); if (!".zip".equals(ext)) { redirectAttributes.addFlashAttribute("errorMessage", "#422.03 only '.zip' files is supported, filename: " + originFilename); return "redirect:/launchpad/snippets"; } final String location = System.getProperty("java.io.tmpdir"); try { File tempDir = DirUtils.createTempDir("snippet-upload-"); if (tempDir == null || tempDir.isFile()) { redirectAttributes.addFlashAttribute("errorMessage", "#422.04 can't create temporary directory in " + location); return "redirect:/launchpad/snippets"; } final File zipFile = new File(tempDir, "snippet.zip"); log.debug("Start storing an uploaded snippet to disk"); try (OutputStream os = new FileOutputStream(zipFile)) { IOUtils.copy(file.getInputStream(), os, 64000); } log.debug("Start unzipping archive"); ZipUtils.unzipFolder(zipFile, tempDir); log.debug("Start loading snippet data to db"); snippetService.loadSnippetsRecursively(tempDir); } catch (Exception e) { log.error("Error", e); redirectAttributes.addFlashAttribute("errorMessage", "#422.05 can't load snippets, Error: " + e.toString()); return "redirect:/launchpad/snippets"; } log.debug("All done. Send redirect"); return "redirect:/launchpad/snippets"; }