Java Code Examples for org.springframework.util.MimeTypeUtils

The following examples show how to use org.springframework.util.MimeTypeUtils. 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: java-technology-stack   Source File: WebSocketStompClientTests.java    License: MIT License 6 votes vote down vote up
@Test
public void sendWebSocketBinary() throws Exception {
	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND);
	accessor.setDestination("/b");
	accessor.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM);
	byte[] payload = "payload".getBytes(StandardCharsets.UTF_8);

	getTcpConnection().send(MessageBuilder.createMessage(payload, accessor.getMessageHeaders()));

	ArgumentCaptor<BinaryMessage> binaryMessageCaptor = ArgumentCaptor.forClass(BinaryMessage.class);
	verify(this.webSocketSession).sendMessage(binaryMessageCaptor.capture());
	BinaryMessage binaryMessage = binaryMessageCaptor.getValue();
	assertNotNull(binaryMessage);
	assertEquals("SEND\ndestination:/b\ncontent-type:application/octet-stream\ncontent-length:7\n\npayload\0",
			new String(binaryMessage.getPayload().array(), StandardCharsets.UTF_8));
}
 
Example 2
@Override
public MessageBuilder<?> createOutputMessageBuilder(Message<?> inputMessage, Object computedScore) {

	Message<?> annotatedInput = inputMessage;

	List<Body> bodies = (List<Body>) computedScore;

	if (this.poseProperties.isDrawPoses()) {
		try {
			byte[] annotatedImage = drawPoses((byte[]) inputMessage.getPayload(), bodies);
			annotatedInput = MessageBuilder.withPayload(annotatedImage)
					.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE)
					.build();
		}
		catch (IOException e) {
			logger.error("Failed to draw the poses", e);
		}
	}

	return super.createOutputMessageBuilder(annotatedInput, toJson(bodies));
}
 
Example 3
Source Project: spring-cloud-stream   Source File: ContentTypeTckTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void typelessToPojoInboundContentTypeBinding() {
	ApplicationContext context = new SpringApplicationBuilder(
			TypelessToPojoStreamListener.class).web(WebApplicationType.NONE).run(
					"--spring.cloud.stream.bindings.input.contentType=text/plain",
					"--spring.jmx.enabled=false");
	InputDestination source = context.getBean(InputDestination.class);
	OutputDestination target = context.getBean(OutputDestination.class);
	String jsonPayload = "{\"name\":\"oleg\"}";
	source.send(new GenericMessage<>(jsonPayload.getBytes()));
	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 4
Source Project: java-technology-stack   Source File: CharSequenceEncoderTests.java    License: MIT License 6 votes vote down vote up
@Override
public void canEncode() throws Exception {
	assertTrue(this.encoder.canEncode(ResolvableType.forClass(String.class),
			MimeTypeUtils.TEXT_PLAIN));
	assertTrue(this.encoder.canEncode(ResolvableType.forClass(StringBuilder.class),
			MimeTypeUtils.TEXT_PLAIN));
	assertTrue(this.encoder.canEncode(ResolvableType.forClass(StringBuffer.class),
			MimeTypeUtils.TEXT_PLAIN));
	assertFalse(this.encoder.canEncode(ResolvableType.forClass(Integer.class),
			MimeTypeUtils.TEXT_PLAIN));
	assertFalse(this.encoder.canEncode(ResolvableType.forClass(String.class),
			MimeTypeUtils.APPLICATION_JSON));

	// SPR-15464
	assertFalse(this.encoder.canEncode(ResolvableType.NONE, null));
}
 
Example 5
Source Project: spring-analysis-note   Source File: ResourceRegionEncoderTests.java    License: MIT License 6 votes vote down vote up
@Test // gh-22107
public void cancelWithoutDemandForMultipleResourceRegions() {
	Resource resource = new ClassPathResource("ResourceRegionEncoderTests.txt", getClass());
	Flux<ResourceRegion> regions = Flux.just(
			new ResourceRegion(resource, 0, 6),
			new ResourceRegion(resource, 7, 9),
			new ResourceRegion(resource, 17, 4),
			new ResourceRegion(resource, 22, 17)
	);
	String boundary = MimeTypeUtils.generateMultipartBoundaryString();

	Flux<DataBuffer> flux = this.encoder.encode(regions, this.bufferFactory,
			ResolvableType.forClass(ResourceRegion.class),
			MimeType.valueOf("text/plain"),
			Collections.singletonMap(ResourceRegionEncoder.BOUNDARY_STRING_HINT, boundary)
	);

	ZeroDemandSubscriber subscriber = new ZeroDemandSubscriber();
	flux.subscribe(subscriber);
	subscriber.cancel();
}
 
Example 6
Source Project: spring-cloud-stream   Source File: ContentTypeTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSendJsonAsString() throws Exception {
	try (ConfigurableApplicationContext context = SpringApplication.run(
			SourceApplication.class, "--server.port=0",
			"--spring.jmx.enabled=false")) {
		MessageCollector collector = context.getBean(MessageCollector.class);
		Source source = context.getBean(Source.class);
		User user = new User("Alice");
		String json = this.mapper.writeValueAsString(user);
		source.output().send(MessageBuilder.withPayload(user).build());
		Message<String> message = (Message<String>) collector
				.forChannel(source.output()).poll(1, TimeUnit.SECONDS);
		assertThat(
				message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)
						.includes(MimeTypeUtils.APPLICATION_JSON));
		assertThat(json).isEqualTo(message.getPayload());
	}
}
 
