类org.springframework.core.io.ByteArrayResource源码实例Demo

下面列出了怎么用org.springframework.core.io.ByteArrayResource的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: syndesis   文件: IntegrationSpecificationITCase.java
@Test
public void shouldServeOpenApiSpecificationInYamlFormat() throws IOException {
    final MultiValueMap<Object, Object> data = specification("/io/syndesis/server/runtime/test-swagger.yaml");

    final ResponseEntity<Integration> integrationResponse = post("/api/v1/apis/generator", data, Integration.class, tokenRule.validToken(), HttpStatus.OK,
        MULTIPART);

    final Integration integration = integrationResponse.getBody();
    final String integrationId = KeyGenerator.createKey();
    dataManager.create(integration.builder()
        .id(integrationId)
        .build());

    final ResponseEntity<ByteArrayResource> specificationResponse = get("/api/v1/integrations/" + integrationId + "/specification",
        ByteArrayResource.class);

    assertThat(specificationResponse.getHeaders().getContentType()).isEqualTo(MediaType.valueOf("application/vnd.oai.openapi"));
    final String givenYaml = getResourceAsText("io/syndesis/server/runtime/test-swagger.yaml");
    final String receivedJson = new String(specificationResponse.getBody().getByteArray(), StandardCharsets.UTF_8);

    final Object givenYamlObject = new Yaml(new SafeConstructor()).load(givenYaml);
    final String givenJson = JsonUtils.toString(givenYamlObject);

    assertThatJson(receivedJson).whenIgnoringPaths("$..operationId").isEqualTo(givenJson);
}
 
源代码2 项目: syndesis   文件: IntegrationSpecificationITCase.java
@Test
public void shouldServeOpenApiSpecificationInJsonFormat() throws IOException {
    final MultiValueMap<Object, Object> data = specification("/io/syndesis/server/runtime/test-swagger.json");

    final ResponseEntity<Integration> integrationResponse = post("/api/v1/apis/generator", data, Integration.class, tokenRule.validToken(), HttpStatus.OK,
        MULTIPART);

    final Integration integration = integrationResponse.getBody();
    final String integrationId = KeyGenerator.createKey();
    dataManager.create(integration.builder()
        .id(integrationId)
        .build());

    final ResponseEntity<ByteArrayResource> specificationResponse = get("/api/v1/integrations/" + integrationId + "/specification",
        ByteArrayResource.class);

    assertThat(specificationResponse.getHeaders().getContentType()).isEqualTo(MediaType.valueOf("application/vnd.oai.openapi+json"));

    final String givenJson = getResourceAsText("io/syndesis/server/runtime/test-swagger.json");
    final String receivedJson = new String(specificationResponse.getBody().getByteArray(), StandardCharsets.UTF_8);

    assertThatJson(receivedJson).whenIgnoringPaths("$..operationId").isEqualTo(givenJson);
}
 
@Test
public void shouldHandleResourceByteRange() throws Exception {
	ResponseEntity<Resource> returnValue = ResponseEntity
			.ok(new ByteArrayResource("Content".getBytes(StandardCharsets.UTF_8)));
	servletRequest.addHeader("Range", "bytes=0-5");

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

	processor.handleReturnValue(returnValue, returnTypeResponseEntityResource, mavContainer, webRequest);

	then(resourceRegionMessageConverter).should(times(1)).write(
			anyCollection(), eq(APPLICATION_OCTET_STREAM),
			argThat(outputMessage -> "bytes".equals(outputMessage.getHeaders().getFirst(HttpHeaders.ACCEPT_RANGES))));
	assertEquals(206, servletResponse.getStatus());
}
 
@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);
	}
}
 
