Java 类org.springframework.core.io.InputStreamResource 实例源码

项目:Learning-Spring-Boot-2.0-Second-Edition    文件:HomeController.java   
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
    produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
    @PathVariable String filename) {
    // tag::try-catch[]
    return imageService.findOneImage(filename)
        .map(resource -> {
            try {
                return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .body(new InputStreamResource(
                        resource.getInputStream()));
            } catch (IOException e) {
                return ResponseEntity.badRequest()
                    .body("Couldn't find " + filename +
                        " => " + e.getMessage());
            }
        });
    // end::try-catch[]
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:HomeController.java   
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
    produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
    @PathVariable String filename) {
    // tag::try-catch[]
    return imageService.findOneImage(filename)
        .map(resource -> {
            try {
                return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .body(new InputStreamResource(
                        resource.getInputStream()));
            } catch (IOException e) {
                return ResponseEntity.badRequest()
                    .body("Couldn't find " + filename +
                        " => " + e.getMessage());
            }
        });
    // end::try-catch[]
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:HomeController.java   
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
    produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
    @PathVariable String filename) {
    // tag::try-catch[]
    return imageService.findOneImage(filename)
        .map(resource -> {
            try {
                return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .body(new InputStreamResource(
                        resource.getInputStream()));
            } catch (IOException e) {
                return ResponseEntity.badRequest()
                    .body("Couldn't find " + filename +
                        " => " + e.getMessage());
            }
        });
    // end::try-catch[]
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:HomeController.java   
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
    produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
    @PathVariable String filename) {
    // tag::try-catch[]
    return imageService.findOneImage(filename)
        .map(resource -> {
            try {
                return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .body(new InputStreamResource(
                        resource.getInputStream()));
            } catch (IOException e) {
                return ResponseEntity.badRequest()
                    .body("Couldn't find " + filename +
                        " => " + e.getMessage());
            }
        });
    // end::try-catch[]
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:HomeController.java   
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
    produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
    @PathVariable String filename) {
    // tag::try-catch[]
    return imageService.findOneImage(filename)
        .map(resource -> {
            try {
                return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .body(new InputStreamResource(
                        resource.getInputStream()));
            } catch (IOException e) {
                return ResponseEntity.badRequest()
                    .body("Couldn't find " + filename +
                        " => " + e.getMessage());
            }
        });
    // end::try-catch[]
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:UploadController.java   
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
    produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
    @PathVariable String filename) {
    // tag::try-catch[]
    return imageService.findOneImage(filename)
        .map(resource -> {
            try {
                return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .body(new InputStreamResource(
                        resource.getInputStream()));
            } catch (IOException e) {
                return ResponseEntity.badRequest()
                    .body("Couldn't find " + filename +
                        " => " + e.getMessage());
            }
        });
    // end::try-catch[]
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:UploadController.java   
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
    produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
    @PathVariable String filename) {
    // tag::try-catch[]
    return imageService.findOneImage(filename)
        .map(resource -> {
            try {
                return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .body(new InputStreamResource(
                        resource.getInputStream()));
            } catch (IOException e) {
                return ResponseEntity.badRequest()
                    .body("Couldn't find " + filename +
                        " => " + e.getMessage());
            }
        });
    // end::try-catch[]
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:UploadController.java   
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
    produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
    @PathVariable String filename) {
    // tag::try-catch[]
    return imageService.findOneImage(filename)
        .map(resource -> {
            try {
                return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .body(new InputStreamResource(
                        resource.getInputStream()));
            } catch (IOException e) {
                return ResponseEntity.badRequest()
                    .body("Couldn't find " + filename +
                        " => " + e.getMessage());
            }
        });
    // end::try-catch[]
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:UploadController.java   
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
    produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
    @PathVariable String filename) {
    // tag::try-catch[]
    return imageService.findOneImage(filename)
        .map(resource -> {
            try {
                return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .body(new InputStreamResource(
                        resource.getInputStream()));
            } catch (IOException e) {
                return ResponseEntity.badRequest()
                    .body("Couldn't find " + filename +
                        " => " + e.getMessage());
            }
        });
    // end::try-catch[]
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:HomeController.java   
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
    produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
    @PathVariable String filename) {
    // tag::try-catch[]
    return imageService.findOneImage(filename)
        .map(resource -> {
            try {
                return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .body(new InputStreamResource(
                        resource.getInputStream()));
            } catch (IOException e) {
                return ResponseEntity.badRequest()
                    .body("Couldn't find " + filename +
                        " => " + e.getMessage());
            }
        });
    // end::try-catch[]
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:HomeController.java   
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
    produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
    @PathVariable String filename) {
    // tag::try-catch[]
    return imageService.findOneImage(filename)
        .map(resource -> {
            try {
                return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .body(new InputStreamResource(
                        resource.getInputStream()));
            } catch (IOException e) {
                return ResponseEntity.badRequest()
                    .body("Couldn't find " + filename +
                        " => " + e.getMessage());
            }
        });
    // end::try-catch[]
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:UploadController.java   
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
    produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
    @PathVariable String filename) {
    // tag::try-catch[]
    return imageService.findOneImage(filename)
        .map(resource -> {
            try {
                return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .body(new InputStreamResource(
                        resource.getInputStream()));
            } catch (IOException e) {
                return ResponseEntity.badRequest()
                    .body("Couldn't find " + filename +
                        " => " + e.getMessage());
            }
        });
    // end::try-catch[]
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:HomeController.java   
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
    produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
    @PathVariable String filename) {
    return imageService.findOneImage(filename)
        .map(resource -> {
            try {
                return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .body(new InputStreamResource(
                        resource.getInputStream()));
            } catch (IOException e) {
                return ResponseEntity.badRequest()
                    .body("Couldn't find " + filename +
                        " => " + e.getMessage());
            }
        });
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:HomeController.java   
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
    produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
    @PathVariable String filename) {
    return imageService.findOneImage(filename)
        .map(resource -> {
            try {
                return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .body(new InputStreamResource(
                        resource.getInputStream()));
            } catch (IOException e) {
                return ResponseEntity.badRequest()
                    .body("Couldn't find " + filename +
                        " => " + e.getMessage());
            }
        });
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:HomeController.java   
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
    produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
                            @PathVariable String filename) {
    return imageService.findOneImage(filename)
        .map(resource -> {
            try {
                return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .body(new InputStreamResource(
                        resource.getInputStream()));
            } catch (IOException e) {
                return ResponseEntity.badRequest()
                    .body("Couldn't find " + filename +
                        " => " + e.getMessage());
            }
        });
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:HomeController.java   
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
    produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
                            @PathVariable String filename) {
    return imageService.findOneImage(filename)
        .map(resource -> {
            try {
                return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .body(new InputStreamResource(
                        resource.getInputStream()));
            } catch (IOException e) {
                return ResponseEntity.badRequest()
                    .body("Couldn't find " + filename +
                        " => " + e.getMessage());
            }
        });
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:UploadController.java   
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
    produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
    @PathVariable String filename) {
    // tag::try-catch[]
    return imageService.findOneImage(filename)
        .map(resource -> {
            try {
                return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .body(new InputStreamResource(
                        resource.getInputStream()));
            } catch (IOException e) {
                return ResponseEntity.badRequest()
                    .body("Couldn't find " + filename +
                        " => " + e.getMessage());
            }
        });
    // end::try-catch[]
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:UploadController.java   
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
    produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
    @PathVariable String filename) {
    // tag::try-catch[]
    return imageService.findOneImage(filename)
        .map(resource -> {
            try {
                return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .body(new InputStreamResource(
                        resource.getInputStream()));
            } catch (IOException e) {
                return ResponseEntity.badRequest()
                    .body("Couldn't find " + filename +
                        " => " + e.getMessage());
            }
        });
    // end::try-catch[]
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:UploadController.java   
@GetMapping(value = BASE_PATH + "/" + FILENAME + "/raw",
    produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public Mono<ResponseEntity<?>> oneRawImage(
    @PathVariable String filename) {
    // tag::try-catch[]
    return imageService.findOneImage(filename)
        .map(resource -> {
            try {
                return ResponseEntity.ok()
                    .contentLength(resource.contentLength())
                    .body(new InputStreamResource(
                        resource.getInputStream()));
            } catch (IOException e) {
                return ResponseEntity.badRequest()
                    .body("Couldn't find " + filename +
                        " => " + e.getMessage());
            }
        });
    // end::try-catch[]
}
项目:qpp-conversion-tool    文件:CpcFileControllerV1.java   
/**
 * Retrieve a stored S3 object.
 *
 * @param fileId id for the stored object
 * @return object json or xml content
 * @throws IOException if S3Object content stream is invalid
 */
@GetMapping(value = "/file/{fileId}",
        headers = {"Accept=" + Constants.V1_API_ACCEPT})
public ResponseEntity<InputStreamResource> getFileById(@PathVariable("fileId") String fileId)
        throws IOException {
    API_LOG.info("CPC+ file retrieval request received");

    if (blockCpcPlusApi()) {
        API_LOG.info("CPC+ file request blocked by feature flag");
        return new ResponseEntity<>(null, null, HttpStatus.FORBIDDEN);
    }

    InputStreamResource content = cpcFileService.getFileById(fileId);

    API_LOG.info("CPC+ file retrieval request succeeded");

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_XML);

    return new ResponseEntity<>(content, httpHeaders, HttpStatus.OK);
}
项目:cas-5.1.0    文件:X509CertificateCredentialJsonDeserializer.java   
@Override
public X509CertificateCredential deserialize(final JsonParser jp, 
                                             final DeserializationContext deserializationContext) 
        throws IOException {
    final ObjectCodec oc = jp.getCodec();
    final JsonNode node = oc.readTree(jp);

    final List<X509Certificate> certs = new ArrayList<>();
    node.findValues("certificates").forEach(n -> {
        final String cert = n.get(0).textValue();
        final byte[] data = EncodingUtils.decodeBase64(cert);
        certs.add(CertUtils.readCertificate(new InputStreamResource(new ByteArrayInputStream(data))));
    });
    final X509CertificateCredential c = new X509CertificateCredential(certs.toArray(new X509Certificate[] {}));
    return c;
}
项目:document-management-store-app    文件:DocumentContentVersionController.java   
@GetMapping(value = "/versions/{versionId}/binary")
@ApiOperation("Streams a specific version of the content of a Stored Document.")
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "Returns contents of a document version")
})
public ResponseEntity<InputStreamResource> getDocumentContentVersionDocumentBinary(
    @PathVariable UUID documentId,
    @PathVariable UUID versionId) {

    DocumentContentVersion documentContentVersion = documentContentVersionService.findOne(versionId);

    if (documentContentVersion == null || documentContentVersion.getStoredDocument().isDeleted()) {
        throw new DocumentContentVersionNotFoundException(String.format("ID: %s", versionId.toString()));
    } else {
        auditedDocumentContentVersionOperationsService.readDocumentContentVersionBinary(documentContentVersion);
    }

    return null;

}
项目:ARCLib    文件:FileApi.java   
/**
 * Gets the content of a file with specified id.
 *
 * <p>
 *     Also sets Content-Length and Content-Disposition http headers to values previously saved during upload.
 * </p>
 * @param id Id of file to retrieve
 * @throws MissingObject if the file was not found
 * @return Content of a file in input stream
 */
