org.springframework.util.MimeType源码实例Demo

类org.springframework.util.MimeType源码实例Demo

下面列出了org.springframework.util.MimeType 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: java-technology-stack   文件: Jaxb2XmlDecoder.java
@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;
	});
}
 
源代码2 项目: spring-cloud-stream   文件: ContentTypeTckTests.java
@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);
}
 
@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));
}
 
@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();
}
 
@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);
	}
}
 
@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));
}
 
@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);
}
 
源代码8 项目: spring-content   文件: RenditionServiceImpl.java
@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;
}
 
源代码9 项目: spring-cloud-stream   文件: ContentTypeTests.java
@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));
	}
}
 
/**
 * 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();
}
 
源代码11 项目: haven-platform   文件: MailUtils.java
/**
 * 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);
    }
}
 
@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;
}
 
@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();
}
 
源代码14 项目: java-technology-stack   文件: MockServletContext.java
@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);
	}
}
 
@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();
}
 
源代码16 项目: java-technology-stack   文件: XpathAssertions.java
private String getCharset() {
	return Optional.of(this.bodySpec.returnResult())
			.map(EntityExchangeResult::getResponseHeaders)
			.map(HttpHeaders::getContentType)
			.map(MimeType::getCharset)
			.orElse(StandardCharsets.UTF_8)
			.name();
}
 
private Charset getContentTypeCharset(@Nullable MimeType mimeType) {
	if (mimeType != null && mimeType.getCharset() != null) {
		return mimeType.getCharset();
	}
	else {
		return this.defaultCharset;
	}
}
 
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();
}
 
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);
}
 
@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);
}
 
public static MimeType resolveContentType(String type)
		throws ClassNotFoundException, LinkageError {
	if (!type.contains("/")) {
		Class<?> javaType = resolveJavaType(type);
		return javaObjectMimeType(javaType);
	}
	return MimeType.valueOf(type);
}
 
源代码22 项目: spring-analysis-note   文件: Jaxb2XmlEncoder.java
@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();
}
 
@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));
}
 
源代码24 项目: spring-cloud-aws   文件: TopicMessageChannel.java
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;
}
 
源代码25 项目: spring-analysis-note   文件: DataBufferEncoder.java
@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;
}
 
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;
}
 
@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);
}
 
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());
	}
 
@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));
}
 
@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());
}
 
源代码评论
动弹
沙发等你来抢
 类所在包
 类方法
 同包方法