/**
 * Register all applications listed in a properties file or provided as key/value pairs.
 *
 * @param pageable Pagination information
 * @param pagedResourcesAssembler the resource asembly for app registrations
 * @param uri URI for the properties file
 * @param apps key/value pairs representing applications, separated by newlines
 * @param force if {@code true}, overwrites any pre-existing registrations
 * @return the collection of registered applications
 * @throws IOException if can't store the Properties object to byte output stream
 */
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public PagedModel<? extends AppRegistrationResource> registerAll(
		Pageable pageable,
		PagedResourcesAssembler<AppRegistration> pagedResourcesAssembler,
		@RequestParam(value = "uri", required = false) String uri,
		@RequestParam(value = "apps", required = false) String apps,
		@RequestParam(value = "force", defaultValue = "false") boolean force) throws IOException {
	List<AppRegistration> registrations = new ArrayList<>();

	if (StringUtils.hasText(uri)) {
		registrations.addAll(this.appRegistryService.importAll(force, this.resourceLoader.getResource(uri)));
	}
	else if (!StringUtils.isEmpty(apps)) {
		ByteArrayResource bar = new ByteArrayResource(apps.getBytes());
		registrations.addAll(this.appRegistryService.importAll(force, bar));
	}

	Collections.sort(registrations);
	prefetchMetadata(registrations);
	return pagedResourcesAssembler.toModel(new PageImpl<>(registrations, pageable, registrations.size()), this.assembler);
}
 
源代码6 项目: spring-analysis-note   文件: HttpRangeTests.java
@Test
public void toResourceRegionsValidations() {
	byte[] bytes = "12345".getBytes(StandardCharsets.UTF_8);
	ByteArrayResource resource = new ByteArrayResource(bytes);

	// 1. Below length
	List<HttpRange> ranges = HttpRange.parseRanges("bytes=0-1,2-3");
	List<ResourceRegion> regions = HttpRange.toResourceRegions(ranges, resource);
	assertEquals(2, regions.size());

	// 2. At length
	ranges = HttpRange.parseRanges("bytes=0-1,2-4");
	try {
		HttpRange.toResourceRegions(ranges, resource);
		fail();
	}
	catch (IllegalArgumentException ex) {
		// Expected..
	}
}
 
源代码7 项目: yes-cart   文件: MailComposerImpl.java
/**
 * Add inline resource to mail message.
 * Resource id will be interpreted as file name in following fashion: filename_ext.
 *
 * @param helper          MimeMessageHelper, that has mail message
 * @param htmlTemplate    html message template
 * @param mailTemplateChain physical path to resources
 * @param shopCode        shop code
 * @param locale          locale
 * @param templateName    template name
 *
 * @throws javax.mail.MessagingException in case if resource can not be inlined
 */
void inlineResources(final MimeMessageHelper helper,
                     final String htmlTemplate,
                     final List<String> mailTemplateChain,
                     final String shopCode,
                     final String locale,
                     final String templateName) throws MessagingException, IOException {

    if (StringUtils.isNotBlank(htmlTemplate)) {
        final List<String> resourcesIds = getResourcesId(htmlTemplate);
        if (!resourcesIds.isEmpty()) {
            for (String resourceId : resourcesIds) {
                final String resourceFilename = transformResourceIdToFileName(resourceId);
                final byte[] content = mailTemplateResourcesProvider.getResource(mailTemplateChain, shopCode, locale, templateName, resourceFilename);
                helper.addInline(resourceId, new ByteArrayResource(content) {
                    @Override
                    public String getFilename() {
                        return resourceFilename;
                    }
                });
            }
        }
    }

}
 
/**
 * Determines the name to be used for the provided resource.
 * 
 * @param resource
 *          the resource to get the name for
 * @return the name of the resource
 */
protected String determineResourceName(final Resource resource) {
  String resourceName = null;

  if (resource instanceof ContextResource) {
    resourceName = ((ContextResource) resource).getPathWithinContext();

  } else if (resource instanceof ByteArrayResource) {
    resourceName = resource.getDescription();

  } else {
    try {
      resourceName = resource.getFile().getAbsolutePath();
    } catch (IOException e) {
      resourceName = resource.getFilename();
    }
  }
  return resourceName;
}
 
源代码9 项目: piggymetrics   文件: EmailServiceImpl.java
@Override
@CatAnnotation
public void send(NotificationType type, Recipient recipient, String attachment) throws MessagingException, IOException {

	final String subject = env.getProperty(type.getSubject());
	final String text = MessageFormat.format(env.getProperty(type.getText()), recipient.getAccountName());

	MimeMessage message = mailSender.createMimeMessage();

	MimeMessageHelper helper = new MimeMessageHelper(message, true);
	helper.setTo(recipient.getEmail());
	helper.setSubject(subject);
	helper.setText(text);

	if (StringUtils.hasLength(attachment)) {
		helper.addAttachment(env.getProperty(type.getAttachment()), new ByteArrayResource(attachment.getBytes()));
	}

	mailSender.send(message);
	log.info("{} email notification has been send to {}", type, recipient.getEmail());
}
 