@ApiOperation(value = "Gets the content of a file with specified id.",
        notes = "Returns content of a file in input stream.",
        response = ResponseEntity.class)
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successful response", response = ResponseEntity.class),
        @ApiResponse(code = 404, message = "The file was not found")})
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> download(@ApiParam(value = "Id of file to retrieve", required = true)
                                                        @PathVariable("id") String id) {

    FileRef file = repository.get(id);
    notNull(file, () -> new MissingObject(FileRef.class, id));

    return ResponseEntity
            .ok()
            .header("Content-Disposition", "attachment; filename=" + file.getName())
            .header("Content-Length", String.valueOf(file.getSize()))
            .contentType(MediaType.parseMediaType(file.getContentType()))
            .body(new InputStreamResource(file.getStream()));
}
项目:xm-ms-entity    文件:XmHttpEntityUtils.java   
public static HttpEntity<Resource> buildAvatarHttpEntity(MultipartFile multipartFile) throws IOException {
    // result headers
    HttpHeaders headers = new HttpHeaders();

    // 'Content-Type' header
    String contentType = multipartFile.getContentType();
    if (StringUtils.isNotBlank(contentType)) {
        headers.setContentType(MediaType.valueOf(contentType));
    }

    // 'Content-Length' header
    long contentLength = multipartFile.getSize();
    if (contentLength >= 0) {
        headers.setContentLength(contentLength);
    }

    // File name header
    String fileName = multipartFile.getOriginalFilename();
    headers.set(XM_HEADER_CONTENT_NAME, fileName);

    Resource resource = new InputStreamResource(multipartFile.getInputStream());
    return new HttpEntity<>(resource, headers);
}
项目:dotwebstack-framework    文件:RdfModelTransformer.java   
public static Model mergeResourceWithPrefixes(InputStream inputStreamPrefixes,
    InputStream inputStreamData) throws IOException {
  final Resource mergedDataResource =
      new InputStreamResource(new SequenceInputStream(inputStreamPrefixes, inputStreamData));
  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

  RDFWriter turtleWriter = Rio.createWriter(RDFFormat.TURTLE, byteArrayOutputStream);
  RDFParser trigParser = Rio.createParser(RDFFormat.TRIG);
  trigParser.setRDFHandler(turtleWriter);
  trigParser.parse(mergedDataResource.getInputStream(), "");

  Model result = Rio.parse(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()), "",
      RDFFormat.TURTLE);

  byteArrayOutputStream.close();
  inputStreamData.close();
  return result;
}
项目:dotwebstack-framework    文件:ShaclValidatorTest.java   
@Before
public void setUp() throws Exception {
  shaclValidator = new ShaclValidator();
  shapesResource = new InputStreamResource(
      new ClassPathResource("/shaclvalidation/shapes.trig").getInputStream());
  validDataResource = new InputStreamResource(
      new ClassPathResource("/shaclvalidation/validData.trig").getInputStream());
  invalidDataResource = new InputStreamResource(
      new ClassPathResource("/shaclvalidation/invalidData.trig").getInputStream());
  invalidDataWithoutPrefResource = new InputStreamResource(
      new ClassPathResource("/shaclvalidation/invalidDataWithoutPref.trig").getInputStream());
  validDataWithoutPrefResource = new InputStreamResource(
      new ClassPathResource("/shaclvalidation/validDataWithoutPref.trig").getInputStream());
  prefixesResource = new InputStreamResource(
      new ClassPathResource("/shaclvalidation/_prefixes.trig").getInputStream());
  invalidDataMultipleErrorsResource = new InputStreamResource(
      new ClassPathResource("/shaclvalidation/invalidDataMultipleErrors.trig").getInputStream());
}
项目:NMapGUI    文件:WebController.java   
@GetMapping("/nmap/download/{filename}")
  public ResponseEntity<InputStreamResource> download(@PathVariable("filename") String filename) {

    InputStream file;
try {
    file = new Filefinder().find(filename);
    InputStreamResource resource = new InputStreamResource(file);

       return ResponseEntity.ok()
               .contentType(MediaType.parseMediaType("application/octect-stream"))
               .body(resource);
} catch (FileNotFoundException e) {
    return ResponseEntity.notFound().build();
}       

  }
