List of usage examples for org.springframework.web.multipart MultipartFile getBytes
byte[] getBytes() throws IOException;
From source file:org.openmrs.module.sync.web.controller.ImportListController.java
@Override protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object obj, BindException errors) throws Exception { log.info("***********************************************************\n"); log.info("Inside SynchronizationImportListController"); // just fail fast if in the midst of refreshing the context, as this was causing issues, see SYNC-318 if (Context.isRefreshingContext()) { return null; }// ww w . j av a2 s .c om // There are 3 ways to come to this point, so we'll handle all of them: // 1) uploading a file (results in a file attachment as response) // 2) posting data to page (results in pure XML output) // 3) remote connection (with username + password, also posting data) (results in pure XML) // none of these result in user-friendly - so no comfy, user-friendly stuff needed here //outputing statistics: debug only! log.info("HttpServletRequest INFO:"); log.info("ContentType: " + request.getContentType()); log.info("CharacterEncoding: " + request.getCharacterEncoding()); log.info("ContentLength: " + request.getContentLength()); log.info("checksum: " + request.getParameter("checksum")); log.info("syncData: " + request.getParameter("syncData")); log.info("syncDataResponse: " + request.getParameter("syncDataResponse")); long checksum = 0; Integer serverId = 0; boolean isResponse = false; boolean isUpload = false; boolean useCompression = false; String contents = ""; String username = ""; String password = ""; //file-based upload, and multi-part form submission if (request instanceof MultipartHttpServletRequest) { log.info("Processing contents of syncDataFile multipart request parameter"); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; serverId = ServletRequestUtils.getIntParameter(multipartRequest, "serverId", 0); isResponse = ServletRequestUtils.getBooleanParameter(multipartRequest, "isResponse", false); useCompression = ServletRequestUtils.getBooleanParameter(multipartRequest, "compressed", false); isUpload = ServletRequestUtils.getBooleanParameter(multipartRequest, "upload", false); username = ServletRequestUtils.getStringParameter(multipartRequest, "username", ""); password = ServletRequestUtils.getStringParameter(multipartRequest, "password", ""); log.info("Request class: " + request.getClass()); log.info("serverId: " + serverId); log.info("upload = " + isUpload); log.info("compressed = " + useCompression); log.info("response = " + isResponse); log.info("username = " + username); log.info("Request content length: " + request.getContentLength()); MultipartFile multipartFile = multipartRequest.getFile("syncDataFile"); if (multipartFile != null && !multipartFile.isEmpty()) { InputStream inputStream = null; try { // Decompress content in file ConnectionResponse syncResponse = new ConnectionResponse( new ByteArrayInputStream(multipartFile.getBytes()), useCompression); log.info("Content to decompress: " + multipartFile.getBytes()); log.info("Content received: " + syncResponse.getResponsePayload()); log.info("Decompression Checksum: " + syncResponse.getChecksum()); contents = syncResponse.getResponsePayload(); checksum = syncResponse.getChecksum(); log.info("Final content: " + contents); } catch (Exception e) { log.warn("Unable to read in sync data file", e); } finally { IOUtils.closeQuietly(inputStream); } } } else { log.debug("seems we DO NOT have a file object"); } // prepare to process the input: contents now contains decompressed request ready to be processed SyncTransmissionResponse str = new SyncTransmissionResponse(); str.setErrorMessage(SyncConstants.ERROR_TX_NOT_UNDERSTOOD); str.setFileName(SyncConstants.FILENAME_TX_NOT_UNDERSTOOD); str.setUuid(SyncConstants.UUID_UNKNOWN); str.setSyncSourceUuid(SyncConstants.UUID_UNKNOWN); str.setSyncTargetUuid(SyncConstants.UUID_UNKNOWN); str.setState(SyncTransmissionState.TRANSMISSION_NOT_UNDERSTOOD); str.setTimestamp(new Date()); //set the timestamp of the response if (log.isInfoEnabled()) { log.info("CONTENT IN IMPORT CONTROLLER: " + contents); } //if no content, nothing to process just send back response if (contents == null || contents.length() < 0) { log.info("returning from ingest: nothing to process."); this.sendResponse(str, isUpload, response); return null; } // if this is option 3 (posting from remote server), we need to authenticate if (!Context.isAuthenticated()) { try { Context.authenticate(username, password); } catch (Exception e) { } } // Could not authenticate user: send back error if (!Context.isAuthenticated()) { str.setErrorMessage(SyncConstants.ERROR_AUTH_FAILED); str.setFileName(SyncConstants.FILENAME_AUTH_FAILED); str.setState(SyncTransmissionState.AUTH_FAILED); this.sendResponse(str, isUpload, response); return null; } //Fill-in the server uuid for the response: since request was authenticated we can start letting callers //know about us str.setSyncTargetUuid(Context.getService(SyncService.class).getServerUuid()); //Checksum check before doing anything at all: on unreliable networks we can get seemingly //valid HTTP POST but content is messed up, defend against it with custom checksums long checksumReceived = ServletRequestUtils.getLongParameter(request, "checksum", -1); log.info("checksum value received in POST: " + checksumReceived); log.info("checksum value of payload: " + checksum); log.info("SIZE of payload: " + contents.length()); if (checksumReceived > 0 && (checksumReceived != checksum)) { log.error("ERROR: FAILED CHECKSUM!"); str.setState(SyncTransmissionState.TRANSMISSION_NOT_UNDERSTOOD); this.sendResponse(str, isUpload, response); return null; } //Test message. Test message was sent (i.e. using 'test connection' button on server screen) //just send empty acknowledgment if (SyncConstants.TEST_MESSAGE.equals(contents)) { str.setErrorMessage(""); str.setState(SyncTransmissionState.OK); str.setUuid(""); str.setFileName(SyncConstants.FILENAME_TEST); this.sendResponse(str, isUpload, response); return null; } if (SyncConstants.CLONE_MESSAGE.equals(contents)) { try { log.info("CLONE MESSAGE RECEIVED, TRYING TO CLONE THE DB"); File file = Context.getService(SyncService.class).generateDataFile(); StringWriter writer = new StringWriter(); IOUtils.copy(new FileInputStream(file), writer); this.sendCloneResponse(writer.toString(), response, false); boolean clonedDBLog = Boolean.parseBoolean(Context.getAdministrationService() .getGlobalProperty(SyncConstants.PROPERTY_SYNC_CLONED_DATABASE_LOG_ENABLED, "true")); if (!clonedDBLog) { file.delete(); } } catch (Exception ex) { log.warn(ex.toString()); ex.printStackTrace(); } return null; } /************************************************************************************************************************* * This is a real transmission: - user was properly authenticated - checksums match - it is * not a test transmission Start processing! 1. Deserialize what was sent; it can be either * SyncTransmssion, or SyncTransmissionResponse 2. If it is a response, *************************************************************************************************************************/ SyncTransmission st = null; if (!isResponse) { //this is not 'response' to something we sent out; thus the contents should contain plan SyncTransmission try { log.info("xml to sync transmission with contents: " + contents); st = SyncDeserializer.xmlToSyncTransmission(contents); } catch (Exception e) { log.error("Unable to deserialize the following: " + contents, e); str.setErrorMessage("Unable to deserialize transmission contents into SyncTansmission."); str.setState(SyncTransmissionState.TRANSMISSION_NOT_UNDERSTOOD); this.sendResponse(str, isUpload, response); return null; } } else { log.info("Processing a response, not a transmission"); SyncTransmissionResponse priorResponse = null; try { // this is the confirmation of receipt of previous transmission priorResponse = SyncDeserializer.xmlToSyncTransmissionResponse(contents); log.info("This is a response from a previous transmission. Uuid is: " + priorResponse.getUuid()); } catch (Exception e) { log.error("Unable to deserialize the following: " + contents, e); str.setErrorMessage("Unable to deserialize transmission contents into SyncTransmissionResponse."); str.setState(SyncTransmissionState.TRANSMISSION_NOT_UNDERSTOOD); this.sendResponse(str, isUpload, response); return null; } // figure out where this came from: // for responses, the target ID contains the server that generated the response String sourceUuid = priorResponse.getSyncTargetUuid(); log.info("SyncTransmissionResponse has a sourceUuid of " + sourceUuid); RemoteServer origin = Context.getService(SyncService.class).getRemoteServer(sourceUuid); if (origin == null) { log.error("Source server not registered locally. Unable to find source server by uuid: " + sourceUuid); str.setErrorMessage( "Source server not registered locally. Unable to find source server by uuid " + sourceUuid); str.setState(SyncTransmissionState.INVALID_SERVER); this.sendResponse(str, isUpload, response); return null; } else { log.info("Found source server by uuid: " + sourceUuid + " = " + origin.getNickname()); log.info("Source server is " + origin.getNickname()); } if (priorResponse == null) { } // process response that was sent to us; the sync response normally contains: //a) results of the records that we sent out //b) new records from 'source' to be applied against this server if (priorResponse.getSyncImportRecords() == null) { log.debug("No records to process in response"); } else { // now process each incoming syncImportRecord, this is just status update for (SyncImportRecord importRecord : priorResponse.getSyncImportRecords()) { Context.getService(SyncIngestService.class).processSyncImportRecord(importRecord, origin); } } // now pull out the data that originated on the 'source' server and try to process it st = priorResponse.getSyncTransmission(); } // now process the syncTransmission if one was received if (st != null) { str = SyncUtilTransmission.processSyncTransmission(st, SyncUtil.getGlobalPropetyValueAsInteger(SyncConstants.PROPERTY_NAME_MAX_RECORDS_WEB)); } else log.info("st was null"); //send response this.sendResponse(str, isUpload, response); // never a situation where we want to actually use the model/view - either file download or http request return null; }
From source file:org.opentestsystem.shared.progman.rest.AssetPoolController.java
@ResponseStatus(HttpStatus.CREATED) @RequestMapping(value = "/assetPool/{assetPoolId}/assetFile", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = { MediaType.TEXT_PLAIN_VALUE })/*from w w w .jav a 2s . com*/ @Secured({ "ROLE_Progman Admin" }) @ResponseBody public String uploadAssetFile(@RequestParam("assetFile") final MultipartFile assetFile, @PathVariable final String assetPoolId, final HttpServletRequest request, final HttpServletResponse response) throws IOException { String jsonAsStringForIE = null; Asset savedFile; try { savedFile = assetPoolService.saveAssetFile(assetPoolId, assetFile.getOriginalFilename(), assetFile.getBytes(), assetFile.getContentType()); jsonAsStringForIE = objectMapper.writeValueAsString(savedFile); } catch (LocalizedException e) { // return a 201 here - // IE9 and browsers which require iframe transport must receive an OK status to get the response result after file upload jsonAsStringForIE = objectMapper.writeValueAsString(super.handleException(e)); } catch (IOException e) { // return a 201 here - // IE9 and browsers which require iframe transport must receive an OK status to get the response result after file upload jsonAsStringForIE = objectMapper.writeValueAsString(super.handleException(e)); } return jsonAsStringForIE; }
From source file:org.qifu.controller.CommonUploadDownloadAction.java
@ControllerMethodAuthority(check = true, programId = "CORE_PROGCOMM0003Q") @RequestMapping(value = "/core.commonUploadFileJson.do", method = { RequestMethod.POST }, headers = "content-type=multipart/*") public @ResponseBody DefaultControllerJsonResultObj<String> uploadFile( @RequestParam("commonUploadFile") MultipartFile file, @RequestParam("commonUploadFileType") String type, @RequestParam("commonUploadFileIsFileMode") String isFile, @RequestParam("commonUploadFileSystem") String system) { DefaultControllerJsonResultObj<String> result = this.getDefaultJsonResult("CORE_PROGCOMM0003Q"); if (!this.isAuthorizeAndLoginFromControllerJsonResult(result)) { return result; }/*from w ww.jav a2s . co m*/ if (null == file || file.getSize() < 1) { result.setMessage(SysMessageUtil.get(SysMsgConstants.UPLOAD_FILE_NO_SELECT)); return result; } if (file.getSize() > UPLOAD_MAX_SIZE) { result.setMessage("File max size only " + UPLOAD_MAX_SIZE + " bytes!"); return result; } if (!UploadTypes.check(type)) { result.setMessage(SysMessageUtil.get(SysMsgConstants.UPLOAD_FILE_TYPE_ERROR)); return result; } try { String uploadOid = UploadSupportUtils.create(system, type, (YES.equals(isFile) ? true : false), file.getBytes(), file.getOriginalFilename()); if (!StringUtils.isBlank(uploadOid)) { result.setSuccess(YES); result.setValue(uploadOid); result.setMessage(SysMessageUtil.get(SysMsgConstants.INSERT_SUCCESS)); } else { result.setMessage(SysMessageUtil.get(SysMsgConstants.INSERT_FAIL)); } } catch (AuthorityException | ServiceException | ControllerException e) { result.setMessage(e.getMessage().toString()); } catch (Exception e) { exceptionResult(result, e); } return result; }
From source file:org.springframework.cloud.config.server.EncryptionController.java
@RequestMapping(value = "/key", method = RequestMethod.POST, params = { "password" }) public ResponseEntity<Map<String, Object>> uploadKeyStore(@RequestParam("file") MultipartFile file, @RequestParam("password") String password, @RequestParam("alias") String alias) { Map<String, Object> body = new HashMap<String, Object>(); body.put("status", "OK"); try {/*w ww .ja v a 2s .c om*/ ByteArrayResource resource = new ByteArrayResource(file.getBytes()); KeyPair keyPair = new KeyStoreKeyFactory(resource, password.toCharArray()).getKeyPair(alias); encryptor = new RsaSecretEncryptor(keyPair); body.put("publicKey", ((RsaKeyHolder) encryptor).getPublicKey()); } catch (IOException e) { throw new KeyFormatException(); } return new ResponseEntity<Map<String, Object>>(body, HttpStatus.CREATED); }
From source file:org.springframework.cloud.netflix.zuul.FormZuulServletProxyApplicationTests.java
@RequestMapping(value = "/file", method = RequestMethod.POST) public String file(@RequestParam(required = false) MultipartFile file) throws IOException { byte[] bytes = new byte[0]; if (file != null) { if (file.getSize() > 1024) { bytes = new byte[1024]; InputStream inputStream = file.getInputStream(); inputStream.read(bytes);/*ww w . j a v a 2s .co m*/ byte[] buffer = new byte[1024 * 1024 * 10]; while (inputStream.read(buffer) >= 0) { log.info("Read more bytes"); } } else { bytes = file.getBytes(); } } return "Posted! " + new String(bytes); }
From source file:org.springframework.integration.http.DefaultInboundRequestMapper.java
@SuppressWarnings("unchecked") private Object createPayloadFromMultipartRequest(MultipartHttpServletRequest multipartRequest) { Map<String, Object> payloadMap = new HashMap<String, Object>(multipartRequest.getParameterMap()); Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) { MultipartFile multipartFile = entry.getValue(); if (multipartFile.isEmpty()) { continue; }//from w w w . j a va 2s. co m try { if (this.copyUploadedFiles) { File tmpFile = File.createTempFile("si_", null); multipartFile.transferTo(tmpFile); payloadMap.put(entry.getKey(), tmpFile); if (logger.isDebugEnabled()) { logger.debug("copied uploaded file [" + multipartFile.getOriginalFilename() + "] to temporary file [" + tmpFile.getAbsolutePath() + "]"); } } else if (multipartFile.getContentType() != null && multipartFile.getContentType().startsWith("text")) { String multipartFileAsString = this.multipartCharset != null ? new String(multipartFile.getBytes(), this.multipartCharset) : new String(multipartFile.getBytes()); payloadMap.put(entry.getKey(), multipartFileAsString); } else { payloadMap.put(entry.getKey(), multipartFile.getBytes()); } } catch (IOException e) { throw new IllegalArgumentException("Cannot read contents of multipart file", e); } } return Collections.unmodifiableMap(payloadMap); }
From source file:org.springframework.samples.petclinic.web.validator.multipart.MultipartValidator.java
@Override public boolean isValid(MultipartFile multipartFile, ConstraintValidatorContext ctx) { String[] allowedFileTypes = multipart.fileTypes(); byte[] fileByte = null; if (multipartFile == null) { return false; } else {/*w w w . java 2 s. c o m*/ try { String fileExt = FilenameUtils.getExtension(multipartFile.getOriginalFilename()); // Check file extension allowed or not. if (!Arrays.asList(allowedFileTypes).contains(fileExt)) { return false; } fileByte = multipartFile.getBytes(); // Check file size. if (fileByte.length == 0) { return false; } return true; } catch (IOException ex) { Logger.getLogger(MultipartValidator.class.getName()).log(Level.SEVERE, null, ex); } } return false; }
From source file:org.springframework.web.multipart.support.ByteArrayMultipartFileEditor.java
public void setValue(Object value) { if (value instanceof MultipartFile) { MultipartFile multipartFile = (MultipartFile) value; try {/* w w w. j a v a2s .c om*/ super.setValue(multipartFile.getBytes()); } catch (IOException ex) { logger.warn("Cannot read contents of multipart file", ex); throw new IllegalArgumentException("Cannot read contents of multipart file: " + ex.getMessage()); } } else if (value instanceof byte[]) { super.setValue(value); } else { super.setValue(value != null ? value.toString().getBytes() : null); } }
From source file:org.springframework.web.multipart.support.StringMultipartFileEditor.java
public void setValue(Object value) { if (value instanceof MultipartFile) { MultipartFile multipartFile = (MultipartFile) value; try {//from w ww . j av a 2 s . c o m super.setValue(this.charsetName != null ? new String(multipartFile.getBytes(), this.charsetName) : new String(multipartFile.getBytes())); } catch (IOException ex) { logger.warn("Cannot read contents of multipart file", ex); throw new IllegalArgumentException("Cannot read contents of multipart file: " + ex.getMessage()); } } else { super.setValue(value); } }
From source file:org.telscenter.sail.webapp.presentation.web.controllers.admin.UploadProjectController.java
/** * @override @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException) */// w w w . ja va2 s .c o m @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { // probably should do some kind of virus check. but for now, it's only // accessible to admin. // uploaded file must be a zip file and have a .zip extension ProjectUpload projectUpload = (ProjectUpload) command; MultipartFile file = projectUpload.getFile(); // upload the zipfile to curriculum_base_dir String curriculumBaseDir = portalProperties.getProperty("curriculum_base_dir"); File uploadDir = new File(curriculumBaseDir); if (!uploadDir.exists()) { throw new Exception("curriculum upload directory does not exist."); } // save the upload zip file in the curriculum folder. String sep = System.getProperty("file.separator"); long timeInMillis = Calendar.getInstance().getTimeInMillis(); String zipFilename = file.getOriginalFilename(); String filename = zipFilename.substring(0, zipFilename.indexOf(".zip")); String newFilename = filename; if (new File(curriculumBaseDir + sep + filename).exists()) { // if this directory already exists, add a date time in milliseconds to the filename to make it unique newFilename = filename + "-" + timeInMillis; } String newFileFullPath = curriculumBaseDir + sep + newFilename + ".zip"; // copy the zip file inside curriculum_base_dir temporarily File uploadedFile = new File(newFileFullPath); uploadedFile.createNewFile(); FileCopyUtils.copy(file.getBytes(), uploadedFile); // make a new folder where the contents of the zip should go String newFileFullDir = curriculumBaseDir + sep + newFilename; File newFileFullDirFile = new File(newFileFullDir); newFileFullDirFile.mkdir(); // unzip the zip file try { ZipFile zipFile = new ZipFile(newFileFullPath); Enumeration entries = zipFile.entries(); int i = 0; // index used later to check for first folder in the zip file while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.getName().startsWith("__MACOSX")) { // if this entry starts with __MACOSX, this zip file was created by a user using mac's "compress" feature. // ignore it. continue; } if (entry.isDirectory()) { // first check to see if the user has changed the zip file name and therefore the zipfile name // is no longer the same as the name of the first folder in the top-level of the zip file. // if this is the case, import will fail, so throw an error. if (i == 0) { if (!entry.getName().startsWith(filename)) { throw new Exception( "Zip file name does not match folder name. Do not change zip filename"); } i++; } // Assume directories are stored parents first then children. System.out.println("Extracting directory: " + entry.getName()); // This is not robust, just for demonstration purposes. (new File(entry.getName().replace(filename, newFileFullDir))).mkdir(); continue; } System.out.println("Extracting file: " + entry.getName()); copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream( new FileOutputStream(entry.getName().replaceFirst(filename, newFileFullDir)))); } zipFile.close(); } catch (IOException ioe) { System.err.println("Unhandled exception during project import. Project was not properly imported."); ioe.printStackTrace(); throw ioe; } // remove the temp zip file uploadedFile.delete(); // now create a project in the db with the new path String path = sep + newFilename + sep + "wise4.project.json"; String name = projectUpload.getName(); User signedInUser = ControllerUtil.getSignedInUser(); Set<User> owners = new HashSet<User>(); owners.add(signedInUser); CreateUrlModuleParameters cParams = new CreateUrlModuleParameters(); cParams.setUrl(path); Curnit curnit = curnitService.createCurnit(cParams); ProjectParameters pParams = new ProjectParameters(); pParams.setCurnitId(curnit.getId()); pParams.setOwners(owners); pParams.setProjectname(name); pParams.setProjectType(ProjectType.LD); ProjectMetadata metadata = null; // see if a file called wise4.project-meta.json exists. if yes, try parsing it. try { String projectMetadataFilePath = newFileFullDir + sep + "wise4.project-meta.json"; String projectMetadataStr = FileUtils.readFileToString(new File(projectMetadataFilePath)); JSONObject metadataJSONObj = new JSONObject(projectMetadataStr); metadata = new ProjectMetadataImpl(); metadata.populateFromJSON(metadataJSONObj); } catch (Exception e) { // if there is any error during the parsing of the metadata, set the metadata to null metadata = null; } // If metadata is null at this point, either wise4.project-meta.json was not // found in the zip file, or there was an error parsing. // Set a new fresh metadata object if (metadata == null) { metadata = new ProjectMetadataImpl(); metadata.setTitle(name); } pParams.setMetadata(metadata); Project project = projectService.createProject(pParams); ModelAndView modelAndView = new ModelAndView(getSuccessView()); modelAndView.addObject("msg", "Upload project complete, new projectId is: " + project.getId()); return modelAndView; }