源代码10 项目: pacbot   文件: MailService.java
private MimeMessagePreparator buildMimeMessagePreparator(String from, List<String> to, String subject, String mailContent , final String attachmentUrl) {
	MimeMessagePreparator messagePreparator = mimeMessage -> {
		MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
		messageHelper.setFrom(from);
		String[] toMailList = to.toArray(new String[to.size()]);
		messageHelper.setTo(toMailList);
		messageHelper.setSubject(subject);
		messageHelper.setText(mailContent, true);
		if(StringUtils.isNotEmpty(attachmentUrl) && isHttpUrl(attachmentUrl)) {
			URL url = new URL(attachmentUrl);
			String filename = url.getFile();
			byte fileContent [] = getFileContent(url);
			messageHelper.addAttachment(filename, new ByteArrayResource(fileContent));
		}
	};
	return messagePreparator;
}
 
源代码11 项目: openemm   文件: BlacklistController.java
@GetMapping("/download.action")
public ResponseEntity<Resource> download(ComAdmin admin) throws Exception {

    int companyId = admin.getCompanyID();
    Locale locale = admin.getLocale();

    String fileName = "blacklist.csv";
    String mediaType = "text/csv";

    List<BlacklistDto> recipientList = blacklistService.getAll(companyId);
    String csvContent = csvTableGenerator.generate(recipientList, locale);

    byte[] byteResource = csvContent.getBytes(StandardCharsets.UTF_8);
    ByteArrayResource resource = new ByteArrayResource(byteResource);

    // UAL
    String activityLogAction = "download blacklist";
    String activityLogDescription = "Row count: " + recipientList.size();
    userActivityLogService.writeUserActivityLog(admin, activityLogAction, activityLogDescription, logger);

    return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName)
            .contentLength(byteResource.length)
            .contentType(MediaType.parseMediaType(mediaType))
            .body(resource);
}
 
源代码12 项目: gemfirexd-oss   文件: ConvertUtils.java
/**
 * Converts the 2-dimensional byte array of file data, which includes the name of the file as bytes followed by
 * the byte content of the file, for all files being transmitted by Gfsh to the GemFire Manager.
 * <p/>
 * @param fileData a 2 dimensional byte array of files names and file content.
 * @return an array of Spring Resource objects encapsulating the details (name and content) of each file being
 * transmitted by Gfsh to the GemFire Manager.
 * @see org.springframework.core.io.ByteArrayResource
 * @see org.springframework.core.io.Resource
 * @see com.gemstone.gemfire.management.internal.cli.CliUtil#bytesToData(byte[][])
 * @see com.gemstone.gemfire.management.internal.cli.CliUtil#bytesToNames(byte[][])
 */
public static Resource[] convert(final byte[][] fileData) {
  if (fileData != null) {
    final String[] fileNames = CliUtil.bytesToNames(fileData);
    final byte[][] fileContent = CliUtil.bytesToData(fileData);

    final List<Resource> resources = new ArrayList<Resource>(fileNames.length);

    for (int index = 0; index < fileNames.length; index++) {
      final String filename = fileNames[index];
      resources.add(new ByteArrayResource(fileContent[index], String.format("Contents of JAR file (%1$s).", filename)) {
        @Override
        public String getFilename() {
          return filename;
        }
      });
    }

    return resources.toArray(new Resource[resources.size()]);
  }

  return new Resource[0];
}
 
源代码13 项目: sophia_scaffolding   文件: ImageCodeHandler.java
@Override
public Mono<ServerResponse> handle(ServerRequest serverRequest) {
	//生成验证码
	String text = producer.createText();
	BufferedImage image = producer.createImage(text);

	//保存验证码信息
	String randomStr = serverRequest.queryParam("randomStr").get();
	redisTemplate.opsForValue().set(DEFAULT_CODE_KEY + randomStr, text, 120, TimeUnit.SECONDS);

	// 转换流信息写出
	FastByteArrayOutputStream os = new FastByteArrayOutputStream();
	try {
		ImageIO.write(image, "jpeg", os);
	} catch (IOException e) {
		log.error("ImageIO write err", e);
		return Mono.error(e);
	}

	return ServerResponse
		.status(HttpStatus.OK)
		.contentType(MediaType.IMAGE_JPEG)
		.body(BodyInserters.fromResource(new ByteArrayResource(os.toByteArray())));
}
 