Example 7
Source Project: spring-cloud-stream   Source File: RoutingFunctionTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRoutingViaExplicitEnablingAndDefinitionHeader() {
	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestChannelBinderConfiguration.getCompleteConfiguration(
					RoutingFunctionConfiguration.class))
							.web(WebApplicationType.NONE)
							.run("--spring.jmx.enabled=false",
								"--spring.cloud.stream.function.routing.enabled=true")) {

		InputDestination inputDestination = context.getBean(InputDestination.class);
		OutputDestination outputDestination = context
				.getBean(OutputDestination.class);

		Message<byte[]> inputMessage = MessageBuilder
				.withPayload("Hello".getBytes())
				.setHeader(FunctionProperties.PREFIX + ".definition", "echo")
				.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN)
				.build();
		inputDestination.send(inputMessage);

		Message<byte[]> outputMessage = outputDestination.receive();
		assertThat(outputMessage.getPayload()).isEqualTo("Hello".getBytes());
	}
}
 
Example 8
@Test
public void toMessageWithMutableMessageHeaders() {
	SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
	accessor.setHeader("foo", "bar");
	accessor.setNativeHeader("fooNative", "barNative");
	accessor.setLeaveMutable(true);

	MessageHeaders headers = accessor.getMessageHeaders();
	Message<?> message = this.converter.toMessage("ABC", headers);

	assertSame(headers, message.getHeaders());
	assertNull(message.getHeaders().getId());
	assertNull(message.getHeaders().getTimestamp());
	assertEquals(MimeTypeUtils.TEXT_PLAIN, message.getHeaders().get(MessageHeaders.CONTENT_TYPE));
}
 
Example 9
Source Project: spring4-understanding   Source File: StompHeaderAccessor.java    License: Apache License 2.0 5 votes vote down vote up
void updateSimpMessageHeadersFromStompHeaders() {
	if (getNativeHeaders() == null) {
		return;
	}
	String value = getFirstNativeHeader(STOMP_DESTINATION_HEADER);
	if (value != null) {
		super.setDestination(value);
	}
	value = getFirstNativeHeader(STOMP_CONTENT_TYPE_HEADER);
	if (value != null) {
		super.setContentType(MimeTypeUtils.parseMimeType(value));
	}
	StompCommand command = getCommand();
	if (StompCommand.MESSAGE.equals(command)) {
		value = getFirstNativeHeader(STOMP_SUBSCRIPTION_HEADER);
		if (value != null) {
			super.setSubscriptionId(value);
		}
	}
	else if (StompCommand.SUBSCRIBE.equals(command) || StompCommand.UNSUBSCRIBE.equals(command)) {
		value = getFirstNativeHeader(STOMP_ID_HEADER);
		if (value != null) {
			super.setSubscriptionId(value);
		}
	}
	else if (StompCommand.CONNECT.equals(command)) {
		protectPasscode();
	}
}
 
