org.springframework.boot.context.properties.source.MapConfigurationPropertySource#org.springframework.core.io.InputStreamResource源码实例Demo

下面列出了org.springframework.boot.context.properties.source.MapConfigurationPropertySource#org.springframework.core.io.InputStreamResource 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Test //SPR-16754
public void disableRangeSupportForStreamingResponses() throws Exception {
	InputStream is = new ByteArrayInputStream("Content".getBytes(StandardCharsets.UTF_8));
	InputStreamResource resource = new InputStreamResource(is, "test");
	ResponseEntity<Resource> returnValue = ResponseEntity.ok(resource);
	servletRequest.addHeader("Range", "bytes=0-5");

	given(resourceMessageConverter.canWrite(any(), eq(null))).willReturn(true);
	given(resourceMessageConverter.canWrite(any(), eq(APPLICATION_OCTET_STREAM))).willReturn(true);

	processor.handleReturnValue(returnValue, returnTypeResponseEntityResource, mavContainer, webRequest);
	then(resourceMessageConverter).should(times(1)).write(
			any(InputStreamResource.class), eq(APPLICATION_OCTET_STREAM), any(HttpOutputMessage.class));
	assertEquals(200, servletResponse.getStatus());
	assertThat(servletResponse.getHeader(HttpHeaders.ACCEPT_RANGES), Matchers.isEmptyOrNullString());
}
 
@Override
protected Resource readInternal(Class<? extends Resource> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	if (this.supportsReadStreaming && InputStreamResource.class == clazz) {
		return new InputStreamResource(inputMessage.getBody()) {
			@Override
			public String getFilename() {
				return inputMessage.getHeaders().getContentDisposition().getFilename();
			}
		};
	}
	else if (Resource.class == clazz || ByteArrayResource.class.isAssignableFrom(clazz)) {
		byte[] body = StreamUtils.copyToByteArray(inputMessage.getBody());
		return new ByteArrayResource(body) {
			@Override
			@Nullable
			public String getFilename() {
				return inputMessage.getHeaders().getContentDisposition().getFilename();
			}
		};
	}
	else {
		throw new HttpMessageNotReadableException("Unsupported resource class: " + clazz, inputMessage);
	}
}
 
@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[]
}
 
源代码4 项目: lams   文件: HttpRange.java
/**
 * Turn a {@code Resource} into a {@link ResourceRegion} using the range
 * information contained in the current {@code HttpRange}.
 * @param resource the {@code Resource} to select the region from
 * @return the selected region of the given {@code Resource}
 * @since 4.3
 */
public ResourceRegion toResourceRegion(Resource resource) {
	// Don't try to determine contentLength on InputStreamResource - cannot be read afterwards...
	// Note: custom InputStreamResource subclasses could provide a pre-calculated content length!
	Assert.isTrue(resource.getClass() != InputStreamResource.class,
			"Cannot convert an InputStreamResource to a ResourceRegion");
	try {
		long contentLength = resource.contentLength();
		Assert.isTrue(contentLength > 0, "Resource content length should be > 0");
		long start = getRangeStart(contentLength);
		long end = getRangeEnd(contentLength);
		return new ResourceRegion(resource, start, end - start + 1);
	}
	catch (IOException ex) {
		throw new IllegalArgumentException("Failed to convert Resource to ResourceRegion", ex);
	}
}
 
@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[]
}
 
@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[]
}
 
@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[]
}
 
@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[]
}
 
源代码9 项目: nbp   文件: IndexController.java
/**
 * get the ngc zip file
 * @param fileName
 * @return
 * @throws IOException
 */
@RequestMapping(value="/download/{fileName}", method= RequestMethod.GET)
public ResponseEntity<InputStreamResource> downloadFile (@PathVariable("fileName") String fileName)
        throws IOException {
    logger.info(String.format("-----------------Begin download the zip file %s-----------------", fileName));
    if (!vCenterService.isValidZipFileName(fileName)) {
        return ResponseEntity.notFound().build();
    }
    MediaType mediaType = MediaTypeUtils.getMediaTypeForFileName(this.servletContext, fileName);
    File file = new File(vCenterService.getZipfilePath());
    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

    return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName())
            // Content-Type
            .contentType(mediaType)
            // Content-Length
            .contentLength(file.length())
            .body(resource);
}
 
