List of usage examples for org.springframework.web.multipart MultipartFile getOriginalFilename
@Nullable String getOriginalFilename();
From source file:com.dominion.salud.nomenclator.negocio.service.impl.tools.BuzonSucesosServiceImpl.java
@Override public void upload(MultipartFile file) { logger.info("INICIANDO la carga de la base de datos de AEMPS"); BuzonSucesos buzonSucesos = null;/*from w w w . jav a2 s . co m*/ File zip = null; File dest = null; try { logger.debug(" Procesando el fichero: " + file.getOriginalFilename()); zip = new File(NOMENCLATORConstantes._TEMP + file.getOriginalFilename()); file.transferTo(zip); dest = new File(NOMENCLATORConstantes._TEMP); ZipUtil.unZip(zip, dest); //DICCIONARIO_ATC try { logger.debug(" Iniciando la carga de " + DICCIONARIO_ATC); atcService.load( new File(dest.getAbsolutePath() + System.getProperty("file.separator") + DICCIONARIO_ATC)); } catch (Exception e) { logger.warn(" No se ha podido cargar " + DICCIONARIO_ATC + ": " + e.toString()); buzonSucesos = new BuzonSucesos(); buzonSucesos.setCodProceso(BuzonSucesos.DICCIONARIO_ATC); buzonSucesos.setFecIni(new Date()); buzonSucesos.setFecFin(new Date()); buzonSucesos.setMensaje("No se ha podido cargar " + DICCIONARIO_ATC + ": " + e.toString()); save(buzonSucesos); } //DICCIONARIO_DCP try { logger.debug(" Iniciando la carga de " + DICCIONARIO_DCP); dcpService.load( new File(dest.getAbsolutePath() + System.getProperty("file.separator") + DICCIONARIO_DCP)); } catch (Exception e) { logger.warn(" No se ha podido cargar " + DICCIONARIO_DCP + ": " + e.toString()); buzonSucesos = new BuzonSucesos(); buzonSucesos.setCodProceso(BuzonSucesos.DICCIONARIO_DCP); buzonSucesos.setFecIni(new Date()); buzonSucesos.setFecFin(new Date()); buzonSucesos.setMensaje("No se ha podido cargar " + DICCIONARIO_DCP + ": " + e.toString()); save(buzonSucesos); } //DICCIONARIO_DCPF try { logger.debug(" Iniciando la carga de " + DICCIONARIO_DCPF); dcpfService.load( new File(dest.getAbsolutePath() + System.getProperty("file.separator") + DICCIONARIO_DCPF)); } catch (Exception e) { logger.warn(" No se ha podido cargar " + DICCIONARIO_DCPF + ": " + e.toString()); buzonSucesos = new BuzonSucesos(); buzonSucesos.setCodProceso(BuzonSucesos.DICCIONARIO_DCPF); buzonSucesos.setFecIni(new Date()); buzonSucesos.setFecFin(new Date()); buzonSucesos.setMensaje("No se ha podido cargar " + DICCIONARIO_DCPF + ": " + e.toString()); save(buzonSucesos); } //DICCIONARIO_DCSA try { logger.debug(" Iniciando la carga de " + DICCIONARIO_DCSA); dcsaService.load( new File(dest.getAbsolutePath() + System.getProperty("file.separator") + DICCIONARIO_DCSA)); } catch (Exception e) { logger.warn(" No se ha podido cargar " + DICCIONARIO_DCSA + ": " + e.toString()); buzonSucesos = new BuzonSucesos(); buzonSucesos.setCodProceso(BuzonSucesos.DICCIONARIO_DCSA); buzonSucesos.setFecIni(new Date()); buzonSucesos.setFecFin(new Date()); buzonSucesos.setMensaje("No se ha podido cargar " + DICCIONARIO_DCSA + ": " + e.toString()); save(buzonSucesos); } //DICCIONARIO_ENVASES try { logger.debug(" Iniciando la carga de " + DICCIONARIO_ENVASES); envasesService.load(new File( dest.getAbsolutePath() + System.getProperty("file.separator") + DICCIONARIO_ENVASES)); } catch (Exception e) { logger.warn(" No se ha podido cargar " + DICCIONARIO_ENVASES + ": " + e.toString()); buzonSucesos = new BuzonSucesos(); buzonSucesos.setCodProceso(BuzonSucesos.DICCIONARIO_ENVASES); buzonSucesos.setFecIni(new Date()); buzonSucesos.setFecFin(new Date()); buzonSucesos.setMensaje("No se ha podido cargar " + DICCIONARIO_ENVASES + ": " + e.toString()); save(buzonSucesos); } //DICCIONARIO_EXCIPIENTES_DECL_OBLIGATORIA try { logger.debug(" Iniciando la carga de " + DICCIONARIO_EXCIPIENTES_DECL_OBLIGATORIA); excipientesService.load(new File(dest.getAbsolutePath() + System.getProperty("file.separator") + DICCIONARIO_EXCIPIENTES_DECL_OBLIGATORIA)); } catch (Exception e) { logger.warn(" No se ha podido cargar " + DICCIONARIO_EXCIPIENTES_DECL_OBLIGATORIA + ": " + e.toString()); buzonSucesos = new BuzonSucesos(); buzonSucesos.setCodProceso(BuzonSucesos.DICCIONARIO_EXCIPIENTES_DECL_OBLIGATORIA); buzonSucesos.setFecIni(new Date()); buzonSucesos.setFecFin(new Date()); buzonSucesos.setMensaje( "No se ha podido cargar " + DICCIONARIO_EXCIPIENTES_DECL_OBLIGATORIA + ": " + e.toString()); save(buzonSucesos); } //DICCIONARIO_FORMA_FARMACEUTICA_SIMPLIFICADAS try { logger.debug(" Iniciando la carga de " + DICCIONARIO_FORMA_FARMACEUTICA_SIMPLIFICADAS); formasFarSimpService.load(new File(dest.getAbsolutePath() + System.getProperty("file.separator") + DICCIONARIO_FORMA_FARMACEUTICA_SIMPLIFICADAS)); } catch (Exception e) { logger.warn(" No se ha podido cargar " + DICCIONARIO_FORMA_FARMACEUTICA_SIMPLIFICADAS + ": " + e.toString()); buzonSucesos = new BuzonSucesos(); buzonSucesos.setCodProceso(BuzonSucesos.DICCIONARIO_FORMA_FARMACEUTICA_SIMPLIFICADAS); buzonSucesos.setFecIni(new Date()); buzonSucesos.setFecFin(new Date()); buzonSucesos.setMensaje("No se ha podido cargar " + DICCIONARIO_FORMA_FARMACEUTICA_SIMPLIFICADAS + ": " + e.toString()); save(buzonSucesos); } //DICCIONARIO_FORMA_FARMACEUTICA try { logger.debug(" Iniciando la carga de " + DICCIONARIO_FORMA_FARMACEUTICA); formasFarService.load(new File(dest.getAbsolutePath() + System.getProperty("file.separator") + DICCIONARIO_FORMA_FARMACEUTICA)); } catch (Exception e) { logger.warn( " No se ha podido cargar " + DICCIONARIO_FORMA_FARMACEUTICA + ": " + e.toString()); buzonSucesos = new BuzonSucesos(); buzonSucesos.setCodProceso(BuzonSucesos.DICCIONARIO_FORMA_FARMACEUTICA); buzonSucesos.setFecIni(new Date()); buzonSucesos.setFecFin(new Date()); buzonSucesos.setMensaje( "No se ha podido cargar " + DICCIONARIO_FORMA_FARMACEUTICA + ": " + e.toString()); save(buzonSucesos); } //DICCIONARIO_LABORATORIOS try { logger.debug(" Iniciando la carga de " + DICCIONARIO_LABORATORIOS); laboratoriosService.load(new File( dest.getAbsolutePath() + System.getProperty("file.separator") + DICCIONARIO_LABORATORIOS)); } catch (Exception e) { logger.warn(" No se ha podido cargar " + DICCIONARIO_LABORATORIOS + ": " + e.toString()); buzonSucesos = new BuzonSucesos(); buzonSucesos.setCodProceso(BuzonSucesos.DICCIONARIO_LABORATORIOS); buzonSucesos.setFecIni(new Date()); buzonSucesos.setFecFin(new Date()); buzonSucesos.setMensaje("No se ha podido cargar " + DICCIONARIO_LABORATORIOS + ": " + e.toString()); save(buzonSucesos); } //DICCIONARIO_PRINCIPIOS_ACTIVOS try { logger.debug(" Iniciando la carga de " + DICCIONARIO_PRINCIPIOS_ACTIVOS); principiosActivosService.load(new File(dest.getAbsolutePath() + System.getProperty("file.separator") + DICCIONARIO_PRINCIPIOS_ACTIVOS)); } catch (Exception e) { logger.warn( " No se ha podido cargar " + DICCIONARIO_PRINCIPIOS_ACTIVOS + ": " + e.toString()); buzonSucesos = new BuzonSucesos(); buzonSucesos.setCodProceso(BuzonSucesos.DICCIONARIO_PRINCIPIOS_ACTIVOS); buzonSucesos.setFecIni(new Date()); buzonSucesos.setFecFin(new Date()); buzonSucesos.setMensaje( "No se ha podido cargar " + DICCIONARIO_PRINCIPIOS_ACTIVOS + ": " + e.toString()); save(buzonSucesos); } //DICCIONARIO_SITUACION_REGISTRO try { logger.debug(" Iniciando la carga de " + DICCIONARIO_SITUACION_REGISTRO); situacionRegistroService.load(new File(dest.getAbsolutePath() + System.getProperty("file.separator") + DICCIONARIO_SITUACION_REGISTRO)); } catch (Exception e) { logger.warn( " No se ha podido cargar " + DICCIONARIO_SITUACION_REGISTRO + ": " + e.toString()); buzonSucesos = new BuzonSucesos(); buzonSucesos.setCodProceso(BuzonSucesos.DICCIONARIO_SITUACION_REGISTRO); buzonSucesos.setFecIni(new Date()); buzonSucesos.setFecFin(new Date()); buzonSucesos.setMensaje( "No se ha podido cargar " + DICCIONARIO_SITUACION_REGISTRO + ": " + e.toString()); save(buzonSucesos); } //DICCIONARIO_UNIDAD_CONTENIDO try { logger.debug(" Iniciando la carga de " + DICCIONARIO_UNIDAD_CONTENIDO); unidadesContenidoService.load(new File(dest.getAbsolutePath() + System.getProperty("file.separator") + DICCIONARIO_UNIDAD_CONTENIDO)); } catch (Exception e) { logger.warn( " No se ha podido cargar " + DICCIONARIO_UNIDAD_CONTENIDO + ": " + e.toString()); buzonSucesos = new BuzonSucesos(); buzonSucesos.setCodProceso(BuzonSucesos.DICCIONARIO_UNIDAD_CONTENIDO); buzonSucesos.setFecIni(new Date()); buzonSucesos.setFecFin(new Date()); buzonSucesos .setMensaje("No se ha podido cargar " + DICCIONARIO_UNIDAD_CONTENIDO + ": " + e.toString()); save(buzonSucesos); } //DICCIONARIO_UNIDAD_DOSIS try { logger.debug(" Iniciando la carga de " + DICCIONARIO_UNIDAD_DOSIS); unidadesDosisService.load(new File( dest.getAbsolutePath() + System.getProperty("file.separator") + DICCIONARIO_UNIDAD_DOSIS)); } catch (Exception e) { logger.warn(" No se ha podido cargar " + DICCIONARIO_UNIDAD_DOSIS + ": " + e.toString()); buzonSucesos = new BuzonSucesos(); buzonSucesos.setCodProceso(BuzonSucesos.DICCIONARIO_UNIDAD_DOSIS); buzonSucesos.setFecIni(new Date()); buzonSucesos.setFecFin(new Date()); buzonSucesos.setMensaje("No se ha podido cargar " + DICCIONARIO_UNIDAD_DOSIS + ": " + e.toString()); save(buzonSucesos); } //DICCIONARIO_VIAS_ADMINISTRACION try { logger.debug(" Iniciando la carga de " + DICCIONARIO_VIAS_ADMINISTRACION); viasAdminService.load(new File(dest.getAbsolutePath() + System.getProperty("file.separator") + DICCIONARIO_VIAS_ADMINISTRACION)); } catch (Exception e) { logger.warn(" No se ha podido cargar " + DICCIONARIO_VIAS_ADMINISTRACION + ": " + e.toString()); buzonSucesos = new BuzonSucesos(); buzonSucesos.setCodProceso(BuzonSucesos.DICCIONARIO_VIAS_ADMINISTRACION); buzonSucesos.setFecIni(new Date()); buzonSucesos.setFecFin(new Date()); buzonSucesos.setMensaje( "No se ha podido cargar " + DICCIONARIO_VIAS_ADMINISTRACION + ": " + e.toString()); save(buzonSucesos); } //DICCIONARIO_MEDICAMENTOS try { logger.debug(" Iniciando la carga de " + PRESCRIPCION); medicamentosService.load( new File(dest.getAbsolutePath() + System.getProperty("file.separator") + PRESCRIPCION)); } catch (Exception e) { logger.warn(" No se ha podido cargar " + PRESCRIPCION + ": " + e.toString()); buzonSucesos = new BuzonSucesos(); buzonSucesos.setCodProceso(BuzonSucesos.DICCIONARIO_MEDICAMENTOS); buzonSucesos.setFecIni(new Date()); buzonSucesos.setFecFin(new Date()); buzonSucesos.setMensaje("No se ha podido cargar " + PRESCRIPCION + ": " + e.toString()); save(buzonSucesos); } logger.debug(" Fichero: " + file.getOriginalFilename() + " procesado correctamente"); } catch (Exception e) { logger.error("Se han producido errores al cargar la base de datos de AEMPS: " + e.toString()); buzonSucesos = new BuzonSucesos(); buzonSucesos.setCodProceso(BuzonSucesos.AEMPS); buzonSucesos.setFecIni(new Date()); buzonSucesos.setFecFin(new Date()); buzonSucesos .setMensaje("Se han producido errores al cargar la base de datos de AEMPS: " + e.toString()); save(buzonSucesos); } finally { if (zip != null && zip.isFile()) { logger.debug(" Moviendo el fichero: " + zip.getName() + " al directorio: " + NOMENCLATORConstantes._TEMP + "old" + System.getProperty("file.separator")); try { FileUtils.moveFileToDirectory(zip, new File(NOMENCLATORConstantes._TEMP + "old" + System.getProperty("file.separator")), true); } catch (Exception e) { logger.warn(" No se ha podido mover el fichero al directorio OLD: " + e.toString()); } } if (dest != null && dest.isDirectory()) { logger.debug(" Eliminando ficheros temporales del directorio: " + dest.getAbsolutePath()); File[] ficheros = dest.listFiles(); for (int i = 0; i < ficheros.length; i++) { if (ficheros[i] != null && ficheros[i].isFile()) { ficheros[i].delete(); } } } } logger.info("FINALIZANDO la carga de la base de datos de AEMPS"); }
From source file:aiai.ai.launchpad.resource.ResourceController.java
@PostMapping(value = "/resource-upload-from-file") public String createResourceFromFile(MultipartFile file, @RequestParam(name = "code") String resourceCode, @RequestParam(name = "poolCode") String resourcePoolCode, final RedirectAttributes redirectAttributes) { File tempFile = globals.createTempFileForLaunchpad("temp-raw-file-"); if (tempFile.exists()) { tempFile.delete();/*from w w w .j a v a2 s.com*/ } try { FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile); } catch (IOException e) { redirectAttributes.addFlashAttribute("errorMessage", "#173.06 can't persist uploaded file as " + tempFile.getAbsolutePath() + ", error: " + e.toString()); return "redirect:/launchpad/resources"; } String originFilename = file.getOriginalFilename(); if (originFilename == null) { redirectAttributes.addFlashAttribute("errorMessage", "#172.01 name of uploaded file is null"); return "redirect:/launchpad/resources"; } String code = StringUtils.isNotBlank(resourceCode) ? resourceCode : resourcePoolCode + '-' + originFilename; try { resourceService.storeInitialResource(originFilename, tempFile, code, resourcePoolCode, true, originFilename); } catch (StoreNewPartOfRawFileException e) { log.error("Error", e); redirectAttributes.addFlashAttribute("errorMessage", "#172.04 An error while saving data to file, " + e.toString()); return "redirect:/launchpad/resources"; } return "redirect:/launchpad/resources"; }
From source file:com.sliu.framework.app.process.controller.ProcessXNController.java
/** * ?,??????API/*from ww w . ja v a 2 s . c o m*/ */ @RequestMapping(value = "/deployProcess", method = RequestMethod.POST) @ResponseBody public String deployProcess(@RequestParam("attachMentFile") MultipartFile multipartFile) throws FileNotFoundException { if (multipartFile != null && multipartFile.getSize() != 0) { //,??? FileCommonOperate fileCommonOperate = new FileCommonOperate(); try { String fileName = fileCommonOperate.uploadFile(multipartFile.getInputStream(), deployFilePath, multipartFile.getOriginalFilename()); InputStream fileInputStream = multipartFile.getInputStream(); String extension = FilenameUtils.getExtension(fileName); if (extension.equals("zip") || extension.equals("bar")) { ZipInputStream zip = new ZipInputStream(fileInputStream); repositoryService.createDeployment().addZipInputStream(zip).deploy(); } else { repositoryService.createDeployment().addInputStream(fileName, fileInputStream).deploy(); } } catch (IOException e) { e.printStackTrace(); } } return "{success:true}"; }
From source file:org.literacyapp.web.content.multimedia.video.VideoCreateController.java
@RequestMapping(method = RequestMethod.POST) public String handleSubmit(HttpSession session, /*@Valid*/ Video video, @RequestParam("bytes") MultipartFile multipartFile, BindingResult result, Model model) { logger.info("handleSubmit"); if (StringUtils.isBlank(video.getTitle())) { result.rejectValue("title", "NotNull"); } else {/*from ww w .j a va2 s . co m*/ Video existingVideo = videoDao.read(video.getTitle(), video.getLocale()); if (existingVideo != null) { result.rejectValue("title", "NonUnique"); } } try { byte[] bytes = multipartFile.getBytes(); if (multipartFile.isEmpty() || (bytes == null) || (bytes.length == 0)) { result.rejectValue("bytes", "NotNull"); } else { String originalFileName = multipartFile.getOriginalFilename(); logger.info("originalFileName: " + originalFileName); if (originalFileName.toLowerCase().endsWith(".m4v")) { video.setVideoFormat(VideoFormat.M4V); } else if (originalFileName.toLowerCase().endsWith(".mp4")) { video.setVideoFormat(VideoFormat.MP4); } else { result.rejectValue("bytes", "typeMismatch"); } if (video.getVideoFormat() != null) { String contentType = multipartFile.getContentType(); logger.info("contentType: " + contentType); video.setContentType(contentType); video.setBytes(bytes); // TODO: convert to a default video format? } } } catch (IOException e) { logger.error(e); } if (result.hasErrors()) { model.addAttribute("contentLicenses", ContentLicense.values()); model.addAttribute("literacySkills", LiteracySkill.values()); model.addAttribute("numeracySkills", NumeracySkill.values()); return "content/multimedia/video/create"; } else { video.setTitle(video.getTitle().toLowerCase()); video.setTimeLastUpdate(Calendar.getInstance()); videoDao.create(video); Contributor contributor = (Contributor) session.getAttribute("contributor"); ContentCreationEvent contentCreationEvent = new ContentCreationEvent(); contentCreationEvent.setContributor(contributor); contentCreationEvent.setContent(video); contentCreationEvent.setCalendar(Calendar.getInstance()); contentCreationEventDao.create(contentCreationEvent); if (EnvironmentContextLoaderListener.env == Environment.PROD) { String text = URLEncoder .encode(contributor.getFirstName() + " just added a new Video:\n" + " Language: " + video.getLocale().getLanguage() + "\n" + " Title: \"" + video.getTitle() + "\"\n" + " Video format: " + video.getVideoFormat() + "\n" + "See ") + "http://literacyapp.org/content/multimedia/video/list"; String iconUrl = contributor.getImageUrl(); SlackApiHelper.postMessage(Team.CONTENT_CREATION, text, iconUrl, "http://literacyapp.org/video/" + video.getId() + "." + video.getVideoFormat().toString().toLowerCase()); } return "redirect:/content/multimedia/video/list"; } }
From source file:gr.abiss.calipso.controller.AbstractServiceBasedRestController.java
@RequestMapping(value = "{subjectId}/uploads/{propertyName}", method = { RequestMethod.POST, RequestMethod.PUT }, consumes = {}, produces = { "application/json", "application/xml" }) public @ResponseBody BinaryFile addUploadsToProperty(@PathVariable ID subjectId, @PathVariable String propertyName, MultipartHttpServletRequest request, HttpServletResponse response) { LOGGER.info("uploadPost called"); Configuration config = ConfigurationFactory.getConfiguration(); String fileUploadDirectory = config.getString(ConfigurationFactory.FILES_DIR); String baseUrl = config.getString("calipso.baseurl"); Iterator<String> itr = request.getFileNames(); MultipartFile mpf; BinaryFile bf = new BinaryFile(); try {/*from w ww. j a va2s. com*/ if (itr.hasNext()) { mpf = request.getFile(itr.next()); LOGGER.info("Uploading {}", mpf.getOriginalFilename()); bf.setName(mpf.getOriginalFilename()); bf.setFileNameExtention( mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf(".") + 1)); bf.setContentType(mpf.getContentType()); bf.setSize(mpf.getSize()); // request targets specific path? StringBuffer uploadsPath = new StringBuffer('/') .append(this.service.getDomainClass().getDeclaredField("PATH_FRAGMENT").get(String.class)) .append('/').append(subjectId).append("/uploads/").append(propertyName); bf.setParentPath(uploadsPath.toString()); LOGGER.info("Saving image entity with path: " + bf.getParentPath()); bf = binaryFileService.create(bf); LOGGER.info("file name: {}", bf.getNewFilename()); bf = binaryFileService.findById(bf.getId()); LOGGER.info("file name: {}", bf.getNewFilename()); File storageDirectory = new File(fileUploadDirectory + bf.getParentPath()); if (!storageDirectory.exists()) { storageDirectory.mkdirs(); } LOGGER.info("storageDirectory: {}", storageDirectory.getAbsolutePath()); LOGGER.info("file name: {}", bf.getNewFilename()); File newFile = new File(storageDirectory, bf.getNewFilename()); newFile.createNewFile(); LOGGER.info("newFile path: {}", newFile.getAbsolutePath()); Files.copy(mpf.getInputStream(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING); BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290); File thumbnailFile = new File(storageDirectory, bf.getThumbnailFilename()); ImageIO.write(thumbnail, "png", thumbnailFile); bf.setThumbnailSize(thumbnailFile.length()); bf = binaryFileService.update(bf); // attach file // TODO: add/update to collection Field fileField = GenericSpecifications.getField(this.service.getDomainClass(), propertyName); Class clazz = fileField.getType(); if (BinaryFile.class.isAssignableFrom(clazz)) { T target = this.service.findById(subjectId); BeanUtils.setProperty(target, propertyName, bf); this.service.update(target); } bf.setUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/files/" + bf.getId()); bf.setThumbnailUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/thumbs/" + bf.getId()); bf.setDeleteUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/" + bf.getId()); bf.setDeleteType("DELETE"); bf.addInitialPreview("<img src=\"" + bf.getThumbnailUrl() + "\" class=\"file-preview-image\" />"); } } catch (Exception e) { LOGGER.error("Could not upload file(s) ", e); } // Map<String, Object> files= new HashMap<String, Object>(); //files.put("files", list); return bf; }
From source file:com.tela.pms.PatientController.java
/** * createPatient will create a new patient and save in the cloud db *///from www. j av a2s .c o m @RequestMapping(value = "/createPatient", method = RequestMethod.POST) public String createPatient(HttpServletRequest request, HttpServletResponse response, Model model, @RequestParam("file") MultipartFile file) { String view = "patient"; //Creating a new patient object String firstName = request.getParameter("fName"); String lastName = request.getParameter("lName"); 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 formatedString = request.getParameter("tags"); String tags = formatedString.toString().replace("[", "") //remove the right bracket .replace("]", ""); String patientName = firstName + " " + lastName; //Validating Empty fields 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"; } //Generating an unique id int id = 1001; List<Patient> pasList = patientService.retrieveAllPatients(); if (pasList != null) { if (pasList.size() > 1) { Collections.sort(pasList, new Comparator<Patient>() { @Override public int compare(Patient p1, Patient p2) { if (p1.getPatient_Id() > p1.getPatient_Id()) return 1; if (p1.getPatient_Id() < p2.getPatient_Id()) return -1; return 0; } }); id = pasList.get(pasList.size() - 1).getPatient_Id() + 1; } else if (pasList.size() == 1) { id = pasList.get(0).getPatient_Id() + 1; } else { id = 1001; } } else { id = 78 * new Date().getDay() * new Date().getSeconds(); } //Creating DateTime SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd hh:mm a", Locale.US); String createdAt = DATE_FORMAT.format(new Date()); //Retrieving uploaded files MultipartFile patientPhoto = file; //byte[] bFile_patientPhoto = null; String imagePath = "N/A"; String extensionFile = FilenameUtils.getExtension(patientPhoto.getOriginalFilename()); System.out.println(extensionFile); boolean value = extensionFile.equals("jpeg") || extensionFile.equals("jpg") || extensionFile.equals("JPG") || extensionFile.equals("JPEG"); if (patientPhoto != null && value) { 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(); } /* try { //bFile_patientPhoto = new byte[(int) patientPhoto.getSize()]; //InputStream inputStream_patientPhoto = patientPhoto.getInputStream(); //inputStream_patientPhoto.read(bFile_patientPhoto); //inputStream_patientPhoto.close(); } catch (IOException e) { e.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 (gender.equals("Female")) { imagePath = "resources/images/patient-female.png"; } else { imagePath = "resources/images/patient-male.png"; } } Patient patient = new Patient(); 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_CreatedAt(createdAt); patient.setPatient_Photo(imagePath); patient.setPatient_tags(tags); //System.out.println(patientName+" "+age+" "+patientPhoto.getOriginalFilename()+" "+nic+" "+address+" "+gender+" "+contactNo+" "+email); List<Patient> palist = patientService.retrieveAllPatients(); if (palist.size() == 0) { patientService.persistPatient(patient); logger.info("A New Patient " + id + " created @ " + new Date()); } else { if (palist != null && palist.size() > 0) { boolean isNewPatient = true; boolean isNotExistingPatient = true; for (Patient pati : palist) { if (pati.getPatient_Id() == id) { isNewPatient = false; logger.info("Similar patient with same id exists. " + id); view = "error1"; } if (pati.getPatient_Name().equals(patientName) && pati.getPatient_Photo().equals(imagePath) && pati.getPatient_Age().equals(age)) { logger.info("Similar patient exists."); view = "error1"; isNotExistingPatient = false; isNewPatient = false; } } if (isNewPatient || isNotExistingPatient) { patientService.persistPatient(patient); logger.info("A New Patient " + id + " created @ " + new Date()); } } } Patient newPatient = patientService.findPatientById(id); model.addAttribute("patient", newPatient); List<Prescription> prescriptions = prescriptionService.retrieveAllPrescriptionsByPatientId(id); model.addAttribute("prescriptions", prescriptions); logger.info("New Patient " + id + " retrieved @ " + new Date()); logger.info("Prescription list " + prescriptions + " retrieved @ " + new Date()); model.addAttribute("status", "<strong>Great !</strong> A New Patient created successfully"); model.addAttribute("style", "style=\"display:block;margin-top: 5px;\""); return view; }
From source file:net.duckling.ddl.web.controller.team.ConfigTeamController.java
@RequestMapping(method = RequestMethod.POST, params = "func=uploadMailList") public void uploadMailList(@RequestParam("qqfile") MultipartFile uplFile, HttpServletResponse response) throws IOException { InputStream in = uplFile.getInputStream(); String fileName = uplFile.getOriginalFilename(); uploadMailListCommon(fileName, in, response); }
From source file:com.orange.mmp.midlet.MidletManager.java
/** * Deploy an uploaded Midlet archive on PFS * @param uploadedFile The updloaded PFM file (MultipartFile to copy) *///from ww w . ja va2 s .c o m public void deployMidlet(MultipartFile uploadedFile) throws MMPException { String fileName = uploadedFile.getOriginalFilename(); File dstFile = new File(System.getProperty("java.io.tmpdir"), fileName); //Try to create file InputStream input = null; OutputStream output = null; try { input = uploadedFile.getInputStream(); output = new FileOutputStream(dstFile); IOUtils.copy(input, output); } catch (IOException ioe) { throw new MMPException("Failed to deploy PFM", ioe); } finally { try { if (input != null) input.close(); if (output != null) output.close(); } catch (IOException ioe) { //NOP } } this.deployMidlet(dstFile); }
From source file:com.opendesign.controller.ProductController.java
/** * ??() ?/// w w w . ja v a 2 s . c o m * * @param product * @param request * @param saveType * @return * @throws Exception */ private JsonModelAndView saveProduct(DesignWorkVO product, MultipartHttpServletRequest request, int saveType) throws Exception { /* * ?? ? ? */ boolean isUpdate = saveType == SAVE_TYPE_UPDATE; Map<String, Object> resultMap = new HashMap<String, Object>(); UserVO loginUser = CmnUtil.getLoginUser(request); if (loginUser == null || !StringUtil.isNotEmpty(loginUser.getSeq())) { resultMap.put("result", "100"); return new JsonModelAndView(resultMap); } /* ? ? */ if (isUpdate) { DesignWorkVO prevProduct = designerService.getDesignWork(product.getSeq()); if (!loginUser.getSeq().equals(prevProduct.getMemberSeq())) { resultMap.put("result", "101"); return new JsonModelAndView(resultMap); } } /* * ? ? */ MultipartFile fileUrlFile = request.getFile("fileUrlFile"); if (fileUrlFile != null) { String fileName = fileUrlFile.getOriginalFilename().toLowerCase(); if (!(fileName.endsWith(".jpg") || fileName.endsWith(".png"))) { resultMap.put("result", "202"); return new JsonModelAndView(resultMap); } } else { /* ? ? . */ if (!isUpdate) { resultMap.put("result", "201"); return new JsonModelAndView(resultMap); } } /* * license */ String license01 = request.getParameter("license01"); String license02 = request.getParameter("license02"); String license03 = request.getParameter("license03"); String license = license01 + license02 + license03; product.setLicense(license); //?? ?///// String stem = request.getParameter("origin"); if (stem == null) { product.setOriginSeq("0"); } else { product.setOriginSeq(stem); } ////////////////////////////// /* * ?? ? "0" */ String point = request.getParameter("point"); point = String.valueOf(CmnUtil.getIntValue(point)); //null--> 0 product.setPoint(point); /* * ? ? */ List<MultipartFile> productFileList = new ArrayList<MultipartFile>(); List<MultipartFile> openSourceFileList = new ArrayList<MultipartFile>(); Iterator<String> iterator = request.getFileNames(); while (iterator.hasNext()) { String fileNameKey = iterator.next(); MultipartFile reqFile = request.getFile(fileNameKey); if (reqFile != null) { boolean existProuductFile = fileNameKey.startsWith("productFile"); boolean existOpenSourceFile = fileNameKey.startsWith("openSourceFile"); if (existProuductFile || existOpenSourceFile) { long fileSize = reqFile.getSize(); if (fileSize > LIMIT_FILE_SIZE) { resultMap.put("result", "203"); resultMap.put("fileName", reqFile.getOriginalFilename()); return new JsonModelAndView(resultMap); } if (existProuductFile) { productFileList.add(reqFile); } if (existOpenSourceFile) { openSourceFileList.add(reqFile); } } } } product.setMemberSeq(loginUser.getSeq()); /* * ?? */ String fileUploadDir = CmnUtil.getFileUploadDir(request, FileUploadDomain.PRODUCT); File thumbFile = null; if (fileUrlFile != null) { String saveFileName = UUID.randomUUID().toString(); thumbFile = CmnUtil.saveFile(fileUrlFile, fileUploadDir, saveFileName); String fileUploadDbPath = CmnUtil.getFileUploadDbPath(request, thumbFile); product.setThumbUri(fileUploadDbPath); } /* * ??() */ List<DesignPreviewImageVO> productList = new ArrayList<DesignPreviewImageVO>(); List<String> productFilePaths = new ArrayList<>(); for (MultipartFile aFile : productFileList) { String saveFileName = UUID.randomUUID().toString(); File file = CmnUtil.saveFile(aFile, fileUploadDir, saveFileName); productFilePaths.add(file.getAbsolutePath()); String fileUploadDbPath = CmnUtil.getFileUploadDbPath(request, file); DesignPreviewImageVO productFile = new DesignPreviewImageVO(); productFile.setFilename(aFile.getOriginalFilename()); productFile.setFileUri(fileUploadDbPath); productList.add(productFile); } product.setImageList(productList); /* * */ List<DesignWorkFileVO> openSourceList = new ArrayList<DesignWorkFileVO>(); for (MultipartFile aFile : openSourceFileList) { String saveFileName = UUID.randomUUID().toString(); File file = CmnUtil.saveFile(aFile, fileUploadDir, saveFileName); String fileUploadDbPath = CmnUtil.getFileUploadDbPath(request, file); //openSourceFile? ??? client? . String filenameOpenSourceFile = StringUtils .stripToEmpty(request.getParameter("filename_" + aFile.getName())); DesignWorkFileVO openSourceFile = new DesignWorkFileVO(); openSourceFile.setFilename(filenameOpenSourceFile); openSourceFile.setFileUri(fileUploadDbPath); openSourceList.add(openSourceFile); } product.setFileList(openSourceList); /* * ??/? ? ? ? * ?? ? ? ? ? ? */ String thumbFilePath = ""; if (thumbFile != null) { thumbFilePath = thumbFile.getAbsolutePath(); } ThumbnailManager.resizeNClone4DesignWork(thumbFilePath, productFilePaths); /* * */ String tag = request.getParameter("tag"); if (StringUtil.isNotEmpty(tag)) { String[] tags = tag.split(","); int addIndex = 0; StringBuffer tagBuffer = new StringBuffer(); for (String aTag : tags) { if (StringUtil.isNotEmpty(aTag)) { aTag = aTag.trim(); tagBuffer.append(aTag); tagBuffer.append("|"); addIndex++; } if (addIndex >= 5) { break; } } if (addIndex > 0) { tagBuffer.insert(0, "|"); tag = tagBuffer.toString(); } } product.setTags(tag); String currentDate = Day.getCurrentTimestamp().substring(0, 12); product.setRegisterTime(currentDate); product.setUpdateTime(currentDate); String[] categoryCodes = request.getParameterValues("categoryCodes"); /* * */ if (isUpdate) { String[] removeProductSeqs = request.getParameterValues("removeProductSeq"); String[] removeOpenSourceSeqs = request.getParameterValues("removeOpenSourceSeq"); int projectSeq = service.updateProduct(product, categoryCodes, removeProductSeqs, removeOpenSourceSeqs); } else { int projectSeq = service.insertProduct(product, categoryCodes); } resultMap.put(RstConst.P_NAME, RstConst.V_SUCESS); return new JsonModelAndView(resultMap); }