org.springframework.util.MimeType Java Examples

The following examples show how to use org.springframework.util.MimeType. 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: MailUtils.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Convert message body to text if possible, otherwise throw exception.
 * @param body
 * @return
 */
public static String toPlainText(MailBody body) throws MailBadMessageException {
    MimeType mimeType = body.getMimeType();
    boolean containsMime = false;
    for (MimeType type : mimeTypeSet) {
        containsMime = containsMime || type.includes(mimeType);
    }
    if(!containsMime) {
        throw new MailBadMessageException("Message contains body with unsupported contentType: " + mimeType);
    }
    try(Reader r = body.getReader()) {
        return IOUtils.toString(r);
    } catch (IOException e) {
        throw new MailBadMessageException(e);
    }
}
 
Example #2
Source File: DefaultStompSessionTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void send() throws Exception {

	this.session.afterConnected(this.connection);
	assertTrue(this.session.isConnected());

	String destination = "/topic/foo";
	String payload = "sample payload";
	this.session.send(destination, payload);

	Message<byte[]> message = this.messageCaptor.getValue();
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertEquals(StompCommand.SEND, accessor.getCommand());

	StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
	assertEquals(stompHeaders.toString(), 2, stompHeaders.size());

	assertEquals(destination, stompHeaders.getDestination());
	assertEquals(new MimeType("text", "plain", UTF_8), stompHeaders.getContentType());
	assertEquals(-1, stompHeaders.getContentLength()); // StompEncoder isn't involved
	assertEquals(payload, new String(message.getPayload(), UTF_8));
}
 
Example #3
Source File: AbstractJackson2Decoder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public Object decode(DataBuffer dataBuffer, ResolvableType targetType,
		@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) throws DecodingException {

	try {
		ObjectReader objectReader = getObjectReader(targetType, hints);
		Object value = objectReader.readValue(dataBuffer.asInputStream());
		logValue(value, hints);
		return value;
	}
	catch (IOException ex) {
		throw processException(ex);
	}
	finally {
		DataBufferUtils.release(dataBuffer);
	}
}
 
Example #4
Source File: RenditionServiceImpl.java    From spring-content with Apache License 2.0 6 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation, StoreInvoker invoker) {
	String fromMimeType = null;
	fromMimeType = (String) BeanUtils.getFieldWithAnnotation(
			invocation.getArguments()[0],
			org.springframework.content.commons.annotations.MimeType.class);
	if (fromMimeType == null) {
		return null;
	}
	String toMimeType = (String) invocation.getArguments()[1];

	if (this.canConvert(fromMimeType, toMimeType)) {
		InputStream content = null;
		try {
			content = invoker.invokeGetContent();
			return (InputStream) this.convert(fromMimeType, content, toMimeType);
		}
		catch (Exception e) {
			LOGGER.error(String.format("Failed to get rendition from %s to %s",
					fromMimeType, toMimeType), e);
		}
	}
	return null;
}
 
Example #5
Source File: AbstractEncoderTestCase.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Test a {@link Encoder#encode encode} scenario where the input stream contains an error.
 * This test method will feed the first element of the {@code input} stream to the encoder,
 * followed by an {@link InputException}.
 * The result is expected to contain one "normal" element, followed by the error.
 *
 * @param input the input to be provided to the encoder
 * @param inputType the input type
 * @param mimeType the mime type to use for decoding. May be {@code null}.
 * @param hints the hints used for decoding. May be {@code null}.
 * @see InputException
 */
protected void testEncodeError(Publisher<?> input, ResolvableType inputType,
		@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {

	input = Flux.concat(
			Flux.from(input).take(1),
			Flux.error(new InputException()));

	Flux<DataBuffer> result = encoder().encode(input, this.bufferFactory, inputType,
			mimeType, hints);

	StepVerifier.create(result)
			.consumeNextWith(DataBufferUtils::release)
			.expectError(InputException.class)
			.verify();
}
 
Example #6
Source File: MappingJackson2MessageConverterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void toMessage() {
	MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
	MyBean payload = new MyBean();
	payload.setString("Foo");
	payload.setNumber(42);
	payload.setFraction(42F);
	payload.setArray(new String[]{"Foo", "Bar"});
	payload.setBool(true);
	payload.setBytes(new byte[]{0x1, 0x2});

	Message<?> message = converter.toMessage(payload, null);
	String actual = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8);

	assertTrue(actual.contains("\"string\":\"Foo\""));
	assertTrue(actual.contains("\"number\":42"));
	assertTrue(actual.contains("fraction\":42.0"));
	assertTrue(actual.contains("\"array\":[\"Foo\",\"Bar\"]"));
	assertTrue(actual.contains("\"bool\":true"));
	assertTrue(actual.contains("\"bytes\":\"AQI=\""));
	assertEquals("Invalid content-type", new MimeType("application", "json"),
			message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class));
}
 