项目:JuniperBotJ    文件:BlurImageController.java   
@RequestMapping(value = "/blur", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<InputStreamResource> blur(@RequestParam("source") String sourceUrl, HttpServletResponse response) {
    if (!StringUtils.startsWithAny(sourceUrl, ALLOWED_PREFIX)) {
        return ResponseEntity.badRequest().build();
    }

    String hash = DigestUtils.sha1Hex(sourceUrl);

    try {
        ImageInfo info = readCached(hash);
        if (info == null) {
            info = renderImage(sourceUrl);
            if (info != null) {
                saveCached(hash, info);
            }
        }
        if (info != null) {
            return ResponseEntity.ok()
                    .contentLength(info.contentLength)
                    .contentType(MediaType.IMAGE_JPEG)
                    .body(new InputStreamResource(info.inputStream));
        }
    } catch (IOException e) {
        // fall down
    }
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
项目:FastBootWeixin    文件:WxMediaResourceMessageConverter.java   
@Override
    protected Resource readInternal(Class<? extends Resource> clazz, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException {

        WxMediaResource wxMediaResource = new WxMediaResource(inputMessage);
        if (wxMediaResource.isUrlMedia() && !clazz.isAssignableFrom(WxMediaResource.class)) {
            throw new WxApiException("不支持的返回类型,接口返回了url");
        }
        if (InputStreamResource.class == clazz) {
            return new InputStreamResource(wxMediaResource.getInputStream());
        } else if (clazz.isAssignableFrom(WxMediaResource.class)) {
            return wxMediaResource;
        } else if (clazz.isAssignableFrom(ByteArrayResource.class)) {
            return new ByteArrayResource(wxMediaResource.getBody());
        } else if (clazz.isAssignableFrom(FileSystemResource.class)) {
            return new FileSystemResource(wxMediaResource.getFile());
        }
//      else if (clazz.isAssignableFrom(File.class)) {
//          return wxMediaResource.getFile();
//      }
        throw new WxApiException("不支持的返回类型");
    }
项目:holdmail    文件: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() + "\";";
    }

    return ResponseEntity.ok()
                         .header("Content-Type", content.getContentType())
                         .header("Content-Disposition", disposition)
                         .body(new InputStreamResource(content.getContentStream()));
}
项目:holdmail    文件:MessageControllerTest.java   
@Test
public void shouldGetMessageContentByPartId() throws Exception{

    final int MSG_ID = 983;
    final String PART_ID = "derpPart";
    final String CONTENT_TYPE = "some/type";
    final InputStream CONTENT_STREAM = mock(InputStream.class);

    MessageContentPart contentPartMock = mock(MessageContentPart.class);
    when(contentPartMock.getContentType()).thenReturn(CONTENT_TYPE);
    when(contentPartMock.getContentStream()).thenReturn(CONTENT_STREAM);

    Message messageMock = mock(Message.class);
    when(messageServiceMock.getMessage(MSG_ID)).thenReturn(messageMock);

    MessageContent contentMock = mock(MessageContent.class);
    when(messageMock.getContent()).thenReturn(contentMock);
    when(contentMock.findByContentId(PART_ID)).thenReturn(contentPartMock);

    ResponseEntity response = messageControllerSpy.getMessageContentByPartId(MSG_ID, PART_ID);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(response.getHeaders().get("Content-Type")).hasSize(1).contains(CONTENT_TYPE);
    assertThat(response.getBody()).isEqualTo(new InputStreamResource(CONTENT_STREAM));

}
项目:WebIDE-Backend    文件:WorkspaceController.java   
@RequestMapping(value = "/workspaces/{spaceKey}/raw", method = GET)
public ResponseEntity<InputStreamResource> raw(@PathVariable("spaceKey") Workspace ws,
                                               @RequestParam String path,
                                               @RequestParam(defaultValue = "true") Boolean inline) throws Exception {


    FileInfo fileInfo = wsMgr.getFileInfo(ws, path);

    HttpHeaders headers = new HttpHeaders();

    headers.setContentType(MediaType.valueOf(fileInfo.getContentType()));
    headers.setContentLength(fileInfo.getSize());

    if (inline) {
        headers.add(CONTENT_DISPOSITION, format("inline; filename='%s'", encodeFileName(fileInfo.getName())));
    } else {
        headers.add(CONTENT_DISPOSITION, format("attachment; filename='%s'", encodeFileName(fileInfo.getName())));
    }

    InputStreamResource inputStreamResource = new InputStreamResource(ws.getInputStream(path));

    return ResponseEntity.ok()
            .headers(headers)
            .body(inputStreamResource);
}
项目:todolist    文件:BackupController.java   
@RequestMapping("file")
@ResponseBody
public ResponseEntity<InputStreamResource> file(@RequestParam("q") String q, @RequestParam(value="op", required=false) String op) throws IOException {
    Optional<BackupEntry> entry = backupService.findByName(q);
    if(entry.isPresent()) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentLength(entry.get().getFileSize());
        if("download".equals(op)) {
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.add("Content-Disposition", "attachment; filename=" + entry.get().getFileName());
        } else {
            headers.setContentType(MediaType.TEXT_PLAIN);
        }

        return ResponseEntity.ok()
            .headers(headers)
            .body(new InputStreamResource(Files.newInputStream(entry.get().getPath())));
    }

    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
项目:cms    文件:ResourceController.java   
@RequestMapping(value = "/v" + Constants.REST_API_1_0 + "/" + Constants.GET_DATA + "/{context}/**", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> getDataResponse(@PathVariable String context, HttpServletRequest req, HttpServletResponse response) throws Exception {
    LOG.trace(Constants.GET_DATA + " uri={}", context);

    //Extract UURI
    String resourceUri = req.getRequestURI().substring(req.getRequestURI().indexOf(context));
    //Decode URI
    resourceUri = URLDecoder.decode(resourceUri, "UTF-8");
    //Extract TenantID
    final String tenantID = context.substring(context.lastIndexOf('-') + 1);

    // Populate UID
    final String uuid = hashedDirectoryService.hashText(resourceUri);

    ResponseEntity<InputStreamResource> responseEntity = resourceService.getResponseInputStream(uuid);
    if (responseEntity == null) {
        responseEntity = resourceService.getResponseInputStream(uuid + "-" + tenantID);
    }
    if (responseEntity == null) {
        LOG.error("resource {} was requested but does not exist", context);
        throw new ResourceAccessError("Resource " + context + " was requested but does not exist");
    }

    LOG.trace(responseEntity.toString());
    return responseEntity;
}
项目:flowable-engine    文件:ProcessEngineMvcEndpoint.java   
/**
 * Look up the process definition by key. For example, this is <A href="http://localhost:8080/activiti/processes/fulfillmentProcess">process-diagram for</A> a process definition named
 * {@code fulfillmentProcess}.
 */
@RequestMapping(value = "/processes/{processDefinitionKey:.*}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public ResponseEntity processDefinitionDiagram(@PathVariable String processDefinitionKey) {
    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
            .processDefinitionKey(processDefinitionKey)
            .latestVersion()
            .singleResult();
    if (processDefinition == null) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
    }

    ProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
    BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());

    if (bpmnModel.getLocationMap().size() == 0) {
        BpmnAutoLayout autoLayout = new BpmnAutoLayout(bpmnModel);
        autoLayout.execute();
    }

    InputStream is = processDiagramGenerator.generateJpgDiagram(bpmnModel);
    return ResponseEntity.ok(new InputStreamResource(is));
}
项目:dhis2-core    文件:DefaultDhisConfigurationProvider.java   
private Properties loadDhisConf()
    throws IllegalStateException
{
    try ( InputStream in = locationManager.getInputStream( CONF_FILENAME ) )
    {
        Properties conf = PropertiesLoaderUtils.loadProperties( new InputStreamResource( in ) );
        substituteEnvironmentVariables( conf );

        return conf;
    }
    catch ( LocationManagerException | IOException | SecurityException ex )
    {
        log.debug( String.format( "Could not load %s", CONF_FILENAME ), ex );

        throw new IllegalStateException( "Properties could not be loaded", ex );
    }
}
项目:citizenship-appointment-server    文件:PassController.java   
/**
 * Reference: https://developer.apple.com/library/ios/documentation/PassKit/Reference/PassKit_WebService/WebService.html#//apple_ref/doc/uid/TP40011988-CH0-SW6
 */