Example 10
Source Project: servicecomb-toolkit   Source File: StyleController.java    License: Apache License 2.0 5 votes vote down vote up
@PostMapping(consumes = MimeTypeUtils.TEXT_PLAIN_VALUE, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
@ResponseStatus(value = HttpStatus.OK)
public Map<String, Object> validateOpenAPI(@RequestBody String yaml) {

  ImportError importError = doValidate(yaml);
  Map<String, Object> json = new HashMap<>();
  
  json.put("acknowleged", true);
  json.put("data", importError);
  
  return json;
}
 
Example 11
@Test
public void handleMessageToClientWithBinaryWebSocketMessage() {

	StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.MESSAGE);
	headers.setMessageId("mess0");
	headers.setSubscriptionId("sub0");
	headers.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM);
	headers.setDestination("/queue/foo");

	// Non-empty payload

	byte[] payload = new byte[1];
	Message<byte[]> message = MessageBuilder.createMessage(payload, headers.getMessageHeaders());
	this.protocolHandler.handleMessageToClient(this.session, message);

	assertEquals(1, this.session.getSentMessages().size());
	WebSocketMessage<?> webSocketMessage = this.session.getSentMessages().get(0);
	assertTrue(webSocketMessage instanceof BinaryMessage);

	// Empty payload

	payload = EMPTY_PAYLOAD;
	message = MessageBuilder.createMessage(payload, headers.getMessageHeaders());
	this.protocolHandler.handleMessageToClient(this.session, message);

	assertEquals(2, this.session.getSentMessages().size());
	webSocketMessage = this.session.getSentMessages().get(1);
	assertTrue(webSocketMessage instanceof TextMessage);
}
 
Example 12
@Test
public void resolve() {
	Map<String, Object> map = new HashMap<String, Object>();
	map.put(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON);
	MessageHeaders headers = new MessageHeaders(map);

	assertEquals(MimeTypeUtils.APPLICATION_JSON, this.resolver.resolve(headers));
}
 
Example 13
private MimeMessage makeEmail(TokenData data, _EmailTemplate template, boolean allowReply) throws IOException, MessagingException {
    List<_BridgeMessageContent> contents = Arrays.asList(
            new BridgeMessageContent(MimeTypeUtils.TEXT_PLAIN_VALUE),
            new BridgeMessageContent(MimeTypeUtils.TEXT_HTML_VALUE)
    );

    return makeEmail(data, template, contents, allowReply);
}
 
Example 14
Source Project: spring-analysis-note   Source File: MessageConverterTests.java    License: MIT License 5 votes vote down vote up
@Test
public void canConvertFromStrictContentTypeMatch() {
	this.converter = new TestMessageConverter(Arrays.asList(MimeTypeUtils.TEXT_PLAIN));
	this.converter.setStrictContentTypeMatch(true);

	Message<String> message = MessageBuilder.withPayload("ABC").build();
	assertFalse(this.converter.canConvertFrom(message, String.class));

	message = MessageBuilder.withPayload("ABC")
			.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN).build();
	assertTrue(this.converter.canConvertFrom(message, String.class));

}
 
Example 15
/**
 * Indicates whether the content type represented by the given string is a
 * valid, known content type.
 *
 * @param contentType the content type string.
 * @return true if the content is valid, false if not.
 */
public static boolean isValidContentType( String contentType )
{
    try
    {
        MimeTypeUtils.parseMimeType( contentType );
    }
    catch ( InvalidMimeTypeException ignored )
    {
        return false;
    }

    return true;
}
 
