Example usage for org.springframework.web.multipart MultipartFile getInputStream

List of usage examples for org.springframework.web.multipart MultipartFile getInputStream

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartFile getInputStream.

Prototype

@Override
InputStream getInputStream() throws IOException;

Source Link

Document

Return an InputStream to read the contents of the file from.

Usage

From source file:com.groupon.odo.controllers.BackupController.java

/**
 * Set client server configuration and overrides according to backup
 *
 * @param fileData File containing profile overrides and server configuration
 * @param profileID Profile to update for client
 * @param clientUUID Client to apply overrides to
 * @param odoImport Param to determine if an odo config will be imported with the overrides import
 * @return/*from  ww  w .ja  v  a 2 s. c  om*/
 * @throws Exception
 */
@RequestMapping(value = "/api/backup/profile/{profileID}/{clientUUID}", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<String> processSingleProfileBackup(
        @RequestParam("fileData") MultipartFile fileData, @PathVariable int profileID,
        @PathVariable String clientUUID,
        @RequestParam(value = "odoImport", defaultValue = "false") boolean odoImport) throws Exception {
    if (!fileData.isEmpty()) {
        try {
            // Read in file
            InputStream inputStream = fileData.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String singleLine;
            String fullFileString = "";
            while ((singleLine = bufferedReader.readLine()) != null) {
                fullFileString += singleLine;
            }
            JSONObject fileBackup = new JSONObject(fullFileString);

            if (odoImport) {
                JSONObject odoBackup = fileBackup.getJSONObject("odoBackup");
                byte[] bytes = odoBackup.toString().getBytes();
                // Save to second file to be used in importing odo configuration
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(new File("backup-uploaded.json")));
                stream.write(bytes);
                stream.close();
                File f = new File("backup-uploaded.json");
                BackupService.getInstance().restoreBackupData(new FileInputStream(f));
            }

            // Get profile backup if json contained both profile backup and odo backup
            if (fileBackup.has("profileBackup")) {
                fileBackup = fileBackup.getJSONObject("profileBackup");
            }

            // Import profile overrides
            BackupService.getInstance().setProfileFromBackup(fileBackup, profileID, clientUUID);
        } catch (Exception e) {
            try {
                JSONArray errorArray = new JSONArray(e.getMessage());
                return new ResponseEntity<>(errorArray.toString(), HttpStatus.BAD_REQUEST);
            } catch (Exception k) {
                // Catch for exceptions other than ones defined in backup service
                return new ResponseEntity<>("[{\"error\" : \"Upload Error\"}]", HttpStatus.BAD_REQUEST);
            }
        }
    }

    return new ResponseEntity<>(HttpStatus.OK);
}

From source file:com.esri.geoportal.harvester.rest.TaskController.java