Example #7
Source File: Jaxb2XmlDecoder.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public Flux<Object> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType,
		@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {

	Flux<XMLEvent> xmlEventFlux = this.xmlEventDecoder.decode(
			inputStream, ResolvableType.forClass(XMLEvent.class), mimeType, hints);

	Class<?> outputClass = elementType.toClass();
	QName typeName = toQName(outputClass);
	Flux<List<XMLEvent>> splitEvents = split(xmlEventFlux, typeName);

	return splitEvents.map(events -> {
		Object value = unmarshal(events, outputClass);
		LogFormatUtils.traceDebug(logger, traceOn -> {
			String formatted = LogFormatUtils.formatValue(value, !traceOn);
			return Hints.getLogPrefix(hints) + "Decoded [" + formatted + "]";
		});
		return value;
	});
}
 
Example #8
Source File: ContentTypeTckTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void typelessToPojoWithTextHeaderContentTypeBinding() {
	ApplicationContext context = new SpringApplicationBuilder(
			TypelessToPojoStreamListener.class).web(WebApplicationType.NONE)
					.run("--spring.jmx.enabled=false");
	InputDestination source = context.getBean(InputDestination.class);
	OutputDestination target = context.getBean(OutputDestination.class);
	String jsonPayload = "{\"name\":\"oleg\"}";
	source.send(MessageBuilder.withPayload(jsonPayload.getBytes())
			.setHeader(MessageHeaders.CONTENT_TYPE, MimeType.valueOf("text/plain"))
			.build());
	Message<byte[]> outputMessage = target.receive();
	assertThat(outputMessage.getHeaders().get(MessageHeaders.CONTENT_TYPE))
			.isEqualTo(MimeTypeUtils.APPLICATION_JSON);
	assertThat(new String(outputMessage.getPayload(), StandardCharsets.UTF_8))
			.isEqualTo(jsonPayload);
}
 
Example #9
Source File: BeanFactoryAwareFunctionRegistryTests.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testSerializationWithCompatibleWildcardSubtypeAcceptHeader() {
	FunctionCatalog catalog = this.configureCatalog(NegotiatingMessageConverterConfiguration.class);
	FunctionInvocationWrapper function = catalog.lookup("echo", "text/*");

	Message<Tuple2<String, String>> tupleResult = (Message<Tuple2<String, String>>) function.apply(MessageBuilder
			.withPayload(Tuples.of("bonjour", "monde"))
			.setHeader(MessageHeaders.CONTENT_TYPE, MimeType.valueOf("text/csv"))
			.build()
	);

	assertThat(tupleResult.getHeaders().get(MessageHeaders.CONTENT_TYPE)).isEqualTo(MimeType.valueOf("text/csv"));
	assertThat(tupleResult.getHeaders().get("accept")).isNull();

	Message<Date> dateResult = (Message<Date>) function.apply(MessageBuilder
			.withPayload(123)
			.setHeader(MessageHeaders.CONTENT_TYPE, MimeType.valueOf("text/integer"))
			.build()
	);

	assertThat(dateResult.getHeaders().get(MessageHeaders.CONTENT_TYPE)).isEqualTo(MimeType.valueOf("text/integer"));
	assertThat(dateResult.getHeaders().get("accept")).isNull();
}
 
