Java Code Examples for org.springframework.util.MimeTypeUtils#parseMimeType()

The following examples show how to use org.springframework.util.MimeTypeUtils#parseMimeType() . 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: RSocketClientToServerITest.java    From spring-rsocket-demo with GNU General Public License v3.0 6 votes vote down vote up
@BeforeAll
public static void setupOnce(@Autowired RSocketRequester.Builder builder,
                             @LocalRSocketServerPort Integer port,
                             @Autowired RSocketStrategies strategies) {

    SocketAcceptor responder = RSocketMessageHandler.responder(strategies, new ClientHandler());
    credentials = new UsernamePasswordMetadata("user", "pass");
    mimeType = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());

    requester = builder
            .setupRoute("shell-client")
            .setupData(UUID.randomUUID().toString())
            .setupMetadata(credentials, mimeType)
            .rsocketStrategies(b ->
                    b.encoder(new SimpleAuthenticationEncoder()))
            .rsocketConnector(connector -> connector.acceptor(responder))
            .connectTcp("localhost", port)
            .block();
}
 
Example 2
Source File: MessageConverterDelegateSerde.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 6 votes vote down vote up
private static MimeType resolveMimeType(Map<String, ?> configs) {
	if (configs.containsKey(MessageHeaders.CONTENT_TYPE)) {
		String contentType = (String) configs.get(MessageHeaders.CONTENT_TYPE);
		if (DEFAULT_AVRO_MIME_TYPE.equals(MimeTypeUtils.parseMimeType(contentType))) {
			return DEFAULT_AVRO_MIME_TYPE;
		}
		else if (contentType.contains("avro")) {
			return MimeTypeUtils.parseMimeType("application/avro");
		}
		else {
			return new MimeType("application", "json", StandardCharsets.UTF_8);
		}
	}
	else {
		return new MimeType("application", "json", StandardCharsets.UTF_8);
	}
}
 
Example 3
Source File: FileUploadApiController.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
@PostMapping("/file/upload")
public ResponseEntity<String> uploadFile(@RequestParam(required = false, value = "resizeImage", defaultValue = "false") Boolean resizeImage,
                                         @RequestBody UploadBase64FileModification upload) {

    try {
        final var mimeType = MimeTypeUtils.parseMimeType(upload.getType());
        if (MIME_TYPE_IMAGE_SVG.equalsTypeAndSubtype(mimeType)) {
            upload = rasterizeSVG(upload, resizeImage);
        } else if (Boolean.TRUE.equals(resizeImage)) {
            upload = resize(upload, mimeType);
        }
        return ResponseEntity.ok(fileUploadManager.insertFile(upload));
    } catch (Exception e) {
        log.error("error while uploading image", e);
        return ResponseEntity.badRequest().build();
    }
}
 
Example 4
Source File: WebFluxConfigurationSupportTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void viewResolutionResultHandler() throws Exception {
	ApplicationContext context = loadConfig(CustomViewResolverConfig.class);

	String name = "viewResolutionResultHandler";
	ViewResolutionResultHandler handler = context.getBean(name, ViewResolutionResultHandler.class);
	assertNotNull(handler);

	assertEquals(Ordered.LOWEST_PRECEDENCE, handler.getOrder());

	List<ViewResolver> resolvers = handler.getViewResolvers();
	assertEquals(1, resolvers.size());
	assertEquals(FreeMarkerViewResolver.class, resolvers.get(0).getClass());

	List<View> views = handler.getDefaultViews();
	assertEquals(1, views.size());

	MimeType type = MimeTypeUtils.parseMimeType("application/json;charset=UTF-8");
	assertEquals(type, views.get(0).getSupportedMediaTypes().get(0));
}
 
Example 5
Source File: RSocketClientToSecuredServerITest.java    From spring-rsocket-demo with GNU General Public License v3.0 6 votes vote down vote up
@BeforeAll
public static void setupOnce(@Autowired RSocketRequester.Builder builder,
                             @LocalRSocketServerPort Integer port,
                             @Autowired RSocketStrategies strategies) {

    SocketAcceptor responder = RSocketMessageHandler.responder(strategies, new ClientHandler());
    mimeType = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());

    // *******  The user 'test' is NOT in the required 'USER' role! **********
    credentials = new UsernamePasswordMetadata("test", "pass");

    requester = builder
            .setupRoute("shell-client")
            .setupData(UUID.randomUUID().toString())
            .setupMetadata(credentials, mimeType)
            .rsocketStrategies(b ->
                    b.encoder(new SimpleAuthenticationEncoder()))

            .rsocketConnector(connector -> connector.acceptor(responder))
            .connectTcp("localhost", port)
            .block();
}
 
Example 6
Source File: WebFluxConfigurationSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void viewResolutionResultHandler() throws Exception {
	ApplicationContext context = loadConfig(CustomViewResolverConfig.class);

	String name = "viewResolutionResultHandler";
	ViewResolutionResultHandler handler = context.getBean(name, ViewResolutionResultHandler.class);
	assertNotNull(handler);

	assertEquals(Ordered.LOWEST_PRECEDENCE, handler.getOrder());

	List<ViewResolver> resolvers = handler.getViewResolvers();
	assertEquals(1, resolvers.size());
	assertEquals(FreeMarkerViewResolver.class, resolvers.get(0).getClass());

	List<View> views = handler.getDefaultViews();
	assertEquals(1, views.size());

	MimeType type = MimeTypeUtils.parseMimeType("application/json");
	assertEquals(type, views.get(0).getSupportedMediaTypes().get(0));
}
 