@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[]
}
 
@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[]
}
 
@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());
			}
		});
}
 
@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());
			}
		});
}
 
@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());
			}
		});
}
 
@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());
			}
		});
}
 
@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[]
}
 
@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[]
}
 
@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[]
}
 
源代码19 项目: zhcet-web   文件: UploadedImageController.java
@ResponseBody
@GetMapping("/image:view/{image:.+}")
public ResponseEntity<InputStreamResource> serveImage(@PathVariable UploadedImage image) {
    if (image == null) {
        log.warn("Trying to view non existent image");
        return ResponseEntity.notFound().build();
    }

    File file = systemStorageService.load(FileType.IMAGE, image.getFilename()).toFile();
    if (!file.exists()) {
        log.warn("Trying to view non existent image {}", image);
        return ResponseEntity.notFound().build();
    }

    try {
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(image.getContentType()))
                .contentLength(file.length())
                .body(new InputStreamResource(new FileInputStream(file)));
    } catch (FileNotFoundException e) {
        return ResponseEntity.noContent().build();
    }
}
 
InitializrProperties toProperties(String url) {
	return CACHE.computeIfAbsent(url, s -> {
		String retrievedFile = this.rawGithubRetriever.raw(s);
		if (StringUtils.isEmpty(retrievedFile)) {
			return null;
		}
		YamlPropertiesFactoryBean yamlProcessor = new YamlPropertiesFactoryBean();
		yamlProcessor.setResources(new InputStreamResource(new ByteArrayInputStream(
				retrievedFile.getBytes(StandardCharsets.UTF_8))));
		Properties properties = yamlProcessor.getObject();
		return new Binder(
				new MapConfigurationPropertySource(properties.entrySet().stream()
						.collect(Collectors.toMap(e -> e.getKey().toString(),
								e -> e.getValue().toString()))))
										.bind("initializr",
												InitializrProperties.class)
										.get();
	});
}
 
源代码21 项目: XS2A-Sandbox   文件: TppDataUploaderController.java
@Override
public ResponseEntity<Resource> generateData(boolean generatePayments, String currency) {
    log.info("Request to create test data received");

    byte[] bytes = generationService.generate(generatePayments, Currency.getInstance(currency));

    InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(bytes));
    HttpHeaders headers = getExportFileHttpHeaders();
    return ResponseEntity.ok()
               .headers(headers)
               .contentLength(bytes.length)
               .contentType(MediaType.APPLICATION_OCTET_STREAM)
               .body(resource);
}
 
源代码22 项目: beihu-boot   文件: FileApi.java
@GetMapping("{bucketName}/**")
public ResponseEntity<Resource> downloadFile(@PathVariable("bucketName") String bucketName,
                                             HttpServletRequest request)
        throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException,
        InvalidArgumentException, InternalException, NoResponseException, InvalidBucketNameException,
        XmlPullParserException, ErrorResponseException {

    String path = String.valueOf(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
    String objectName = path.substring(path.indexOf(bucketName) + bucketName.length() + 1);

    InputStream objectStream = minioTemplate.getObject(bucketName, objectName);
    String fileName = objectName.substring(objectName.lastIndexOf('/') + 1);

    return ResponseEntity.ok()
            .contentType(MediaType.IMAGE_JPEG)
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName)
            .body(new InputStreamResource(objectStream));
}
 
/**
 * Determine, if possible, the contentLength of the given resource without reading it.
 * @param resource the resource instance
 * @return the contentLength of the resource
 */
private OptionalLong contentLength(Resource resource) {
	// Don't try to determine contentLength on InputStreamResource - cannot be read afterwards...
	// Note: custom InputStreamResource subclasses could provide a pre-calculated content length!
	if (InputStreamResource.class != resource.getClass()) {
		try {
			return OptionalLong.of(resource.contentLength());
		}
		catch (IOException ignored) {
		}
	}
	return OptionalLong.empty();
}
 