@RequestMapping(value = "/rest/harvester/tasks/upload", method = RequestMethod.POST)
public ResponseEntity<TaskResponse> handleImport(@RequestParam("file") MultipartFile file) {
    try (InputStream inputStream = file.getInputStream()) {
        try {/* w w w. ja v a 2s  . c  om*/
            TaskDefinition taskDefinition = deserialize(inputStream, TaskDefinition.class);
            LOG.debug(formatForLog("POST /rest/harvester/tasks/upload <-- %s", taskDefinition));
            UUID id = engine.getTasksService().addTaskDefinition(taskDefinition);
            return new ResponseEntity<>(new TaskResponse(id, taskDefinition), HttpStatus.OK);
        } catch (IOException | DataProcessorException ex) {
            LOG.error(String.format("Error uploading task"), ex);
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    } catch (IOException ex) {
        LOG.error(String.format("Error uploading task"), ex);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:se.vgregion.social.controller.publicprofile.PublicProfileController.java

@ActionMapping(params = "action=uploadProfileImage")
public void uploadProfileImage(MultipartActionRequest request) throws IOException, SocialServiceException {
    MultipartFile profileImageInput = request.getFile("profileImage");

    if (profileImageInput == null || profileImageInput.getSize() <= 0) {
        return;/*from w  ww  .  j a v  a  2 s .  co  m*/
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    final int croppedWidth = 160;
    final int croppedHeight = 160;

    BufferedImage bufferedImage = ImageIO.read(profileImageInput.getInputStream());

    ImageUtil.writeImageToStream(baos, croppedWidth, croppedHeight, bufferedImage);

    long loggedInUserId = getLoggedInUserId(request);
    service.updatePortrait(loggedInUserId, baos.toByteArray());
}

From source file:org.openlmis.fulfillment.service.TemplateServiceTest.java

@Test
public void shouldValidateFileAndSetDataIfDefaultValueExpressionIsNull() throws Exception {
    MultipartFile file = mock(MultipartFile.class);
    when(file.getOriginalFilename()).thenReturn(NAME_OF_FILE);

    mockStatic(JasperCompileManager.class);
    JasperReport report = mock(JasperReport.class);
    InputStream inputStream = mock(InputStream.class);
    when(file.getInputStream()).thenReturn(inputStream);

    JRParameter param1 = mock(JRParameter.class);
    JRParameter param2 = mock(JRParameter.class);
    JRPropertiesMap propertiesMap = mock(JRPropertiesMap.class);
    JRExpression jrExpression = mock(JRExpression.class);
    String[] propertyNames = { DISPLAY_NAME };

    when(report.getParameters()).thenReturn(new JRParameter[] { param1, param2 });
    when(JasperCompileManager.compileReport(inputStream)).thenReturn(report);
    when(propertiesMap.getPropertyNames()).thenReturn(propertyNames);
    when(propertiesMap.getProperty(DISPLAY_NAME)).thenReturn(PARAM_DISPLAY_NAME);

    when(param1.getPropertiesMap()).thenReturn(propertiesMap);
    when(param1.getValueClassName()).thenReturn("String");
    when(param1.getDefaultValueExpression()).thenReturn(jrExpression);
    when(jrExpression.getText()).thenReturn("text");

    when(param2.getPropertiesMap()).thenReturn(propertiesMap);
    when(param2.getValueClassName()).thenReturn("Integer");
    when(param2.getDefaultValueExpression()).thenReturn(null);

    ByteArrayOutputStream byteOutputStream = mock(ByteArrayOutputStream.class);
    whenNew(ByteArrayOutputStream.class).withAnyArguments().thenReturn(byteOutputStream);
    ObjectOutputStream objectOutputStream = spy(new ObjectOutputStream(byteOutputStream));
    whenNew(ObjectOutputStream.class).withArguments(byteOutputStream).thenReturn(objectOutputStream);
    doNothing().when(objectOutputStream).writeObject(report);
    byte[] byteData = new byte[1];
    when(byteOutputStream.toByteArray()).thenReturn(byteData);
    Template template = new Template();

    templateService.validateFileAndInsertTemplate(template, file);

    verify(templateRepository).save(template);
    assertThat(template.getTemplateParameters().get(0).getDisplayName(), is(PARAM_DISPLAY_NAME));
}

From source file:de.iteratec.iteraplan.presentation.dialog.ExcelImport.ExcelImportController.java

/**
 * Test if file is valid (via checkFile()), and return InputStream if so
 * //from  w w  w.  j a  va  2 s  .  c om
 * @return InputStream from a file if it is valid; null otherwise
 */
private InputStream getInputStreamFromFileIfValid(MultipartFile file) {
    // Check if Valid
    if (!this.checkFile(file)) {
        return null;
    }

    // Convert File to Input Stream
    InputStream is;
    try {
        is = file.getInputStream();
    } catch (IOException e) {
        LOGGER.error(e);
        return null;
    }
    return is;
}

From source file:com.eryansky.modules.disk.utils.DiskUtils.java

/**
 * ?/*www . j a  v  a2s  . com*/
 *
 * @param folderCode
 *            ?
 * @param sessionInfo
 *            session? ??null
 * @param multipartFile
 *             SpringMVC
 * @return
 * @throws InvalidExtensionException
 * @throws FileUploadBase.FileSizeLimitExceededException
 * @throws FileNameLengthLimitExceededException
 * @throws IOException
 */
public static File saveSystemFile(String folderCode, SessionInfo sessionInfo, MultipartFile multipartFile)
        throws InvalidExtensionException, FileUploadBase.FileSizeLimitExceededException,
        FileNameLengthLimitExceededException, IOException {
    String userId = null;
    if (sessionInfo != null && sessionInfo.getUserId() != null) {
        userId = sessionInfo.getUserId();
    }

    String code = FileUploadUtils.encodingFilenamePrefix(userId + "", multipartFile.getOriginalFilename());
    Folder folder = getSystemFolderByCode(folderCode, userId);
    String storeFilePath = iFileManager.getStorePath(folder, userId, multipartFile.getOriginalFilename());
    File file = new File();
    file.setFolder(folder);
    file.setCode(code);
    file.setUserId(userId);
    file.setName(multipartFile.getOriginalFilename());
    file.setFilePath(storeFilePath);
    file.setFileSize(multipartFile.getSize());
    file.setFileSuffix(FilenameUtils.getExtension(multipartFile.getOriginalFilename()));
    iFileManager.saveFile(file.getFilePath(), multipartFile.getInputStream(), true);
    diskManager.saveFile(file);
    return file;
}

From source file:com.egeniuss.appmarket.controller.AppManagerController.java

@RequestMapping("/uploadApp.html")
public @ResponseBody Map<String, Object> uploadApp(@RequestParam(required = false) MultipartFile app,
        HttpServletRequest request) {/*w w w.j a  v  a  2 s.  c o  m*/
    Date now = new Date();
    long time = now.getTime();
    String appFileName = app.getOriginalFilename();
    String realFileName = time + appFileName.substring(appFileName.lastIndexOf("."));
    Map<String, Object> msg = new HashMap<String, Object>();
    try {
        FileUtils.copyInputStreamToFile(app.getInputStream(), new File(appStore.concat(realFileName)));
    } catch (IOException e) {
        LOGGER.error("?", e);
        msg.put("errcode", -1);
        msg.put("errmsg", "<br/>" + e.getMessage());
        return msg;
    }
    SimpleDateFormat formator = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    StringTokenizer linemsg = new StringTokenizer(request.getParameter("releaseNote"), "\n");
    StringBuilder releaseNoteSb = new StringBuilder();
    while (linemsg.hasMoreElements()) {
        releaseNoteSb.append(linemsg.nextElement()).append("\\n");
    }
    Object[] args = new Object[] { time, request.getParameter("appKey"), request.getParameter("appPlatform"),
            request.getParameter("appEnv"), request.getParameter("versionNum"), app.getSize(),
            releaseNoteSb.toString(), realFileName, formator.format(now) };
    int[] argTypes = new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
            Types.DECIMAL, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR };
    jdbcTemplate.update(
            "insert into APP_MARKET (APP_ID, APP_KEY, APP_PLATFORM, APP_ENV, VERSION_NUM, APP_SIZE, RELEASE_NOTE, FILE_NAME, CREATE_TIME) values (?, ?, ?, ?, ?, ?, ?, ?, ?)",
            args, argTypes);
    msg.put("errcode", 0);
    msg.put("errmsg", "ok");
    return msg;
}

From source file:eionet.transfer.dao.UploadsServiceSwift.java

@Override
public void storeFile(MultipartFile myFile, String fileId, int fileTTL) throws IOException {
    if (swiftUsername == null) {
        System.out.println("Swift username is not configured");
    }// w  w  w.jav  a  2s.  c o  m
    assert swiftUsername != null;
    if (config == null) {
        login();
    }
    StoredObject swiftObject = container.getObject(fileId);
    swiftObject.uploadObject(myFile.getInputStream());
    if (myFile.getContentType() != null) {
        swiftObject.setContentType(myFile.getContentType());
    }

    Map<String, Object> metadata = new HashMap<String, Object>();
    if (myFile.getOriginalFilename() != null) {
        metadata.put("filename", myFile.getOriginalFilename());
    }
    if (myFile.getContentType() != null) {
        metadata.put("content-type", myFile.getContentType());
    }
    swiftObject.setMetadata(metadata);
    swiftObject.saveMetadata();
    //swiftObject.setDeleteAt(Date date);
}

From source file:org.ktunaxa.referral.server.mvc.UploadDocumentController.java

@RequestMapping(value = "/upload/referral/document", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam(KtunaxaConstant.FORM_ID) String formId,
        @RequestParam(KtunaxaConstant.FORM_REFERRAL) String referralId,
        @RequestParam(value = KtunaxaConstant.FORM_OVERRIDE, required = false) String override,
        @RequestParam("file") MultipartFile file, Model model) {

    UploadResponse response = new UploadResponse();
    response.addObject(KtunaxaConstant.FORM_ID, formId);
    try {/*from w  w  w  .j a  v a 2  s. c o m*/
        String year = "20" + referralId.substring(8, 10);
        String originalFilename = file.getOriginalFilename();
        Document document;
        if (override != null && "true".equalsIgnoreCase(override)) {
            document = cmisService.saveOrUpdate(originalFilename, file.getContentType(), file.getInputStream(),
                    file.getSize(), year, referralId);
        } else {
            document = cmisService.create(originalFilename, file.getContentType(), file.getInputStream(),
                    file.getSize(), year, referralId);
        }
        response.addObject(KtunaxaConstant.FORM_DOCUMENT_TITLE, originalFilename);
        response.addObject(KtunaxaConstant.FORM_DOCUMENT_ID, document.getId());
        response.addObject(KtunaxaConstant.FORM_DOCUMENT_DISPLAY_URL, cmisService.getDisplayUrl(document));
        response.addObject(KtunaxaConstant.FORM_DOCUMENT_DOWNLOAD_URL, cmisService.getDownloadUrl(document));
        model.addAttribute(UploadView.RESPONSE, response);
    } catch (Exception e) {
        log.error("Could not upload document", e);
        response.setException(e);
    }
    model.addAttribute(UploadView.RESPONSE, response);
    return UploadView.NAME;
}

From source file:org.openlmis.fulfillment.service.TemplateServiceTest.java

@Test
public void shouldValidateFileAndSetData() throws Exception {
    MultipartFile file = mock(MultipartFile.class);
    when(file.getOriginalFilename()).thenReturn(NAME_OF_FILE);

    mockStatic(JasperCompileManager.class);
    JasperReport report = mock(JasperReport.class);
    InputStream inputStream = mock(InputStream.class);
    when(file.getInputStream()).thenReturn(inputStream);

    JRParameter param1 = mock(JRParameter.class);
    JRParameter param2 = mock(JRParameter.class);
    JRPropertiesMap propertiesMap = mock(JRPropertiesMap.class);
    JRExpression jrExpression = mock(JRExpression.class);

    String[] propertyNames = { DISPLAY_NAME };
    when(report.getParameters()).thenReturn(new JRParameter[] { param1, param2 });
    when(JasperCompileManager.compileReport(inputStream)).thenReturn(report);
    when(propertiesMap.getPropertyNames()).thenReturn(propertyNames);
    when(propertiesMap.getProperty(DISPLAY_NAME)).thenReturn(PARAM_DISPLAY_NAME);

    when(param1.getPropertiesMap()).thenReturn(propertiesMap);
    when(param1.getValueClassName()).thenReturn("String");
    when(param1.getName()).thenReturn("name");
    when(param1.getDescription()).thenReturn("desc");
    when(param1.getDefaultValueExpression()).thenReturn(jrExpression);
    when(jrExpression.getText()).thenReturn("text");

    when(param2.getPropertiesMap()).thenReturn(propertiesMap);
    when(param2.getValueClassName()).thenReturn("Integer");
    when(param2.getName()).thenReturn("name");
    when(param2.getDescription()).thenReturn("desc");
    when(param2.getDefaultValueExpression()).thenReturn(jrExpression);

    ByteArrayOutputStream byteOutputStream = mock(ByteArrayOutputStream.class);
    whenNew(ByteArrayOutputStream.class).withAnyArguments().thenReturn(byteOutputStream);
    ObjectOutputStream objectOutputStream = spy(new ObjectOutputStream(byteOutputStream));
    whenNew(ObjectOutputStream.class).withArguments(byteOutputStream).thenReturn(objectOutputStream);
    doNothing().when(objectOutputStream).writeObject(report);
    byte[] byteData = new byte[1];
    when(byteOutputStream.toByteArray()).thenReturn(byteData);
    Template template = new Template();

    templateService.validateFileAndInsertTemplate(template, file);

    verify(templateRepository).save(template);

    assertThat(template.getTemplateParameters().get(0).getDisplayName(), is(PARAM_DISPLAY_NAME));
    assertThat(template.getTemplateParameters().get(0).getDescription(), is("desc"));
    assertThat(template.getTemplateParameters().get(0).getName(), is("name"));
}