@RequestMapping(value = "/wallet/v1/passes/${wallet.pass.type.identifier}/citizenship", method = RequestMethod.GET, produces = "application/vnd.apple.pkpass")
public ResponseEntity<Resource> createPass(@AuthenticationPrincipal Client client,
                                           HttpServletRequest request) throws IOException, URISyntaxException {
    LOG.info("Creating pass for clientId=[{}]", client.getClientId());
    AppointmentDetails appointment = appointmentDetailsService.getExpectedAppointmentForClientForNextYear(client);
    if (!isValid(appointment)) {
        return new ResponseEntity<>(new ByteArrayResource(new byte[0]), HttpStatus.BAD_REQUEST);
    }
    URL walletWebServiceUrl = getWalletWebServiceUrl(request);
    Pass pass = passBuilder.createAppointmentPassForClient(client, appointment, walletWebServiceUrl);
    byte[] passAsBytes = pass.getBytes();
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentLength(passAsBytes.length);
    responseHeaders.setContentType(new MediaType("application", "vnd.apple.pkpass"));
    responseHeaders.setContentDispositionFormData("attachment", "appointment.pkpass");
    return new ResponseEntity<>(new InputStreamResource(new ByteArrayInputStream(passAsBytes)), responseHeaders, HttpStatus.OK);
}
项目:opencucina    文件:DefaultProcessEnvironmentTest.java   
/**
 * JAVADOC Method Level Comments
 *
 * @throws Exception JAVADOC.
 */