Example #10
Source File: QueueMessageChannelTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void sendMessage_withMimeTypeAsStringHeader_shouldPassItAsMessageAttribute()
		throws Exception {
	// Arrange
	AmazonSQSAsync amazonSqs = mock(AmazonSQSAsync.class);
	QueueMessageChannel messageChannel = new QueueMessageChannel(amazonSqs,
			"http://testQueue");
	String mimeTypeAsString = new MimeType("test", "plain", Charset.forName("UTF-8"))
			.toString();
	Message<String> message = MessageBuilder.withPayload("Hello")
			.setHeader(MessageHeaders.CONTENT_TYPE, mimeTypeAsString).build();

	ArgumentCaptor<SendMessageRequest> sendMessageRequestArgumentCaptor = ArgumentCaptor
			.forClass(SendMessageRequest.class);
	when(amazonSqs.sendMessage(sendMessageRequestArgumentCaptor.capture()))
			.thenReturn(new SendMessageResult());

	// Act
	boolean sent = messageChannel.send(message);

	// Assert
	assertThat(sent).isTrue();
	assertThat(sendMessageRequestArgumentCaptor.getValue().getMessageAttributes()
			.get(MessageHeaders.CONTENT_TYPE).getStringValue())
					.isEqualTo(mimeTypeAsString);
}
 
Example #11
Source File: ContentTypeTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testReceiveRawWithDifferentContentTypes() {
	try (ConfigurableApplicationContext context = SpringApplication.run(
			SinkApplication.class, "--server.port=0", "--spring.jmx.enabled=false")) {
		TestSink testSink = context.getBean(TestSink.class);
		SinkApplication sourceApp = context.getBean(SinkApplication.class);
		testSink.raw().send(MessageBuilder.withPayload(new byte[4])
				.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.IMAGE_JPEG)
				.build());
		testSink.raw().send(MessageBuilder.withPayload(new byte[4])
				.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.IMAGE_GIF)
				.build());
		Map<String, Object> headers = (Map<String, Object>) sourceApp.arguments.pop();
		sourceApp.arguments.pop();
		assertThat(((MimeType) headers.get(MessageHeaders.CONTENT_TYPE))
				.includes(MimeTypeUtils.IMAGE_GIF));
		headers = (Map<String, Object>) sourceApp.arguments.pop();
		sourceApp.arguments.pop();
		assertThat(((MimeType) headers.get(MessageHeaders.CONTENT_TYPE))
				.includes(MimeTypeUtils.IMAGE_JPEG));
	}
}
 
Example #12
Source File: EncoderHttpMessageWriterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void testDefaultMediaType(MediaType negotiatedMediaType) {

		this.mediaTypeCaptor = ArgumentCaptor.forClass(MediaType.class);

		MimeType defaultContentType = MimeTypeUtils.TEXT_XML;
		HttpMessageWriter<String> writer = getWriter(defaultContentType);
		writer.write(Mono.just("body"), forClass(String.class), negotiatedMediaType, this.response, NO_HINTS);

		assertEquals(defaultContentType, this.response.getHeaders().getContentType());
		assertEquals(defaultContentType, this.mediaTypeCaptor.getValue());
	}
 
Example #13
Source File: Jackson2JsonDecoderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test  // SPR-15866
public void canDecodeWithProvidedMimeType() {
	MimeType textJavascript = new MimeType("text", "javascript", StandardCharsets.UTF_8);
	Jackson2JsonDecoder decoder = new Jackson2JsonDecoder(new ObjectMapper(), textJavascript);

	assertEquals(Collections.singletonList(textJavascript), decoder.getDecodableMimeTypes());
}
 
Example #14
Source File: AbstractMessageConverter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public final Message<?> toMessage(Object payload, MessageHeaders headers, Object conversionHint) {
	if (!canConvertTo(payload, headers)) {
		return null;
	}

	payload = convertToInternal(payload, headers, conversionHint);
	if (payload == null) {
		return null;
	}

	MimeType mimeType = getDefaultContentType(payload);
	if (headers != null) {
		MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(headers, MessageHeaderAccessor.class);
		if (accessor != null && accessor.isMutable()) {
			accessor.setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, mimeType);
			return MessageBuilder.createMessage(payload, accessor.getMessageHeaders());
		}
	}

	MessageBuilder<?> builder = MessageBuilder.withPayload(payload);
	if (headers != null) {
		builder.copyHeaders(headers);
	}
	builder.setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, mimeType);
	return builder.build();
}
 