Example 16
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 17
@Override
protected Message<?> doConvert(Object payload, Map<String, Object> headers, MessagePostProcessor postProcessor) {
    String content;
    if (payload instanceof String) {
        content = (String) payload;
    } else {
        // if payload not as string, use objectMapper change it.
        try {
            content = objectMapper.writeValueAsString(payload);
        } catch (JsonProcessingException e) {
            log.info("convert payload to String failed. payload:{}", payload);
            throw new RuntimeException("convert to payload to String failed.", e);
        }
    }

    MessageBuilder<?> builder = MessageBuilder.withPayload(content);
    if (headers != null) {
        builder.copyHeaders(headers);
    }
    builder.setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN);

    Message<?> message = builder.build();
    if (postProcessor != null) {
        message = postProcessor.postProcessMessage(message);
    }
    return message;
}
 
Example 18
Source Project: consensusj   Source File: WebSocketConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
    // Workaround for issue 2445: https://github.com/spring-projects/spring-boot/issues/2445
    DefaultContentTypeResolver resolver = new DefaultContentTypeResolver();
    resolver.setDefaultMimeType(MimeTypeUtils.APPLICATION_JSON);
    MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
    converter.setObjectMapper(objectMapper);
    converter.setContentTypeResolver(resolver);
    messageConverters.add(converter);
    return false;
}
 
Example 19
Source Project: moon-api-gateway   Source File: InitializeInterceptorTest.java    License: MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
    request.addHeader("Content-Type", MimeTypeUtils.APPLICATION_JSON_VALUE);
    request.addHeader("apiKey", "5000-5000-5000-5000");
    request.setQueryString("version=2.2");

    interceptor.preHandler(request, response, null);
}
 
Example 20
protected MappingJackson2MessageConverter createJacksonConverter() {
	DefaultContentTypeResolver resolver = new DefaultContentTypeResolver();
	resolver.setDefaultMimeType(MimeTypeUtils.APPLICATION_JSON);
	MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
	converter.setContentTypeResolver(resolver);
	return converter;
}
 
Example 21
Source Project: spring-cloud-stream   Source File: ContentTypeTckTests.java    License: Apache License 2.0 5 votes vote down vote up
@StreamListener(Processor.INPUT)
@SendTo(Processor.OUTPUT)
public Message<String> echo(Message<Person> value) {
	return MessageBuilder.withPayload(value.getPayload().toString())
			.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN)
			.build();
}
 
Example 22
Source Project: spring-analysis-note   Source File: DefaultStompSessionTests.java    License: MIT License 5 votes vote down vote up
@Test
public void handleMessageFrameWithConversionException() {
	this.session.afterConnected(this.connection);
	assertTrue(this.session.isConnected());

	StompFrameHandler frameHandler = mock(StompFrameHandler.class);
	String destination = "/topic/foo";
	Subscription subscription = this.session.subscribe(destination, frameHandler);

	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.MESSAGE);
	accessor.setDestination(destination);
	accessor.setSubscriptionId(subscription.getSubscriptionId());
	accessor.setContentType(MimeTypeUtils.APPLICATION_JSON);
	accessor.setMessageId("1");
	accessor.setLeaveMutable(true);
	byte[] payload = "{'foo':'bar'}".getBytes(StandardCharsets.UTF_8);

	StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
	given(frameHandler.getPayloadType(stompHeaders)).willReturn(Map.class);

	this.session.handleMessage(MessageBuilder.createMessage(payload, accessor.getMessageHeaders()));

	verify(frameHandler).getPayloadType(stompHeaders);
	verifyNoMoreInteractions(frameHandler);

	verify(this.sessionHandler).handleException(same(this.session), same(StompCommand.MESSAGE),
			eq(stompHeaders), same(payload), any(MessageConversionException.class));
	verifyNoMoreInteractions(this.sessionHandler);
}
 
Example 23
protected MappingJackson2MessageConverter createJacksonConverter() {
	DefaultContentTypeResolver resolver = new DefaultContentTypeResolver();
	resolver.setDefaultMimeType(MimeTypeUtils.APPLICATION_JSON);
	MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
	converter.setContentTypeResolver(resolver);
	return converter;
}
 
