org.springframework.core.io.ByteArrayResource Java Examples

The following examples show how to use org.springframework.core.io.ByteArrayResource. 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 File: CommonAutoDeploymentStrategy.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #2
Source File: IntegrationSpecificationITCase.java    From syndesis with 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 #3
Source File: EmailServiceImpl.java    From piggymetrics with 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 #4
Source File: IntegrationSpecificationITCase.java    From syndesis with 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 #5
Source File: HttpEntityMethodProcessorMockTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #6
Source File: AppRegistryController.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #7
Source File: HttpRangeTests.java    From spring-analysis-note with 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 #8
Source File: MailComposerImpl.java    From yes-cart with 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 #9
Source File: AbstractAutoDeploymentStrategy.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #10
Source File: MailService.java    From pacbot with 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 #11
Source File: BlacklistController.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 #12
Source File: ConvertUtils.java    From gemfirexd-oss with 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 #13
Source File: ImageCodeHandler.java    From sophia_scaffolding with 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 #14
Source File: YamlMapFactoryBeanTests.java    From java-technology-stack with 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 #15
Source File: ScriptableTransformProcessorConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
@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 #16
Source File: PropertySourceUtils.java    From spring-cloud-kubernetes with Apache License 2.0 6 votes vote down vote up
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 #17
Source File: ResourceHttpMessageConverterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 #18
Source File: SystemConfigController.java    From Jpom with MIT License 5 votes vote down vote up
@RequestMapping(value = "save_config.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String saveConfig(String content, String restart) {
    if (StrUtil.isEmpty(content)) {
        return JsonMessage.getString(405, "内容不能为空");
    }
    try {
        YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader();
        ByteArrayResource resource = new ByteArrayResource(content.getBytes());
        yamlPropertySourceLoader.load("test", resource);
    } catch (Exception e) {
        DefaultSystemLog.getLog().warn("内容格式错误,请检查修正", e);
        return JsonMessage.getString(500, "内容格式错误,请检查修正:" + e.getMessage());
    }
    if (JpomManifest.getInstance().isDebug()) {
        return JsonMessage.getString(405, "调试模式不支持在线修改,请到resource目录下");
    }
    File resourceFile = ExtConfigBean.getResourceFile();
    FileUtil.writeString(content, resourceFile, CharsetUtil.CHARSET_UTF_8);

    if (Convert.toBool(restart, false)) {
        // 重启
        ThreadUtil.execute(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ignored) {
            }
            JpomApplication.restart();
        });
    }
    return JsonMessage.getString(200, "修改成功");
}
 
Example #19
Source File: SmtpMailer.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void send(EventAndOrganizationId event, String fromName, String to, List<String> cc, String subject, String text,
                 Optional<String> html, Attachment... attachments) {

    var conf = configurationManager.getFor(Set.of(SMTP_FROM_EMAIL, MAIL_REPLY_TO,
        SMTP_HOST, SMTP_PORT, SMTP_PROTOCOL,
        SMTP_USERNAME, SMTP_PASSWORD, SMTP_PROPERTIES), ConfigurationLevel.event(event));

    MimeMessagePreparator preparator = mimeMessage -> {

        MimeMessageHelper message = html.isPresent() || !ArrayUtils.isEmpty(attachments) ? new MimeMessageHelper(mimeMessage, true, "UTF-8")
                : new MimeMessageHelper(mimeMessage, "UTF-8");
        message.setSubject(subject);
        message.setFrom(conf.get(SMTP_FROM_EMAIL).getRequiredValue(), fromName);
        String replyTo = conf.get(MAIL_REPLY_TO).getValueOrDefault("");
        if(StringUtils.isNotBlank(replyTo)) {
            message.setReplyTo(replyTo);
        }
        message.setTo(to);
        if(cc != null && !cc.isEmpty()){
            message.setCc(cc.toArray(new String[0]));
        }
        if (html.isPresent()) {
            message.setText(text, html.get());
        } else {
            message.setText(text, false);
        }

        if (attachments != null) {
            for (Attachment a : attachments) {
                message.addAttachment(a.getFilename(), new ByteArrayResource(a.getSource()), a.getContentType());
            }
        }
        
        message.getMimeMessage().saveChanges();
        message.getMimeMessage().removeHeader("Message-ID");
    };
    toMailSender(conf).send(preparator);
}
 