Example #15
Source File: MappingJackson2MessageConverterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void toMessageUtf16String() {
	MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
	converter.setSerializedPayloadClass(String.class);

	MimeType contentType = new MimeType("application", "json", StandardCharsets.UTF_16BE);
	Map<String, Object> map = new HashMap<>();
	map.put(MessageHeaders.CONTENT_TYPE, contentType);
	MessageHeaders headers = new MessageHeaders(map);
	String payload = "H\u00e9llo W\u00f6rld";
	Message<?> message = converter.toMessage(payload, headers);

	assertEquals("\"" + payload + "\"", message.getPayload());
	assertEquals(contentType, message.getHeaders().get(MessageHeaders.CONTENT_TYPE));
}
 
Example #16
Source File: MockServletContext.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
public String getMimeType(String filePath) {
	String extension = StringUtils.getFilenameExtension(filePath);
	if (this.mimeTypes.containsKey(extension)) {
		return this.mimeTypes.get(extension).toString();
	}
	else {
		return MediaTypeFactory.getMediaType(filePath).
				map(MimeType::toString)
				.orElse(null);
	}
}
 
Example #17
Source File: AbstractMessageConverter.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected boolean supportsMimeType(@Nullable MessageHeaders headers) {
	if (getSupportedMimeTypes().isEmpty()) {
		return true;
	}
	MimeType mimeType = getMimeType(headers);
	if (mimeType == null) {
		return !isStrictContentTypeMatch();
	}
	for (MimeType current : getSupportedMimeTypes()) {
		if (current.getType().equals(mimeType.getType()) && current.getSubtype().equals(mimeType.getSubtype())) {
			return true;
		}
	}
	return false;
}
 
Example #18
Source File: DispatchHandlerTests.java    From spring-cloud-sockets with Apache License 2.0 5 votes vote down vote up
@Test
public void oneWayHandler() throws Exception{
	User user = new User("Mary", "blue");
	Mono<Void> result = this.handler.fireAndForget(new PayloadImpl(converter.write(user), getMetadataBytes(MimeType.valueOf("application/json") ,"/oneway")));
	User output = (User) resultsQueue.poll();
	assertThat(output).isEqualTo(user);
}
 
Example #19
Source File: DataBufferEncoder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public DataBuffer encodeValue(DataBuffer buffer, DataBufferFactory bufferFactory,
		ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {

	if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) {
		logValue(buffer, hints);
	}
	return buffer;
}
 
Example #20
Source File: AbstractMessageConverter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Nullable
public final Message<?> toMessage(Object payload, @Nullable MessageHeaders headers, @Nullable Object conversionHint) {
	if (!canConvertTo(payload, headers)) {
		return null;
	}

	Object payloadToUse = convertToInternal(payload, headers, conversionHint);
	if (payloadToUse == null) {
		return null;
	}

	MimeType mimeType = getDefaultContentType(payloadToUse);
	if (headers != null) {
		MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(headers, MessageHeaderAccessor.class);
		if (accessor != null && accessor.isMutable()) {
			if (mimeType != null) {
				accessor.setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, mimeType);
			}
			return MessageBuilder.createMessage(payloadToUse, accessor.getMessageHeaders());
		}
	}

	MessageBuilder<?> builder = MessageBuilder.withPayload(payloadToUse);
	if (headers != null) {
		builder.copyHeaders(headers);
	}
	if (mimeType != null) {
		builder.setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, mimeType);
	}
	return builder.build();
}
 
