Java Code Examples for org.springframework.core.io.ByteArrayResource

The following examples show how to use org.springframework.core.io.ByteArrayResource. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: syndesis   Source File: IntegrationSpecificationITCase.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 2
Source Project: syndesis   Source File: IntegrationSpecificationITCase.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 3
@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());
}
 
Example 4
/**
 * 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);
}
 
Example 5
Source Project: spring-analysis-note   Source File: HttpRangeTests.java    License: MIT License 6 votes vote down vote up
@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..
	}
}
 
Example 6
Source Project: yes-cart   Source File: MailComposerImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
                    }
                });
            }
        }
    }

}
 
Example 7
/**
 * 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;
}
 
Example 8
Source Project: piggymetrics   Source File: EmailServiceImpl.java    License: MIT License 6 votes vote down vote up
@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());
}
 
Example 9
Source Project: pacbot   Source File: MailService.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 10
@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);
}
 
Example 11
Source Project: gemfirexd-oss   Source File: ConvertUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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];
}
 
Example 12
Source Project: sophia_scaffolding   Source File: ImageCodeHandler.java    License: Apache License 2.0 6 votes vote down vote up
@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())));
}
 
Example 13
Source Project: java-technology-stack   Source File: YamlMapFactoryBeanTests.java    License: MIT License 6 votes vote down vote up
@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());
}
 
Example 14
@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();
}
 
Example 15
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();
	};
}
 
Example 16
/**
 * 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;
}
 
Example 17
Source Project: fake-smtp-server   Source File: EmailController.java    License: Apache License 2.0 5 votes vote down vote up
@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()));
}
 
Example 18
Source Project: KOMORAN   Source File: DicWordController.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 19
Source Project: tddl5   Source File: StringXmlApplicationContext.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 20
@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()));
}
 
Example 21
Source Project: spring4-understanding   Source File: YamlProcessorTests.java    License: Apache License 2.0 5 votes vote down vote up
@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) {
		}
	});
}
 
Example 22
Source Project: spring-analysis-note   Source File: ResourceEncoderTests.java    License: MIT License 5 votes vote down vote up
@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));
}
 
Example 23
Source Project: spring-analysis-note   Source File: ResourceEncoderTests.java    License: MIT License 5 votes vote down vote up
@Override
public void encode() {
	Flux<Resource> input = Flux.just(new ByteArrayResource(this.bytes));

	testEncodeAll(input, Resource.class, step -> step
			.consumeNextWith(expectBytes(this.bytes))
			.verifyComplete());
}
 
Example 24
Source Project: java-technology-stack   Source File: YamlMapFactoryBeanTests.java    License: MIT License 5 votes vote down vote up
@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());
}
 
Example 25
@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());
}
 
Example 26
@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"));
}
 
Example 27
@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());
}
 
Example 28
@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());
}
 
Example 29
@Test
public void handleReturnTypeResourceIllegalByteRange() throws Exception {
	ResponseEntity<Resource> returnValue = ResponseEntity
			.ok(new ByteArrayResource("Content".getBytes(StandardCharsets.UTF_8)));
	servletRequest.addHeader("Range", "illegal");

	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(never()).write(
			anyCollection(), eq(APPLICATION_OCTET_STREAM), any(HttpOutputMessage.class));
	assertEquals(416, servletResponse.getStatus());
}
 
Example 30
@Test //SPR-16921
public void disableRangeSupportIfContentRangePresent() throws Exception {
	ResponseEntity<Resource> returnValue = ResponseEntity
			.status(HttpStatus.PARTIAL_CONTENT)
			.header(HttpHeaders.RANGE, "bytes=0-5")
			.body(new ByteArrayResource("Content".getBytes(StandardCharsets.UTF_8)));

	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(never()).write(anyCollection(), any(), any());
	assertEquals(206, servletResponse.getStatus());
}