Example 7
Source File: PayloadMethodArgumentResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Return the mime type for the content. By default this method checks the
 * {@link MessageHeaders#CONTENT_TYPE} header expecting to find a
 * {@link MimeType} value or a String to parse to a {@link MimeType}.
 * @param message the input message
 */
@Nullable
protected MimeType getMimeType(Message<?> message) {
	Object headerValue = message.getHeaders().get(MessageHeaders.CONTENT_TYPE);
	if (headerValue == null) {
		return null;
	}
	else if (headerValue instanceof String) {
		return MimeTypeUtils.parseMimeType((String) headerValue);
	}
	else if (headerValue instanceof MimeType) {
		return (MimeType) headerValue;
	}
	else {
		throw new IllegalArgumentException("Unexpected MimeType value: " + headerValue);
	}
}
 
Example 8
Source File: StringDecoderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void decodeMultibyteCharacterUtf16() {
	String u = "ü";
	String e = "é";
	String o = "ø";
	String s = String.format("%s\n%s\n%s", u, e, o);
	Flux<DataBuffer> source = toDataBuffers(s, 2, UTF_16BE);
	MimeType mimeType = MimeTypeUtils.parseMimeType("text/plain;charset=utf-16be");

	testDecode(source, TYPE, step -> step.expectNext(u, e, o).verifyComplete(), mimeType, null);
}
 
Example 9
Source File: RSocketClientDeniedConnectionToSecuredServerITest.java    From spring-rsocket-demo with GNU General Public License v3.0 5 votes vote down vote up
@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 10
Source File: FileResourceUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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 11
Source File: StompHeaderAccessor.java    From spring-analysis-note with MIT License 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) || StompCommand.STOMP.equals(command)) {
		protectPasscode();
	}
}
 
Example 12
Source File: MessagingRSocket.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Wrap the {@link ConnectionSetupPayload} with a {@link Message} and
 * delegate to {@link #handle(Payload)} for handling.
 * @param payload the connection payload
 * @return completion handle for success or error
 */
public Mono<Void> handleConnectionSetupPayload(ConnectionSetupPayload payload) {
	if (StringUtils.hasText(payload.dataMimeType())) {
		this.dataMimeType = MimeTypeUtils.parseMimeType(payload.dataMimeType());
	}
	// frameDecoder does not apply to connectionSetupPayload
	// so retain here since handle expects it..
	payload.retain();
	return handle(payload);
}
 
Example 13
Source File: StringDecoderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void decodeMultibyteCharacterUtf16() {
	String u = "ü";
	String e = "é";
	String o = "ø";
	String s = String.format("%s\n%s\n%s", u, e, o);
	Flux<DataBuffer> source = toDataBuffers(s, 2, UTF_16BE);
	MimeType mimeType = MimeTypeUtils.parseMimeType("text/plain;charset=utf-16be");

	testDecode(source, TYPE, step -> step
			.expectNext(u, e, o)
			.verifyComplete(), mimeType, null);
}
 
Example 14
Source File: CompressionCustomizer.java    From spring-boot-rsocket with Apache License 2.0 5 votes vote down vote up
private CompressionPredicate getMimeTypesPredicate(String[] mimeTypes) {
	if (ObjectUtils.isEmpty(mimeTypes)) {
		return ALWAYS_COMPRESS;
	}
	return (request, response) -> {
		String contentType = response.responseHeaders()
				.get(HttpHeaderNames.CONTENT_TYPE);
		if (StringUtils.isEmpty(contentType)) {
			return false;
		}
		MimeType contentMimeType = MimeTypeUtils.parseMimeType(contentType);
		return Arrays.stream(mimeTypes).map(MimeTypeUtils::parseMimeType)
				.anyMatch((candidate) -> candidate.isCompatibleWith(contentMimeType));
	};
}
 
Example 15
Source File: AppConfigService.java    From haven-platform with 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 16
Source File: StompHeaders.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Return the content-type header value.
 */
@Nullable
public MimeType getContentType() {
	String value = getFirst(CONTENT_TYPE);
	return (StringUtils.hasLength(value) ? MimeTypeUtils.parseMimeType(value) : null);
}
 
Example 17
Source File: MimeTypeDeserializer.java    From haven-platform with Apache License 2.0 4 votes vote down vote up
@Override
public MimeType deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    String mimeString = p.readValueAs(String.class);
    return MimeTypeUtils.parseMimeType(mimeString);
}
 
Example 18
Source File: StompHeaders.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Return the content-type header value.
 */
public MimeType getContentType() {
	String value = getFirst(CONTENT_TYPE);
	return (StringUtils.hasLength(value) ? MimeTypeUtils.parseMimeType(value) : null);
}
 
Example 19
Source File: MediaType.java    From swagger-brake with Apache License 2.0 4 votes vote down vote up
public MediaType(String mediaType) {
    this.mediaType = MimeTypeUtils.parseMimeType(mediaType);
}
 
Example 20
Source File: StompHeaders.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Return the content-type header value.
 */
@Nullable
public MimeType getContentType() {
	String value = getFirst(CONTENT_TYPE);
	return (StringUtils.hasLength(value) ? MimeTypeUtils.parseMimeType(value) : null);
}