源代码24 项目: spring-analysis-note   文件: ResourceDecoder.java
@Override
public Resource decode(DataBuffer dataBuffer, ResolvableType elementType,
		@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {

	byte[] bytes = new byte[dataBuffer.readableByteCount()];
	dataBuffer.read(bytes);
	DataBufferUtils.release(dataBuffer);

	if (logger.isDebugEnabled()) {
		logger.debug(Hints.getLogPrefix(hints) + "Read " + bytes.length + " bytes");
	}

	Class<?> clazz = elementType.toClass();
	String filename = hints != null ? (String) hints.get(FILENAME_HINT) : null;
	if (clazz == InputStreamResource.class) {
		return new InputStreamResource(new ByteArrayInputStream(bytes)) {
			@Override
			public String getFilename() {
				return filename;
			}
		};
	}
	else if (Resource.class.isAssignableFrom(clazz)) {
		return new ByteArrayResource(bytes) {
			@Override
			public String getFilename() {
				return filename;
			}
		};
	}
	else {
		throw new IllegalStateException("Unsupported resource class: " + clazz);
	}
}
 
源代码25 项目: flow-platform-x   文件: LoggingServiceImpl.java
@Override
public Resource get(String cmdId) {
    try {
        String fileName = getLogFile(cmdId);
        InputStream stream = fileManager.read(fileName, getLogDir(cmdId));
        return new InputStreamResource(stream);
    } catch (IOException e) {
        throw new NotFoundException("Log not available");
    }
}
 
@Override
@Test
public void canEncode() {
	assertTrue(this.encoder.canEncode(ResolvableType.forClass(InputStreamResource.class),
			MimeTypeUtils.TEXT_PLAIN));
	assertTrue(this.encoder.canEncode(ResolvableType.forClass(ByteArrayResource.class),
			MimeTypeUtils.TEXT_PLAIN));
	assertTrue(this.encoder.canEncode(ResolvableType.forClass(Resource.class),
			MimeTypeUtils.TEXT_PLAIN));
	assertTrue(this.encoder.canEncode(ResolvableType.forClass(InputStreamResource.class),
			MimeTypeUtils.APPLICATION_JSON));

	// SPR-15464
	assertFalse(this.encoder.canEncode(ResolvableType.NONE, null));
}
 
@Override
protected Resource readInternal(Class<? extends Resource> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	if (this.supportsReadStreaming && InputStreamResource.class == clazz) {
		return new InputStreamResource(inputMessage.getBody()) {
			@Override
			public String getFilename() {
				return inputMessage.getHeaders().getContentDisposition().getFilename();
			}
		};
	}
	else if (Resource.class == clazz || ByteArrayResource.class.isAssignableFrom(clazz)) {
		byte[] body = StreamUtils.copyToByteArray(inputMessage.getBody());
		return new ByteArrayResource(body) {
			@Override
			@Nullable
			public String getFilename() {
				return inputMessage.getHeaders().getContentDisposition().getFilename();
			}
		};
	}
	else {
		throw new HttpMessageNotReadableException("Unsupported resource class: " + clazz, inputMessage);
	}
}
 
@Override
protected Long getContentLength(Resource resource, @Nullable MediaType contentType) throws IOException {
	// Don't try to determine contentLength on InputStreamResource - cannot be read afterwards...
	// Note: custom InputStreamResource subclasses could provide a pre-calculated content length!
	if (InputStreamResource.class == resource.getClass()) {
		return null;
	}
	long contentLength = resource.contentLength();
	return (contentLength < 0 ? null : contentLength);
}
 
private static long lengthOf(Resource resource) {
	// Don't consume InputStream...
	if (InputStreamResource.class != resource.getClass()) {
		try {
			return resource.contentLength();
		}
		catch (IOException ignored) {
		}
	}
	return -1;
}
 
源代码30 项目: spring-analysis-note   文件: HttpRange.java
/**
 * Turn a {@code Resource} into a {@link ResourceRegion} using the range
 * information contained in the current {@code HttpRange}.
 * @param resource the {@code Resource} to select the region from
 * @return the selected region of the given {@code Resource}
 * @since 4.3
 */
public ResourceRegion toResourceRegion(Resource resource) {
	// Don't try to determine contentLength on InputStreamResource - cannot be read afterwards...
	// Note: custom InputStreamResource subclasses could provide a pre-calculated content length!
	Assert.isTrue(resource.getClass() != InputStreamResource.class,
			"Cannot convert an InputStreamResource to a ResourceRegion");
	long contentLength = getLengthFor(resource);
	long start = getRangeStart(contentLength);
	long end = getRangeEnd(contentLength);
	return new ResourceRegion(resource, start, end - start + 1);
}