org.springframework.util.MimeTypeUtils Java Examples
The following examples show how to use
org.springframework.util.MimeTypeUtils.
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: WebSocketStompClientTests.java From java-technology-stack with MIT License | 6 votes |
@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
Source File: ResourceRegionEncoderTests.java From spring-analysis-note with MIT License | 6 votes |
@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 #3
Source File: PoseEstimateOutputMessageBuilder.java From tensorflow with Apache License 2.0 | 6 votes |
@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 #4
Source File: ContentTypeTests.java From spring-cloud-stream with Apache License 2.0 | 6 votes |
@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 #5
Source File: CharSequenceEncoderTests.java From java-technology-stack with MIT License | 6 votes |
@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 #6
Source File: ContentTypeTckTests.java From spring-cloud-stream with Apache License 2.0 | 6 votes |
@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 #7
Source File: RoutingFunctionTests.java From spring-cloud-stream with Apache License 2.0 | 6 votes |
@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
Source File: WebSocketStompClient.java From spring-analysis-note with MIT License | 5 votes |
public WebSocketMessage<?> encode(Message<byte[]> message, Class<? extends WebSocketSession> sessionType) { StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); Assert.notNull(accessor, "No StompHeaderAccessor available"); byte[] payload = message.getPayload(); byte[] bytes = ENCODER.encode(accessor.getMessageHeaders(), payload); boolean useBinary = (payload.length > 0 && !(SockJsSession.class.isAssignableFrom(sessionType)) && MimeTypeUtils.APPLICATION_OCTET_STREAM.isCompatibleWith(accessor.getContentType())); return (useBinary ? new BinaryMessage(bytes) : new TextMessage(bytes)); }
Example #9
Source File: StompSubProtocolHandlerTests.java From spring-analysis-note with MIT License | 5 votes |
@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 #10
Source File: ReactiveSocketClient.java From spring-cloud-sockets with Apache License 2.0 | 5 votes |
private AbstractRemoteHandler handlerFor(Method method){ AbstractRemoteHandler handler = remoteHandlers.get(method); if(handler != null){ return handler; } synchronized (remoteHandlers){ ServiceMethodInfo serviceMethodInfo = new ServiceMethodInfo(method); Converter converter = converters.stream().filter(payloadConverter -> payloadConverter.accept(serviceMethodInfo.getMappingInfo().getMimeType())).findFirst().orElseThrow(IllegalStateException::new); Converter metadataConverter = converters.stream().filter(binaryConverter -> binaryConverter.accept(MimeTypeUtils.APPLICATION_JSON)).findFirst().orElseThrow(IllegalStateException::new); switch (serviceMethodInfo.getMappingInfo().getExchangeMode()){ case ONE_WAY: handler = new OneWayRemoteHandler(socket, serviceMethodInfo); remoteHandlers.put(method, handler); break; case REQUEST_ONE: handler = new RequestOneRemoteHandler(socket, serviceMethodInfo); remoteHandlers.put(method, handler); break; case REQUEST_MANY: handler = new RequestManyRemoteHandler(socket, serviceMethodInfo); remoteHandlers.put(method, handler); break; case REQUEST_STREAM: handler = new RequestStreamRemoteHandler(socket, serviceMethodInfo); remoteHandlers.put(method, handler); break; } handler.setPayloadConverter(converter); handler.setMetadataConverter(metadataConverter); } return handler; }
Example #11
Source File: HeaderAndBodyApplication.java From rocketmq-binder-demo with Apache License 2.0 | 5 votes |
@Override public void run(String... args) throws Exception { int count = 5; for (int index = 1; index <= count; index++) { source.output().send(MessageBuilder.withPayload("msg-" + index) .setHeader("index", index).build()); } source.output().send(MessageBuilder .withPayload(objectMapper.writeValueAsString(new Person(99, "Jim"))) .setHeader("index", 9999) .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON) .build()); }
Example #12
Source File: MediaType.java From spring-analysis-note with MIT License | 5 votes |
/** * Parse the comma-separated string into a list of {@code MediaType} objects. * <p>This method can be used to parse an Accept or Content-Type header. * @param mediaTypes the string to parse * @return the list of media types * @throws InvalidMediaTypeException if the media type value cannot be parsed */ public static List<MediaType> parseMediaTypes(@Nullable String mediaTypes) { if (!StringUtils.hasLength(mediaTypes)) { return Collections.emptyList(); } // Avoid using java.util.stream.Stream in hot paths List<String> tokenizedTypes = MimeTypeUtils.tokenize(mediaTypes); List<MediaType> result = new ArrayList<>(tokenizedTypes.size()); for (String type : tokenizedTypes) { result.add(parseMediaType(type)); } return result; }
Example #13
Source File: DefaultRSocketRequesterTests.java From spring-analysis-note with MIT License | 5 votes |
@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 #14
Source File: SenderService.java From spring-boot-demo with MIT License | 5 votes |
/** * 发送对象 * * @param msg * @param tag * @param <T> */ public <T> void sendObject(T msg, String tag) { Message message = MessageBuilder.withPayload(msg) .setHeader(RocketMQHeaders.TAGS, tag) .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON) .build(); source.output2().send(message); }
Example #15
Source File: ResourceRegionEncoderTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void shouldEncodeResourceRegionFileResource() throws Exception { ResourceRegion region = new ResourceRegion( new ClassPathResource("ResourceRegionEncoderTests.txt", getClass()), 0, 6); Flux<DataBuffer> result = this.encoder.encode(Mono.just(region), this.bufferFactory, ResolvableType.forClass(ResourceRegion.class), MimeTypeUtils.APPLICATION_OCTET_STREAM, Collections.emptyMap()); StepVerifier.create(result) .consumeNextWith(stringConsumer("Spring")) .expectComplete() .verify(); }
Example #16
Source File: MessageConverterTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void supportsMimeType() { Message<String> message = MessageBuilder.withPayload( "ABC").setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN).build(); assertEquals("success-from", this.converter.fromMessage(message, String.class)); }
Example #17
Source File: DefaultContentTypeResolverTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void resolveStringContentType() { Map<String, Object> map = new HashMap<String, Object>(); map.put(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON_VALUE); MessageHeaders headers = new MessageHeaders(map); assertEquals(MimeTypeUtils.APPLICATION_JSON, this.resolver.resolve(headers)); }
Example #18
Source File: EncoderHttpMessageWriterTests.java From java-technology-stack with MIT License | 5 votes |
@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 #19
Source File: StringMessageConverterTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void toMessage() { Map<String, Object> map = new HashMap<>(); map.put(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN); MessageHeaders headers = new MessageHeaders(map); Message<?> message = this.converter.toMessage("ABC", headers); assertEquals("ABC", new String(((byte[]) message.getPayload()))); }
Example #20
Source File: EncoderHttpMessageWriterTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void useNegotiatedMediaType() { HttpMessageWriter<String> writer = getWriter(MimeTypeUtils.ALL); writer.write(Mono.just("body"), forClass(String.class), TEXT_PLAIN, this.response, NO_HINTS); assertEquals(TEXT_PLAIN, response.getHeaders().getContentType()); assertEquals(TEXT_PLAIN, this.mediaTypeCaptor.getValue()); }
Example #21
Source File: RSocketClientDeniedConnectionToSecuredServerITest.java From spring-rsocket-demo with GNU General Public License v3.0 | 5 votes |
@BeforeAll public static void setupOnce(@Autowired RSocketRequester.Builder builder, @LocalRSocketServerPort Integer port, @Autowired RSocketStrategies strategies) { mimeType = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString()); reqbuilder = builder; theport = port; // ******* The user 'fake' is NOT in the user list! ********** credentials = new UsernamePasswordMetadata("fake", "pass"); }
Example #22
Source File: ContentTypeTckTests.java From spring-cloud-stream with Apache License 2.0 | 5 votes |
@Test public void byteArrayMessageToStringJsonMessageStreamListener() { ApplicationContext context = new SpringApplicationBuilder( ByteArrayMessageToStringJsonMessageStreamListener.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(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("{\"name\":\"bob\"}"); }
Example #23
Source File: ByteArrayEncoderTests.java From spring-analysis-note with MIT License | 5 votes |
@Override @Test public void canEncode() { assertTrue(this.encoder.canEncode(ResolvableType.forClass(byte[].class), MimeTypeUtils.TEXT_PLAIN)); assertFalse(this.encoder.canEncode(ResolvableType.forClass(Integer.class), MimeTypeUtils.TEXT_PLAIN)); assertTrue(this.encoder.canEncode(ResolvableType.forClass(byte[].class), MimeTypeUtils.APPLICATION_JSON)); // SPR-15464 assertFalse(this.encoder.canEncode(ResolvableType.NONE, null)); }
Example #24
Source File: MessageHeaderAccessorTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void getDetailedLogMessagePayload() { MessageHeaderAccessor accessor = new MessageHeaderAccessor(); accessor.setContentType(MimeTypeUtils.TEXT_PLAIN); String expected = "headers={contentType=text/plain} payload=p"; assertEquals(expected, accessor.getDetailedLogMessage("p")); assertEquals(expected, accessor.getDetailedLogMessage("p".getBytes(StandardCharsets.UTF_8))); assertEquals(expected, accessor.getDetailedLogMessage(new Object() { @Override public String toString() { return "p"; } })); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 80; i++) { sb.append("a"); } final String payload = sb.toString() + " > 80"; String actual = accessor.getDetailedLogMessage(payload); assertEquals("headers={contentType=text/plain} payload=" + sb + " > 80", actual); actual = accessor.getDetailedLogMessage(payload.getBytes(StandardCharsets.UTF_8)); assertEquals("headers={contentType=text/plain} payload=" + sb + " > 80", actual); actual = accessor.getDetailedLogMessage(new Object() { @Override public String toString() { return payload; } }); assertEquals("headers={contentType=text/plain} payload=" + sb + " > 80", actual); }
Example #25
Source File: ServerCodecConfigurerTests.java From spring-analysis-note with MIT License | 5 votes |
@SuppressWarnings("unchecked") private void assertStringDecoder(Decoder<?> decoder, boolean textOnly) { assertEquals(StringDecoder.class, decoder.getClass()); assertTrue(decoder.canDecode(forClass(String.class), MimeTypeUtils.TEXT_PLAIN)); assertEquals(!textOnly, decoder.canDecode(forClass(String.class), MediaType.TEXT_EVENT_STREAM)); Flux<String> flux = (Flux<String>) decoder.decode( Flux.just(new DefaultDataBufferFactory().wrap("line1\nline2".getBytes(StandardCharsets.UTF_8))), ResolvableType.forClass(String.class), MimeTypeUtils.TEXT_PLAIN, Collections.emptyMap()); assertEquals(Arrays.asList("line1", "line2"), flux.collectList().block(Duration.ZERO)); }
Example #26
Source File: MessageSendingTemplateTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@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)); }
Example #27
Source File: MessageConverterTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@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 #28
Source File: SenderService.java From hello-spring-cloud-alibaba with MIT License | 5 votes |
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 File: AppConfigService.java From haven-platform with Apache License 2.0 | 5 votes |
/** */ 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 #30
Source File: MessageConverterTests.java From java-technology-stack with MIT License | 5 votes |
@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)); }