Java Code Examples for org.springframework.http.MediaType#TEXT_PLAIN

The following examples show how to use org.springframework.http.MediaType#TEXT_PLAIN . 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: AttachmentApiController.java    From onboard with Apache License 2.0 7 votes vote down vote up
private MediaType getContentType(String contentType) {
    if (contentType.equalsIgnoreCase(MediaType.IMAGE_GIF_VALUE)) {
        return MediaType.IMAGE_GIF;
    } else if (contentType.equalsIgnoreCase(MediaType.IMAGE_PNG_VALUE)) {
        return MediaType.IMAGE_PNG;
    } else if (contentType.equalsIgnoreCase(MediaType.IMAGE_JPEG_VALUE)) {
        return MediaType.IMAGE_JPEG;
    } else if (contentType.equalsIgnoreCase(MediaType.TEXT_PLAIN_VALUE)) {
        return MediaType.TEXT_PLAIN;
    } else if (contentType.equalsIgnoreCase(MediaType.TEXT_XML_VALUE)) {
        return MediaType.TEXT_XML;
    } else if (contentType.equalsIgnoreCase(MediaType.TEXT_HTML_VALUE)) {
        return MediaType.TEXT_HTML;
    }
    return MediaType.APPLICATION_OCTET_STREAM;
}
 
Example 2
Source File: DefaultClientResponseTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void header() {
	HttpHeaders httpHeaders = new HttpHeaders();
	long contentLength = 42L;
	httpHeaders.setContentLength(contentLength);
	MediaType contentType = MediaType.TEXT_PLAIN;
	httpHeaders.setContentType(contentType);
	InetSocketAddress host = InetSocketAddress.createUnresolved("localhost", 80);
	httpHeaders.setHost(host);
	List<HttpRange> range = Collections.singletonList(HttpRange.createByteRange(0, 42));
	httpHeaders.setRange(range);

	when(mockResponse.getHeaders()).thenReturn(httpHeaders);

	ClientResponse.Headers headers = defaultClientResponse.headers();
	assertEquals(OptionalLong.of(contentLength), headers.contentLength());
	assertEquals(Optional.of(contentType), headers.contentType());
	assertEquals(httpHeaders, headers.asHttpHeaders());
}
 
Example 3
Source File: DefaultClientResponseTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void header() {
	HttpHeaders httpHeaders = new HttpHeaders();
	long contentLength = 42L;
	httpHeaders.setContentLength(contentLength);
	MediaType contentType = MediaType.TEXT_PLAIN;
	httpHeaders.setContentType(contentType);
	InetSocketAddress host = InetSocketAddress.createUnresolved("localhost", 80);
	httpHeaders.setHost(host);
	List<HttpRange> range = Collections.singletonList(HttpRange.createByteRange(0, 42));
	httpHeaders.setRange(range);

	given(mockResponse.getHeaders()).willReturn(httpHeaders);

	ClientResponse.Headers headers = defaultClientResponse.headers();
	assertEquals(OptionalLong.of(contentLength), headers.contentLength());
	assertEquals(Optional.of(contentType), headers.contentType());
	assertEquals(httpHeaders, headers.asHttpHeaders());
}
 
Example 4
Source File: HttpMessageConverterExtractorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-13592
@SuppressWarnings("unchecked")
public void converterThrowsIOException() throws IOException {
	HttpMessageConverter<String> converter = mock(HttpMessageConverter.class);
	HttpHeaders responseHeaders = new HttpHeaders();
	MediaType contentType = MediaType.TEXT_PLAIN;
	responseHeaders.setContentType(contentType);
	extractor = new HttpMessageConverterExtractor<>(String.class, createConverterList(converter));
	given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream("Foobar".getBytes()));
	given(converter.canRead(String.class, contentType)).willReturn(true);
	given(converter.read(eq(String.class), any(HttpInputMessage.class))).willThrow(IOException.class);
	exception.expect(RestClientException.class);
	exception.expectMessage("Error while extracting response for type " +
			"[class java.lang.String] and content type [text/plain]");
	exception.expectCause(Matchers.instanceOf(IOException.class));

	extractor.extractData(response);
}
 
Example 5
Source File: HttpMessageConverterExtractorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void generics() throws IOException {
	GenericHttpMessageConverter<String> converter = mock(GenericHttpMessageConverter.class);
	List<HttpMessageConverter<?>> converters = createConverterList(converter);
	HttpHeaders responseHeaders = new HttpHeaders();
	MediaType contentType = MediaType.TEXT_PLAIN;
	responseHeaders.setContentType(contentType);
	String expected = "Foo";
	ParameterizedTypeReference<List<String>> reference = new ParameterizedTypeReference<List<String>>() {};
	Type type = reference.getType();
	extractor = new HttpMessageConverterExtractor<List<String>>(type, converters);
	given(response.getStatusCode()).willReturn(HttpStatus.OK);
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream(expected.getBytes()));
	given(converter.canRead(type, null, contentType)).willReturn(true);
	given(converter.read(eq(type), eq(null), any(HttpInputMessage.class))).willReturn(expected);

	Object result = extractor.extractData(response);

	assertEquals(expected, result);
}
 
