Example usage for org.springframework.core.io InputStreamResource InputStreamResource

List of usage examples for org.springframework.core.io InputStreamResource InputStreamResource

Introduction

In this page you can find the example usage for org.springframework.core.io InputStreamResource InputStreamResource.

Prototype

public InputStreamResource(InputStream inputStream) 

Source Link

Document

Create a new InputStreamResource.

Usage

From source file:com.spartasystems.holdmail.rest.MessageController.java

@RequestMapping(value = "/{messageId}/att/{attId}")
public ResponseEntity getMessageContentByAttachmentId(@PathVariable("messageId") long messageId,
        @PathVariable("attId") int attId) {

    Message message = messageService.getMessage(messageId);

    MessageContentPart content = message.getContent().findBySequenceId(attId);

    String disposition = "attachment;";

    if (StringUtils.isNotBlank(content.getAttachmentFilename())) {
        disposition += " filename=\"" + content.getAttachmentFilename() + "\";";
    }//  ww w  . ja v  a  2s .  co  m

    return ResponseEntity.ok().header("Content-Type", content.getContentType())
            .header("Content-Disposition", disposition)
            .body(new InputStreamResource(content.getContentStream()));
}

From source file:com.anuz.dummyapi.controller.ClientController.java

@RequestMapping(value = "/contents_file/{id}", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> downloadFiles(@PathVariable("id") int id) throws IOException {

    List<Content> contentList = contentUpdateService.getUnsynchronizedContentList(id);
    if (!contentList.isEmpty()) {
        String fileName = "zipFile" + new Date().getTime() + ".zip";
        ZipUtil zipFile = new ZipUtil();
        for (Content content : contentList) {
            System.out.println(CONSTANTS.CONTENTS + content.getContentLocation());
            zipFile.generateFileList(new File(CONSTANTS.CONTENTS + content.getContentLocation()));
        }/*from ww w .  j  a v  a 2  s. c  o m*/
        String finalZip = zipFile.zipIt(CONSTANTS.CONTENTS + fileName);
        //            System.out.println(finalZip);
        //            if(finalZip!=null){
        //                contentUpdateService.updateContentStatus(id,Boolean.FALSE);
        //            }

        FileSystemResource file = new FileSystemResource(finalZip);

        //            return ResponseEntity.ok().contentLength(file.contentLength())
        //                    .contentType(MediaType.parseMediaType("application/octet-stream"))
        //                    .header("Content-Disposition", "attachment; filename=" + fileName)
        //                    .body(new InputStreamResource(file.getInputStream()));

        return ResponseEntity.ok().contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/zip"))
                .header("Content-Disposition", "attachment; filename=" + fileName)
                .body(new InputStreamResource(file.getInputStream()));

    }
    return ResponseEntity.ok().body(null);

}

From source file:com.wooki.test.unit.ConversionsTest.java

@Test(enabled = true)
public void testAPTConversion() {
    String result = /*
                     * generator .adaptContent(
                     */"<h2>SubTitle</h2><p>Lorem ipsum</p><h3>SubTitle2</h3><p>Lorem ipsum</p>"/* ) */;

    Resource resource = new ByteArrayResource(result.getBytes());
    InputStream xhtml = toXHTMLConvertor.performTransformation(resource);
    logger.debug("Document to xhtml ok");
    InputStream apt = toAPTConvertor.performTransformation(new InputStreamResource(xhtml));
    logger.debug("xhtml to apt ok");
    File aptFile;//  www  .  ja va  2s  .  c om
    try {
        aptFile = File.createTempFile("wooki", ".apt");
        FileOutputStream fos = new FileOutputStream(aptFile);
        logger.debug("APT File is " + aptFile.getAbsolutePath());
        byte[] content = null;
        int available = 0;
        while ((available = apt.available()) > 0) {
            content = new byte[available];
            apt.read(content);
            fos.write(content);
        }
        fos.flush();
        fos.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.intellij.plugins.beans.PluginContext.java

private void registerPluginContextBeans(XmlBeanDefinitionReader reader, InputStream contextConfig,
        InputStream versionedContextConfig) {
    if (versionedContextConfig == null && contextConfig == null)
        return;//from  w w w .j a v a2  s . c om
    if (versionedContextConfig != null)
        reader.loadBeanDefinitions(new InputStreamResource[] { new InputStreamResource(versionedContextConfig),
                new InputStreamResource(contextConfig) });
    else
        reader.loadBeanDefinitions(new InputStreamResource(contextConfig));
}

From source file:org.opennms.ng.dao.support.PropertiesGraphDao.java

/**
 * <p>/*from  w w  w.j ava 2s.  c  o  m*/
 * loadProperties
 * </p>
 * Used exclusively by test code. Will ignore an "include.directory"
 * because we don't have a resource/path to do any useful "relative"
 * pathing to. Also anything loaded in this fashion will *not* have auto
 * reloading on changes, because there's no underlying Resource/File to
 * check against. Like, duh!
 *
 * @param type
 *            a {@link String} object.
 * @param in
 *            a {@link java.io.InputStream} object.
 * @throws java.io.IOException
 *             if any.
 */
public void loadProperties(String type, InputStream in) throws IOException {
    Resource resource = new InputStreamResource(in);
    // Not reloadable; we don't have a file to check for modifications
    PrefabGraphTypeDao t = createPrefabGraphType(type, resource, false);
    if (t != null) {
        m_types.put(t.getName(), new FileReloadContainer<PrefabGraphTypeDao>(t));
    }
}

From source file:com.github.cherimojava.orchidae.controller.PictureController.java

/**
 * actual method retrieving the picture from disk. Requested picture is only returned if the current user is allowed
 * to view it/*w ww. j a  v  a 2  s.c  o  m*/
 * 
 * @param id
 *            identification of picture
 * @param type
 *            type of the picture eg _t for thumbnail etc.
 * @return ResponseEntity containing the resource to the picture or NOT_FOUND
 * @throws IOException
 */
private ResponseEntity<Resource> _getPicture(String id, String type) throws IOException {
    File picture = fileUtil.getFileHandle(id + type);
    if (picture.exists()) {
        return new ResponseEntity<Resource>(new InputStreamResource(FileUtils.openInputStream(picture)),
                HttpStatus.OK);
    } else {
        LOG.debug("Could not find picture with id {}", id);
        // picture doesn't exist so return 404
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}

From source file:org.eclipse.gemini.blueprint.test.AbstractDependencyManagerTests.java

/**
 * Returns the location of the test framework bundles configuration.
 * /*  w  w  w.  j  ava 2  s .co m*/
 * @return the location of the test framework bundles configuration
 */
protected Resource getTestingFrameworkBundlesConfiguration() {
    return new InputStreamResource(
            AbstractDependencyManagerTests.class.getResourceAsStream(TEST_FRRAMEWORK_BUNDLES_CONF_FILE));
}

From source file:business.services.FileService.java

public HttpEntity<InputStreamResource> download(Long id) {
    try {/*  w w  w.j  av  a  2  s .c o m*/
        File attachment = fileRepository.findOne(id);
        if (attachment == null) {
            throw new FileNotFound();
        }
        FileSystem fileSystem = FileSystems.getDefault();
        Path path = fileSystem.getPath(uploadPath, attachment.getFilename());
        InputStream input = new FileInputStream(path.toFile());
        InputStreamResource resource = new InputStreamResource(input);
        HttpHeaders headers = new HttpHeaders();
        if (attachment.getMimeType() != null) {
            headers.setContentType(MediaType.valueOf(attachment.getMimeType()));
        } else {
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        }
        headers.set("Content-Disposition", "attachment; filename=" + attachment.getName().replace(" ", "_"));
        HttpEntity<InputStreamResource> response = new HttpEntity<InputStreamResource>(resource, headers);
        return response;
    } catch (IOException e) {
        log.error(e);
        throw new FileDownloadError();
    }
}

From source file:de.unimannheim.spa.process.rest.ProjectRestController.java

@RequestMapping(value = "/{projectID}/processes/{processID}", method = RequestMethod.GET, produces = "application/octet-stream")
public ResponseEntity<InputStreamResource> downloadProcessFile(@PathVariable("projectID") String projectID,
        @PathVariable("processID") String processID) throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");

    final Optional<DataPool> dataPool = spaService.findProjectById(PROJECT_BASE_URL + projectID)
            .map(project -> project.getDataPools().get(0));
    final Optional<DataBucket> dataBucketToDownload = (dataPool.isPresent())
            ? dataPool.get().findDataBucketById(PROCESS_BASE_URL + processID)
            : Optional.empty();//ww w . ja  v a2  s.com
    final File processFile = Files.createTempFile(dataBucketToDownload.get().getLabel(), "").toFile();

    spaService.exportData(dataBucketToDownload.get(), "BPMN2", processFile);

    headers.add("Content-Disposition", "attachment; filename=" + processFile.getName() + ".bpmn");
    headers.add("Access-Control-Expose-Headers", "Content-Disposition");

    return ResponseEntity.ok().headers(headers).contentLength(processFile.length())
            .contentType(OCTET_CONTENT_TYPE).body(new InputStreamResource(new FileInputStream(processFile)));
}

From source file:org.ow2.proactive.workflow_catalog.rest.service.WorkflowRevisionService.java

public ResponseEntity<?> getWorkflow(Long bucketId, Long workflowId, Optional<Long> revisionId,
        Optional<String> alt) {
    findBucket(bucketId);//from  ww w.jav a  2 s  . c  om
    findWorkflow(workflowId);

    WorkflowRevision workflowRevision = getWorkflowRevision(bucketId, workflowId, revisionId);

    if (alt.isPresent()) {
        String altValue = alt.get();

        if (!altValue.equalsIgnoreCase(SUPPORTED_ALT_VALUE)) {
            throw new UnsupportedMediaTypeException("Unsupported media type '" + altValue + "' (only '"
                    + SUPPORTED_ALT_VALUE + "' is allowed)");
        }

        byte[] bytes = workflowRevision.getXmlPayload();

        return ResponseEntity.ok().contentLength(bytes.length).contentType(MediaType.APPLICATION_XML)
                .body(new InputStreamResource(new ByteArrayInputStream(bytes)));
    }

    WorkflowMetadata workflowMetadata = new WorkflowMetadata(workflowRevision);

    workflowMetadata.add(createLink(bucketId, workflowId, workflowRevision));

    return ResponseEntity.ok(workflowMetadata);
}