Example #21
Source File: Jaxb2XmlEncoder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected Flux<DataBuffer> encode(Object value, DataBufferFactory bufferFactory,
		ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {

	// we're relying on doOnDiscard in base class
	return Mono.fromCallable(() -> encodeValue(value, bufferFactory, valueType, mimeType, hints)).flux();
}
 
Example #22
Source File: XpathAssertions.java    From java-technology-stack with MIT License 5 votes vote down vote up
private String getCharset() {
	return Optional.of(this.bodySpec.returnResult())
			.map(EntityExchangeResult::getResponseHeaders)
			.map(HttpHeaders::getContentType)
			.map(MimeType::getCharset)
			.orElse(StandardCharsets.UTF_8)
			.name();
}
 
Example #23
Source File: TopicMessageChannel.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private MessageAttributeValue getContentTypeMessageAttribute(
		Object messageHeaderValue) {
	if (messageHeaderValue instanceof MimeType) {
		return new MessageAttributeValue()
				.withDataType(MessageAttributeDataTypes.STRING)
				.withStringValue(messageHeaderValue.toString());
	}
	else if (messageHeaderValue instanceof String) {
		return new MessageAttributeValue()
				.withDataType(MessageAttributeDataTypes.STRING)
				.withStringValue((String) messageHeaderValue);
	}
	return null;
}
 
Example #24
Source File: StringMessageConverter.java    From java-technology-stack with MIT License 5 votes vote down vote up
private Charset getContentTypeCharset(@Nullable MimeType mimeType) {
	if (mimeType != null && mimeType.getCharset() != null) {
		return mimeType.getCharset();
	}
	else {
		return this.defaultCharset;
	}
}
 
Example #25
Source File: StompHeaderAccessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
void updateStompHeadersFromSimpMessageHeaders() {
	String destination = getDestination();
	if (destination != null) {
		setNativeHeader(STOMP_DESTINATION_HEADER, destination);
	}
	MimeType contentType = getContentType();
	if (contentType != null) {
		setNativeHeader(STOMP_CONTENT_TYPE_HEADER, contentType.toString());
	}
	trySetStompHeaderForSubscriptionId();
}
 
Example #26
Source File: MappingJackson2MessageConverterTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test  // SPR-12724
public void mimetypesParametrizedConstructor() {
	MimeType jsonMimetype = new MimeType("application", "json", UTF_8);
	MimeType xmlMimetype = new MimeType("application", "xml", UTF_8);
	MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(jsonMimetype, xmlMimetype);
	assertThat(converter.getSupportedMimeTypes(), contains(jsonMimetype, xmlMimetype));
	assertFalse(converter.getObjectMapper().getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
}
 
Example #27
Source File: DefaultWebTestClient.java    From java-technology-stack with MIT License 5 votes vote down vote up
private String getBodyAsString() {
	byte[] body = this.result.getResponseBody();
	if (body == null || body.length == 0) {
		return "";
	}
	Charset charset = Optional.ofNullable(this.result.getResponseHeaders().getContentType())
			.map(MimeType::getCharset).orElse(StandardCharsets.UTF_8);
	return new String(body, charset);
}
 
Example #28
Source File: NegotiatingMessageConverterWrapperTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@Test
public void testSerializationWithCompatibleConcreteAcceptHeader() {
	MimeType acceptableType = MimeType.valueOf("text/csv");

	Message<?> result = NegotiatingMessageConverterWrapper.wrap(new NaiveCsvTupleMessageConverter())
		.toMessage(somePayload, new MessageHeaders(newHashMap(ACCEPT, acceptableType)));

	assertMessageContent(result, "text/csv", expectedSerializedPayload);
}
 
Example #29
Source File: BillingApp.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 5 votes vote down vote up
@Bean
@StreamMessageConverter
public MessageConverter bookingOrderMessageConverter() throws IOException {
  MessageConverter avroSchemaMessageConverter = new AvroSchemaMessageConverter(
      MimeType.valueOf("application/*+avro"));
  ((AvroSchemaMessageConverter) avroSchemaMessageConverter)
      .setSchemaLocation(new ClassPathResource("avro/billingOrder.avsc"));
  return avroSchemaMessageConverter;
}
 
Example #30
Source File: MessageConverterUtils.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
public static MimeType resolveContentType(String type)
		throws ClassNotFoundException, LinkageError {
	if (!type.contains("/")) {
		Class<?> javaType = resolveJavaType(type);
		return javaObjectMimeType(javaType);
	}
	return MimeType.valueOf(type);
}