Example 6
Source File: RestTemplateTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // SPR-15066
public void requestInterceptorCanAddExistingHeaderValueWithBody() throws Exception {
	ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {
		request.getHeaders().add("MyHeader", "MyInterceptorValue");
		return execution.execute(request, body);
	};
	template.setInterceptors(Collections.singletonList(interceptor));

	MediaType contentType = MediaType.TEXT_PLAIN;
	given(converter.canWrite(String.class, contentType)).willReturn(true);
	HttpHeaders requestHeaders = new HttpHeaders();
	mockSentRequest(POST, "https://example.com", requestHeaders);
	mockResponseStatus(HttpStatus.OK);

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.setContentType(contentType);
	entityHeaders.add("MyHeader", "MyEntityValue");
	HttpEntity<String> entity = new HttpEntity<>("Hello World", entityHeaders);
	template.exchange("https://example.com", POST, entity, Void.class);
	assertThat(requestHeaders.get("MyHeader"), contains("MyEntityValue", "MyInterceptorValue"));

	verify(response).close();
}
 
Example 7
Source File: HttpEntityMethodProcessorMockTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test(expected = HttpMediaTypeNotAcceptableException.class)
public void handleReturnValueNotAcceptableProduces() throws Exception {
	String body = "Foo";
	ResponseEntity<String> returnValue = new ResponseEntity<String>(body, HttpStatus.OK);

	MediaType accepted = MediaType.TEXT_PLAIN;
	servletRequest.addHeader("Accept", accepted.toString());

	given(messageConverter.canWrite(String.class, null)).willReturn(true);
	given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
	given(messageConverter.canWrite(String.class, accepted)).willReturn(false);

	processor.handleReturnValue(returnValue, returnTypeResponseEntityProduces, mavContainer, webRequest);

	fail("Expected exception");
}
 
Example 8
Source File: HttpMessageConverterExtractorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test(expected = RestClientException.class)
@SuppressWarnings("unchecked")
public void cannotRead() throws IOException {
	HttpMessageConverter<String> converter = mock(HttpMessageConverter.class);
	List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
	converters.add(converter);
	HttpHeaders responseHeaders = new HttpHeaders();
	MediaType contentType = MediaType.TEXT_PLAIN;
	responseHeaders.setContentType(contentType);
	extractor = new HttpMessageConverterExtractor<String>(String.class, converters);
	given(response.getStatusCode()).willReturn(HttpStatus.OK);
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream("Foobar".getBytes()));
	given(converter.canRead(String.class, contentType)).willReturn(false);

	extractor.extractData(response);
}
 
Example 9
Source File: HttpMessageConverterExtractorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void normal() throws IOException {
	HttpMessageConverter<String> converter = mock(HttpMessageConverter.class);
	HttpHeaders responseHeaders = new HttpHeaders();
	MediaType contentType = MediaType.TEXT_PLAIN;
	responseHeaders.setContentType(contentType);
	String expected = "Foo";
	extractor = new HttpMessageConverterExtractor<>(String.class, createConverterList(converter));
	given(response.getRawStatusCode()).willReturn(HttpStatus.OK.value());
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream(expected.getBytes()));
	given(converter.canRead(String.class, contentType)).willReturn(true);
	given(converter.read(eq(String.class), any(HttpInputMessage.class))).willReturn(expected);

	Object result = extractor.extractData(response);
	assertEquals(expected, result);
}
 
Example 10
Source File: ObjectToStringHttpMessageConverter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * A constructor accepting a {@code ConversionService} as well as a default charset.
 * @param conversionService the conversion service
 * @param defaultCharset the default charset
 */
public ObjectToStringHttpMessageConverter(ConversionService conversionService, Charset defaultCharset) {
	super(defaultCharset, MediaType.TEXT_PLAIN);

	Assert.notNull(conversionService, "ConversionService is required");
	this.conversionService = conversionService;
	this.stringHttpMessageConverter = new StringHttpMessageConverter(defaultCharset);
}
 
Example 11
Source File: RequestResponseBodyAdviceChainTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setup() {
	this.body = "body";
	this.contentType = MediaType.TEXT_PLAIN;
	this.converterType = StringHttpMessageConverter.class;
	this.paramType = new MethodParameter(ClassUtils.getMethod(this.getClass(), "handle", String.class), 0);
	this.returnType = new MethodParameter(ClassUtils.getMethod(this.getClass(), "handle", String.class), -1);
	this.request = new ServletServerHttpRequest(new MockHttpServletRequest());
	this.response = new ServletServerHttpResponse(new MockHttpServletResponse());
}
 