@Test
public void testInit()
    throws Exception {
    DefaultProcessEnvironment environment = new DefaultProcessEnvironment();
    final Resource defres = new ClassPathResource(RULES_DEFINITION_URL);
    ApplicationContext appc = mock(ApplicationContext.class);

    when(appc.getResource(any(String.class))).thenReturn(defres);

    environment.setApplicationContext(appc);

    List<Resource> resources = new ArrayList<Resource>();
    Resource resource = new InputStreamResource(new ByteArrayInputStream(TEST_WF.getBytes()));

    resources.add(resource);
    environment.setDefinitionResources(resources);
    environment.setTokenFactory(mock(TokenFactory.class));
    environment.setDefinitionRegistry(mock(ProcessDefinitionRegistry.class));
    environment.start();
    assertNotNull("Parser is null", environment.getDefinitionParser());
    assertNotNull("DefinitionRegistry is null", environment.getDefinitionRegistry());
    assertNotNull("ResolverRegistry is null", environment.getBeanResolver());
    assertNotNull("Service is null", environment.getService());
}
项目:opencucina    文件:DigesterModuleProcessDefinitionParserTest.java   
/**
 * JAVADOC
 */
@Test
public void testReadJoinsDefinitions() {
    ProcessDefinition wfd = parser.parse(new InputStreamResource(
                new ByteArrayInputStream(ANOTHER_WF.getBytes())));

    assertNotNull(wfd);
    assertEquals("another-workflow", wfd.getId());

    State state = wfd.getStartState();

    assertNotNull(state);
    assertEquals(state.getId(), "Start");

    Transition tr = state.getTransition("toEdit");

    assertNotNull(tr);
    assertEquals(state, tr.getInput());
    state = tr.getOutput();
    assertNotNull(state);
}
项目:opencucina    文件:DigesterRulesModuleTest.java   
/**
 * JAVADOC Method Level Comments
 *
 * @throws Exception JAVADOC.
 */
@Test
public void testLoadRules()
    throws Exception {
    Resource rulesResource = new InputStreamResource(new ByteArrayInputStream(
                SIMPLE_RULES.getBytes()));
    DigesterRulesModule module = new DigesterRulesModule(rulesResource);
    DigesterLoader loader = DigesterLoader.newLoader(module);
    Digester digester = loader.newDigester();

    digester.push(new Container());

    Container cont = digester.parse(new StringReader(SIMPLE_DATA));

    assertNotNull("Container is null", cont);
    assertNotNull("startState is null", cont.getStartState());
}