Example 24
@Ignore
@Test
public void binaryResourceNoLabel() throws Exception {
	when(this.repository.findOne("foo", "default", null, false))
			.thenReturn(new Environment("foo", "default", "master"));
	when(this.resources.findOne("foo", "default", null, "foo.txt"))
			.thenReturn(new ClassPathResource("resource-controller/foo.txt"));
	this.mvc.perform(MockMvcRequestBuilders.get("/foo/default/foo.txt")
			.param("useDefaultLabel", "")
			.header(HttpHeaders.ACCEPT, MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE))
			.andExpect(MockMvcResultMatchers.status().isOk());
	verify(this.repository).findOne("foo", "default", null, false);
	verify(this.resources).findOne("foo", "default", null, "foo.txt");
}
 
Example 25
@Test // SPR-17220
public void emptyBodyWritten() {
	HttpMessageWriter<String> writer = getWriter(MimeTypeUtils.TEXT_PLAIN);
	writer.write(Mono.empty(), forClass(String.class), TEXT_PLAIN, this.response, NO_HINTS).block();
	StepVerifier.create(this.response.getBody()).expectComplete();
	assertEquals(0, this.response.getHeaders().getContentLength());
}
 
Example 26
@Before
public void setUp() {
	RSocketStrategies strategies = RSocketStrategies.builder()
			.decoder(StringDecoder.allMimeTypes())
			.encoder(CharSequenceEncoder.allMimeTypes())
			.build();
	this.rsocket = new TestRSocket();
	this.requester = RSocketRequester.wrap(this.rsocket, MimeTypeUtils.TEXT_PLAIN, strategies);
}
 
Example 27
Source Project: haven-platform   Source File: AppConfigService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 */
public void write(String mimeType, OutputStream os) throws IOException {
    Assert.hasText(mimeType, "MimeType string is null or empty.");
    Assert.notNull(os, "OutputStream is null or empty.");
    MimeType mimeTypeObj = MimeTypeUtils.parseMimeType(mimeType);
    if(MimeTypeUtils.APPLICATION_JSON.equals(mimeTypeObj)) {
        Assert.hasText(mimeType, "MimeType '" + mimeType + "' is not supported.");
    }
    AppConfigObject aco = new AppConfigObject();
    aco.setDate(LocalDateTime.now());
    aco.setVersion(VERSION);
    Map<String, Object> map = new HashMap<>();
    aco.setData(map);
    ConfigWriteContext ctx = ConfigWriteContext.builder()
      .mimeType(mimeTypeObj)
      .build();
    for(ConcurrentMap.Entry<String, ReConfigurableAdapter> cae : adapters.entrySet()) {
        ReConfigurableAdapter ca = cae.getValue();
        Object o = ca.getConfig(ctx);
        if(o == null) {
            continue;
        }
        String name = cae.getKey();
        map.put(name, o);
    }
    objectMapper.writeValue(os, aco);
}
 
Example 28
Source Project: hello-spring-cloud-alibaba   Source File: SenderService.java    License: MIT License 5 votes vote down vote up
public <T> void sendObject(T msg, String tag) throws Exception {
    Message message = MessageBuilder.withPayload(msg)
            .setHeader(MessageConst.PROPERTY_TAGS, tag)
            .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON)
            .build();
    source.output1().send(message);
}
 
Example 29
Source Project: java-technology-stack   Source File: MessageConverterTests.java    License: MIT License 5 votes vote down vote up
@Test
public void canConvertFromStrictContentTypeMatch() {
	this.converter = new TestMessageConverter(Arrays.asList(MimeTypeUtils.TEXT_PLAIN));
	this.converter.setStrictContentTypeMatch(true);

	Message<String> message = MessageBuilder.withPayload("ABC").build();
	assertFalse(this.converter.canConvertFrom(message, String.class));

	message = MessageBuilder.withPayload("ABC")
			.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN).build();
	assertTrue(this.converter.canConvertFrom(message, String.class));

}
 
Example 30
@Test(expected = MessageConversionException.class)
public void convertAndSendNoMatchingConverter() {

	MessageConverter converter = new CompositeMessageConverter(
			Arrays.<MessageConverter>asList(new MappingJackson2MessageConverter()));
	this.template.setMessageConverter(converter);

	this.headers.put(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_XML);
	this.template.convertAndSend("home", "payload", new MessageHeaders(this.headers));
}