Example 12
Source File: RequestResponseBodyMethodProcessorMockTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void handleReturnValue() throws Exception {
	MediaType accepted = MediaType.TEXT_PLAIN;
	servletRequest.addHeader("Accept", accepted.toString());

	String body = "Foo";
	given(stringMessageConverter.canWrite(String.class, null)).willReturn(true);
	given(stringMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
	given(stringMessageConverter.canWrite(String.class, accepted)).willReturn(true);

	processor.handleReturnValue(body, returnTypeString, mavContainer, webRequest);

	assertTrue("The requestHandled flag wasn't set", mavContainer.isRequestHandled());
	verify(stringMessageConverter).write(eq(body), eq(accepted), isA(HttpOutputMessage.class));
}
 
Example 13
Source File: RequestResponseBodyMethodProcessorMockTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test(expected = HttpMediaTypeNotAcceptableException.class)
public void handleReturnValueNotAcceptableProduces() throws Exception {
	MediaType accepted = MediaType.TEXT_PLAIN;
	servletRequest.addHeader("Accept", accepted.toString());

	given(messageConverter.canWrite(String.class, null)).willReturn(true);
	given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
	given(messageConverter.canWrite(String.class, accepted)).willReturn(false);

	processor.handleReturnValue("Foo", returnTypeStringProduces, mavContainer, webRequest);
}
 
Example 14
Source File: RegistryAPI.java    From openvsx with Eclipse Public License 2.0 5 votes vote down vote up
private MediaType getFileType(String fileName) {
    if (fileName.endsWith(".vsix")) {
        return MediaType.APPLICATION_OCTET_STREAM;
    }
    var contentType = URLConnection.guessContentTypeFromName(fileName);
    if (contentType != null) {
        return MediaType.parseMediaType(contentType);
    }
    return MediaType.TEXT_PLAIN;
}
 
Example 15
Source File: RequestResponseBodyMethodProcessorMockTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test(expected = HttpMediaTypeNotAcceptableException.class)
public void handleReturnValueNotAcceptableProduces() throws Exception {
	MediaType accepted = MediaType.TEXT_PLAIN;
	servletRequest.addHeader("Accept", accepted.toString());

	given(stringMessageConverter.canWrite(String.class, null)).willReturn(true);
	given(stringMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
	given(stringMessageConverter.canWrite(String.class, accepted)).willReturn(false);

	processor.handleReturnValue("Foo", returnTypeStringProduces, mavContainer, webRequest);
}
 
Example 16
Source File: RequestResponseBodyMethodProcessorMockTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test(expected = HttpMediaTypeNotSupportedException.class)
public void resolveArgumentCannotRead() throws Exception {
	MediaType contentType = MediaType.TEXT_PLAIN;
	servletRequest.addHeader("Content-Type", contentType.toString());
	servletRequest.setContent("payload".getBytes(StandardCharsets.UTF_8));

	given(stringMessageConverter.canRead(String.class, contentType)).willReturn(false);

	processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null);
}
 
Example 17
Source File: ProtobufHttpMessageConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Construct a new instance with an {@link ExtensionRegistryInitializer}
 * that allows the registration of message extensions.
 */
public ProtobufHttpMessageConverter(ExtensionRegistryInitializer registryInitializer) {
	super(PROTOBUF, MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML);
	if (registryInitializer != null) {
		registryInitializer.initializeExtensionRegistry(this.extensionRegistry);
	}
}
 
Example 18
Source File: RequestResponseBodyMethodProcessorMockTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void handleReturnValue() throws Exception {
	MediaType accepted = MediaType.TEXT_PLAIN;
	servletRequest.addHeader("Accept", accepted.toString());

	String body = "Foo";
	given(messageConverter.canWrite(String.class, null)).willReturn(true);
	given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
	given(messageConverter.canWrite(String.class, accepted)).willReturn(true);

	processor.handleReturnValue(body, returnTypeString, mavContainer, webRequest);

	assertTrue("The requestHandled flag wasn't set", mavContainer.isRequestHandled());
	verify(messageConverter).write(eq(body), eq(accepted), isA(HttpOutputMessage.class));
}
 
Example 19
Source File: RequestResponseBodyAdviceChainTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void setup() {
	this.body = "body";
	this.contentType = MediaType.TEXT_PLAIN;
	this.converterType = StringHttpMessageConverter.class;
	this.paramType = new MethodParameter(ClassUtils.getMethod(this.getClass(), "handle", String.class), 0);
	this.returnType = new MethodParameter(ClassUtils.getMethod(this.getClass(), "handle", String.class), -1);
	this.request = new ServletServerHttpRequest(new MockHttpServletRequest());
	this.response = new ServletServerHttpResponse(new MockHttpServletResponse());
}
 
Example 20
Source File: VSCodeAdapter.java    From openvsx with Eclipse Public License 2.0 5 votes vote down vote up
private MediaType getFileType(String fileName) {
    if (fileName.endsWith(".vsix")) {
        return MediaType.APPLICATION_OCTET_STREAM;
    }
    var contentType = URLConnection.guessContentTypeFromName(fileName);
    if (contentType != null) {
        return MediaType.parseMediaType(contentType);
    }
    return MediaType.TEXT_PLAIN;
}