Example #20
Source File: ResourceDecoderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Test
public void canDecode() {
	assertTrue(this.decoder.canDecode(forClass(InputStreamResource.class), MimeTypeUtils.TEXT_PLAIN));
	assertTrue(this.decoder.canDecode(forClass(ByteArrayResource.class), MimeTypeUtils.TEXT_PLAIN));
	assertTrue(this.decoder.canDecode(forClass(Resource.class), MimeTypeUtils.TEXT_PLAIN));
	assertTrue(this.decoder.canDecode(forClass(InputStreamResource.class), MimeTypeUtils.APPLICATION_JSON));
	assertFalse(this.decoder.canDecode(forClass(Object.class), MimeTypeUtils.APPLICATION_JSON));
}
 
Example #21
Source File: YamlPropertiesFactoryBeanTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testLoadArrayOfObject() {
	YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
	factory.setResources(new ByteArrayResource(
			"foo:\n- bar:\n    spam: crap\n- baz\n- one: two\n  three: four".getBytes()
	));
	Properties properties = factory.getObject();
	assertThat(properties.getProperty("foo[0].bar.spam"), equalTo("crap"));
	assertThat(properties.getProperty("foo[1]"), equalTo("baz"));
	assertThat(properties.getProperty("foo[2].one"), equalTo("two"));
	assertThat(properties.getProperty("foo[2].three"), equalTo("four"));
	assertThat(properties.get("foo"), is(nullValue()));
}
 
Example #22
Source File: ResourceHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected Resource readInternal(Class<? extends Resource> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	if (InputStreamResource.class == clazz){
		return new InputStreamResource(inputMessage.getBody());
	}
	else if (clazz.isAssignableFrom(ByteArrayResource.class)) {
		byte[] body = StreamUtils.copyToByteArray(inputMessage.getBody());
		return new ByteArrayResource(body);
	}
	else {
		throw new IllegalStateException("Unsupported resource class: " + clazz);
	}
}
 
Example #23
Source File: YamlPropertiesFactoryBeanTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testLoadArrayOfString() {
	YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
	factory.setResources(new ByteArrayResource("foo:\n- bar\n- baz".getBytes()));
	Properties properties = factory.getObject();
	assertThat(properties.getProperty("foo[0]"), equalTo("bar"));
	assertThat(properties.getProperty("foo[1]"), equalTo("baz"));
	assertThat(properties.get("foo"), is(nullValue()));
}
 
Example #24
Source File: YamlProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void integerKeyBehaves() {
	this.processor.setResources(new ByteArrayResource("foo: bar\n1: bar".getBytes()));
	this.processor.process((properties, map) -> {
		assertEquals("bar", properties.get("[1]"));
		assertEquals(2, properties.size());
	});
}
 
Example #25
Source File: HomeControllerTests.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Test
public void fetchingImageShouldWork() {
	given(imageService.findOneImage(any()))
		.willReturn(Mono.just(
			new ByteArrayResource("data".getBytes())));

	webClient
		.get().uri("/images/alpha.png/raw")
		.exchange()
		.expectStatus().isOk()
		.expectBody(String.class).isEqualTo("data");

	verify(imageService).findOneImage("alpha.png");
	verifyNoMoreInteractions(imageService);
}
 
Example #26
Source File: HttpRangeTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void toResourceRegionIllegalLength() {
	ByteArrayResource resource = mock(ByteArrayResource.class);
	given(resource.contentLength()).willReturn(-1L);
	HttpRange range = HttpRange.createByteRange(0, 9);
	range.toResourceRegion(resource);
}
 
Example #27
Source File: YamlPropertiesFactoryBeanTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test(expected = DuplicateKeyException.class)
public void testLoadResourcesWithInternalOverride() {
	YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
	factory.setResources(new ByteArrayResource(
			"foo: bar\nspam:\n  foo: baz\nfoo: bucket".getBytes()));
	factory.getObject();
}
 
Example #28
Source File: YamlProcessorTests.java    From spring4-understanding with 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 #29
Source File: YamlPropertiesFactoryBeanTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testBadResource() {
	YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
	factory.setResources(new ByteArrayResource(
			"foo: bar\ncd\nspam:\n  foo: baz".getBytes()));
	assertThatExceptionOfType(ScannerException.class).isThrownBy(
			factory::getObject)
		.withMessageContaining("line 3, column 1");
}
 
Example #30
Source File: StringXmlApplicationContext.java    From tddl5 with 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();
}