@Test
public void testFirstFound() {
	this.factory.setResolutionMethod(YamlProcessor.ResolutionMethod.FIRST_FOUND);
	this.factory.setResources(new AbstractResource() {
		@Override
		public String getDescription() {
			return "non-existent";
		}
		@Override
		public InputStream getInputStream() throws IOException {
			throw new IOException("planned");
		}
	}, new ByteArrayResource("foo:\n  spam: bar".getBytes()));

	assertEquals(1, this.factory.getObject().size());
}
 
源代码15 项目: java-technology-stack   文件: ResourceDecoder.java
@Override
protected Resource decodeDataBuffer(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();
	if (clazz == InputStreamResource.class) {
		return new InputStreamResource(new ByteArrayInputStream(bytes));
	}
	else if (Resource.class.isAssignableFrom(clazz)) {
		return new ByteArrayResource(bytes);
	}
	else {
		throw new IllegalStateException("Unsupported resource class: " + clazz);
	}
}
 
@Bean
@Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
public MessageProcessor<?> transformer() {
	String language = this.properties.getLanguage();
	String script = this.properties.getScript();
	logger.info(String.format("Input script is '%s', language is '%s'", script, language));
	Resource scriptResource = new ByteArrayResource(decodeScript(script).getBytes()) {

		// TODO until INT-3976
		@Override
		public String getFilename() {
			// Only the groovy script processor enforces this requirement for a name
			return "StaticScript";
		}

	};
	return Scripts.script(scriptResource)
			.lang(language)
			.variableGenerator(this.scriptVariableGenerator)
			.get();
}
 
static Function<String, Properties> yamlParserGenerator(Environment environment) {
	return s -> {
		YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
		yamlFactory.setDocumentMatchers(properties -> {
			String profiles = properties.getProperty("spring.profiles");
			if (environment != null && StringUtils.hasText(profiles)) {
				return environment.acceptsProfiles(Profiles.of(profiles)) ? FOUND
						: NOT_FOUND;
			}
			else {
				return ABSTAIN;
			}
		});
		yamlFactory.setResources(new ByteArrayResource(s.getBytes()));
		return yamlFactory.getObject();
	};
}
 
/**
 * Determines the name to be used for the provided resource.
 *
 * @param resource the resource to get the name for
 * @return the name of the resource
 */
protected String determineResourceName(final Resource resource) {
    String resourceName = null;

    if (resource instanceof ContextResource) {
        resourceName = ((ContextResource) resource).getPathWithinContext();

    } else if (resource instanceof ByteArrayResource) {
        resourceName = resource.getDescription();

    } else {
        try {
            resourceName = resource.getFile().getAbsolutePath();
        } catch (IOException e) {
            resourceName = resource.getFilename();
        }
    }
    return resourceName;
}
 
源代码19 项目: fake-smtp-server   文件: EmailController.java
@GetMapping("/email/{mailId}/attachment/{attachmentId}")
@ResponseBody
public ResponseEntity<ByteArrayResource> getEmailAttachmentById(@PathVariable Long mailId, @PathVariable Long attachmentId) {
    var attachment = emailAttachmentRepository.findById(attachmentId)
            .filter(a -> a.getEmail().getId().equals(mailId))
            .orElseThrow(() -> new AttachmentNotFoundException("Attachment with id " + attachmentId + " not found for mail " + mailId));

    var mediaType = mediaTypeUtil.getMediaTypeForFileName(this.servletContext, attachment.getFilename());

    return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + attachment.getFilename())
            .contentType(mediaType)
            .contentLength(attachment.getData().length) //
            .body(new ByteArrayResource(attachment.getData()));
}
 
源代码20 项目: KOMORAN   文件: DicWordController.java
@GetMapping(value = "/download")
public ResponseEntity<?> downloadFile() {
    String dicWordBody = dicWordService.exportToString();
    ByteArrayResource resource = new ByteArrayResource(dicWordBody.getBytes());

    return ResponseEntity.ok()
            .contentType(MediaType.TEXT_PLAIN)
            .header("Content-Disposition", "attachment; filename=" + dicWordFilename)
            .body(resource);
}
 
源代码21 项目: tddl5   文件: StringXmlApplicationContext.java
public StringXmlApplicationContext(String[] stringXmls, ApplicationContext parent, ClassLoader cl){
    super(parent);
    this.cl = cl;
    this.configResources = new Resource[stringXmls.length];
    for (int i = 0; i < stringXmls.length; i++) {
        this.configResources[i] = new ByteArrayResource(stringXmls[i].getBytes());
    }
    refresh();
}
 
@Test  // SPR-10848
public void writeByteArrayNullMediaType() throws IOException {
	MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
	byte[] byteArray = {1, 2, 3};
	Resource body = new ByteArrayResource(byteArray);
	converter.write(body, null, outputMessage);

	assertTrue(Arrays.equals(byteArray, outputMessage.getBodyAsBytes()));
}
 
源代码23 项目: spring4-understanding   文件: YamlProcessorTests.java
@Test
public void testBadResource() throws Exception {
	this.processor.setResources(new ByteArrayResource(
			"foo: bar\ncd\nspam:\n  foo: baz".getBytes()));
	this.exception.expect(ScannerException.class);
	this.exception.expectMessage("line 3, column 1");
	this.processor.process(new MatchCallback() {
		@Override
		public void process(Properties properties, Map<String, Object> map) {
		}
	});
}
 
@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
public void encode() {
	Flux<Resource> input = Flux.just(new ByteArrayResource(this.bytes));

	testEncodeAll(input, Resource.class, step -> step
			.consumeNextWith(expectBytes(this.bytes))
			.verifyComplete());
}
 
@SuppressWarnings("unchecked")
@Test
public void testOverrideAndRemoveDefaults() {
	this.factory.setResources(new ByteArrayResource("foo:\n  bar: spam".getBytes()),
			new ByteArrayResource("foo:\n  spam: bar".getBytes()));

	assertEquals(1, this.factory.getObject().size());
	assertEquals(2, ((Map<String, Object>) this.factory.getObject().get("foo")).size());
}
 
@Test
public void handleReturnTypeResourceIllegalByteRange() throws Exception {
	Resource returnValue = new ByteArrayResource("Content".getBytes(StandardCharsets.UTF_8));
	servletRequest.addHeader("Range", "illegal");

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

	processor.handleReturnValue(returnValue, returnTypeResource, mavContainer, webRequest);

	then(resourceRegionMessageConverter).should(never()).write(
			anyCollection(), eq(MediaType.APPLICATION_OCTET_STREAM), any(HttpOutputMessage.class));
	assertEquals(416, servletResponse.getStatus());
}
 
@Test
public void testLoadResourcesWithOverride() throws Exception {
	YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
	factory.setResources(
			new ByteArrayResource("foo: bar\nspam:\n  foo: baz".getBytes()),
			new ByteArrayResource("foo:\n  bar: spam".getBytes()));
	Properties properties = factory.getObject();
	assertThat(properties.getProperty("foo"), equalTo("bar"));
	assertThat(properties.getProperty("spam.foo"), equalTo("baz"));
	assertThat(properties.getProperty("foo.bar"), equalTo("spam"));
}
 
@Test
public void handleReturnTypeResourceByteRange() throws Exception {
	Resource returnValue = new ByteArrayResource("Content".getBytes(StandardCharsets.UTF_8));
	servletRequest.addHeader("Range", "bytes=0-5");

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

	processor.handleReturnValue(returnValue, returnTypeResource, mavContainer, webRequest);

	then(resourceRegionMessageConverter).should(times(1)).write(
			anyCollection(), eq(MediaType.APPLICATION_OCTET_STREAM),
			argThat(outputMessage -> "bytes".equals(outputMessage.getHeaders().getFirst(HttpHeaders.ACCEPT_RANGES))));
	assertEquals(206, servletResponse.getStatus());
}
 
@Test
public void handleReturnTypeResourceIllegalByteRange() throws Exception {
	Resource returnValue = new ByteArrayResource("Content".getBytes(StandardCharsets.UTF_8));
	servletRequest.addHeader("Range", "illegal");

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

	processor.handleReturnValue(returnValue, returnTypeResource, mavContainer, webRequest);

	then(resourceRegionMessageConverter).should(never()).write(
			anyCollection(), eq(MediaType.APPLICATION_OCTET_STREAM), any(HttpOutputMessage.class));
	assertEquals(416, servletResponse.getStatus());
}
 
 类方法
 同包方法