Example usage for org.springframework.http HttpHeaders getContentType

List of usage examples for org.springframework.http HttpHeaders getContentType

Introduction

In this page you can find the example usage for org.springframework.http HttpHeaders getContentType.

Prototype

@Nullable
public MediaType getContentType() 

Source Link

Document

Return the MediaType media type of the body, as specified by the Content-Type header.

Usage

From source file:com.p5solutions.core.json.JsonHttpMessageConverter.java

/**
 * Deserialize./*  w ww .ja  va 2s. c  o  m*/
 * 
 * @param clazz
 *          the clazz
 * @param bindObject
 *          the bind object
 * @param inputMessage
 *          the input message
 * @return the object
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 */
@SuppressWarnings("unchecked")
protected Object deserialize(Class<?> clazz, Object bindObject, WebRequest webRequest, WebDataBinder binder,
        HttpInputMessage inputMessage) throws IOException {

    ///

    HttpHeaders headers = inputMessage.getHeaders();
    MediaType mediaType = headers.getContentType();
    Charset charset = mediaType.getCharSet();
    InputStream input = inputMessage.getBody();
    Object value = deserializer.deserialize((Class<Object>) clazz, bindObject, webRequest, binder, input,
            charset);

    return value;
}

From source file:org.terasoluna.gfw.functionaltest.app.download.DownloadTest.java

@Test
public void test01_01_fileDownload() throws IOException {
    ResponseEntity<byte[]> response = restTemplate.getForEntity(applicationContextUrl + "/download/1_1",
            byte[].class);
    ClassPathResource images = new ClassPathResource("/image/Duke.png");

    byte[] expected = StreamUtils.copyToByteArray(images.getInputStream());

    HttpHeaders headers = response.getHeaders();
    System.out.println("test01_01_fileDownload: X-Track=" + headers.getFirst("X-Track"));
    assertThat(headers.getFirst("Content-Disposition"), is("attachment; filename=Duke.png"));

    MediaType contentType = headers.getContentType();
    assertThat(contentType.getType(), is("image"));
    assertThat(contentType.getSubtype(), is("png"));

    assertThat(response.getBody(), is(expected));
}

From source file:org.terasoluna.gfw.functionaltest.app.download.DownloadTest.java

@Test
public void test01_02_fileDownload() {
    ResponseEntity<String> response = restTemplate.getForEntity(applicationContextUrl + "/download/1_2",
            String.class);

    HttpHeaders headers = response.getHeaders();
    System.out.println("test01_02_fileDownload: X-Track=" + headers.getFirst("X-Track"));

    assertThat(headers.getFirst("Content-Disposition"), is("attachment; filename=framework.txt"));

    MediaType contentType = headers.getContentType();
    assertThat(contentType.getType(), is("text"));
    assertThat(contentType.getSubtype(), is("plain"));
    assertThat(contentType.getParameter("charset"), equalToIgnoringCase("UTF-8"));

    assertThat(response.getBody(), is("Spring Framework"));

}

From source file:com.orange.cepheus.broker.RemoteRegistrations.java

/**
 * Try propagating the registerContext to a remote broker
 * @param registerContext the registerContext to send
 * @param localRegistrationId the local registrationId
 *///from   ww  w.  j  a v a  2 s. c o  m
public void registerContext(final RegisterContext registerContext, final String localRegistrationId) {

    // When no remote broker is define, don't do anything.
    final String remoteUrl = configuration.getRemoteUrl();
    if (remoteUrl == null || remoteUrl.isEmpty()) {
        return;
    }

    HttpHeaders httpHeaders = ngsiClient.getRequestHeaders(remoteUrl);
    logger.debug("=> registerContext to remote broker {} with Content-Type {}", remoteUrl,
            httpHeaders.getContentType());

    // If we already had a remote registration, reset its registerContext
    String previousRemoteRegistrationId = resetRemoteRegistration(localRegistrationId);
    // Update the registerContext with the previous remote registrationId if any
    registerContext.setRegistrationId(previousRemoteRegistrationId);

    configuration.addRemoteHeaders(httpHeaders);

    ngsiClient.registerContext(remoteUrl, httpHeaders, registerContext).addCallback(result -> {
        String remoteRegistrationId = result.getRegistrationId();
        boolean error = result.getErrorCode() != null || remoteRegistrationId == null;
        if (error) {
            logger.warn("failed to register {} to remote broker (will retry later) with error {}",
                    localRegistrationId, result.getErrorCode());
        } else {
            logger.debug("successfully registered {}to remote broker ({})", localRegistrationId,
                    result.getRegistrationId());
        }
        // On error, keep registerContext for future retry
        updateRemoteRegistration(localRegistrationId, remoteRegistrationId, error ? registerContext : null);
    }, ex -> {
        logger.warn("failed to register {} to remote broker (will retry later) with error {}",
                localRegistrationId, ex.toString());
        updateRemoteRegistration(localRegistrationId, null, registerContext);
    });
}

From source file:com.onedrive.api.internal.MultipartRelatedHttpMessageConverter.java

@SuppressWarnings("unchecked")
private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) throws IOException {
    Object partBody = partEntity.getBody();
    Class<?> partType = partBody.getClass();
    HttpHeaders partHeaders = partEntity.getHeaders();
    MediaType partContentType = partHeaders.getContentType();
    for (HttpMessageConverter<?> messageConverter : this.partConverters) {
        if (messageConverter.canWrite(partType, partContentType)) {
            HttpOutputMessage multipartMessage = new MultipartHttpOutputMessage(os);
            StringBuilder builder = new StringBuilder("<").append(name).append('>');
            multipartMessage.getHeaders().set("Content-ID", builder.toString());
            if (!partHeaders.isEmpty()) {
                multipartMessage.getHeaders().putAll(partHeaders);
            }/*from  ww  w  .j a va  2  s.c  o  m*/
            ((HttpMessageConverter<Object>) messageConverter).write(partBody, partContentType,
                    multipartMessage);
            return;
        }
    }
    throw new HttpMessageNotWritableException("Could not write request: no suitable HttpMessageConverter "
            + "found for request type [" + partType.getName() + "]");
}

From source file:org.jasig.portlet.courses.dao.xml.Jaxb2CourseSummaryHttpMessageConverter.java

@Override
protected void writeToResult(Object o, HttpHeaders headers, Result result) throws IOException {
    try {/* w  w  w  . j  av a2s.  c om*/
        Class clazz = ClassUtils.getUserClass(o);
        Marshaller marshaller = createWrapperMarshaller(clazz);
        setCharset(headers.getContentType(), marshaller);
        marshaller.marshal(o, result);
    } catch (MarshalException ex) {
        throw new HttpMessageNotWritableException("Could not marshal [" + o + "]: " + ex.getMessage(), ex);
    } catch (JAXBException ex) {
        throw new HttpMessageConversionException("Could not instantiate JAXBContext: " + ex.getMessage(), ex);
    }
}

From source file:org.cloudfoundry.identity.api.web.ServerRunning.java

public ResponseEntity<String> postForString(String path, MultiValueMap<String, String> formData,
        HttpHeaders headers) {//ww  w .  ja  va  2  s .  c  o m
    if (headers.getContentType() == null) {
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    }
    return client.exchange(getUrl(path), HttpMethod.POST,
            new HttpEntity<MultiValueMap<String, String>>(formData, headers), String.class);
}

From source file:org.cloudfoundry.identity.api.web.ServerRunning.java

@SuppressWarnings("rawtypes")
public ResponseEntity<Map> postForMap(String path, MultiValueMap<String, String> formData,
        HttpHeaders headers) {/*ww  w.ja v a 2s  . com*/
    if (headers.getContentType() == null) {
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    }
    return client.exchange(getUrl(path), HttpMethod.POST,
            new HttpEntity<MultiValueMap<String, String>>(formData, headers), Map.class);
}

From source file:org.zalando.riptide.Callback.java

@Override
public void doWithRequest(final ClientHttpRequest request) throws IOException {
    final HttpHeaders headers = entity.getHeaders();
    request.getHeaders().putAll(headers);

    @Nullable/*  ww  w  .  jav a 2s  . c  o m*/
    final T body = entity.getBody();

    if (body == null) {
        return;
    }

    final Class<?> type = body.getClass();
    @Nullable
    final MediaType contentType = headers.getContentType();

    final Optional<HttpMessageConverter<T>> match = converters.stream()
            .filter(c -> c.canWrite(type, contentType)).map(this::cast).findFirst();

    if (match.isPresent()) {
        final HttpMessageConverter<T> converter = match.get();

        converter.write(body, contentType, request);
    } else {
        final String message = format(
                "Could not write request: no suitable HttpMessageConverter found for request type [%s]",
                type.getName());

        if (contentType == null) {
            throw new RestClientException(message);
        } else {
            throw new RestClientException(format("%s and content type [%s]", message, contentType));
        }
    }
}

From source file:com.orange.cepheus.cep.EventSinkListenerTest.java

/**
 * Check that an updateContext is fired when a new event bean arrives
 *///www. j a va  2 s.c om
@Test
public void postMessageOnEventUpdate() {

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

    when(statement.getText()).thenReturn("statement");
    when(ngsiClient.getRequestHeaders(any())).thenReturn(httpHeaders);

    // Trigger event update
    List<ContextAttribute> attributes = new LinkedList<>();
    attributes.add(new ContextAttribute("id", "string", "OUT1234"));
    attributes.add(new ContextAttribute("avgTemp", "double", 10.25));
    attributes.add(new ContextAttribute("avgTemp_unit", "string", "celcius"));
    EventBean[] beans = { buildEventBean("TempSensorAvg", attributes) };
    eventSinkListener.update(beans, null, statement, provider);

    // Capture updateContext when postUpdateContextRequest is called on updateContextRequest,
    ArgumentCaptor<UpdateContext> updateContextArg = ArgumentCaptor.forClass(UpdateContext.class);
    ArgumentCaptor<HttpHeaders> headersArg = ArgumentCaptor.forClass(HttpHeaders.class);

    verify(ngsiClient).updateContext(eq(broker.getUrl()), headersArg.capture(), updateContextArg.capture());

    // Check updateContext is valid
    UpdateContext updateContext = updateContextArg.getValue();
    assertEquals(UpdateAction.APPEND, updateContext.getUpdateAction());
    assertEquals(1, updateContext.getContextElements().size());

    // Check headers are valid
    HttpHeaders headers = headersArg.getValue();
    assertEquals(MediaType.APPLICATION_JSON, headers.getContentType());
    assertTrue(headers.getAccept().contains(MediaType.APPLICATION_JSON));
    assertEquals("SN", headers.getFirst("Fiware-Service"));
    assertEquals("SP", headers.getFirst("Fiware-ServicePath"));
    assertEquals("AUTH_TOKEN", headers.getFirst("X-Auth-Token"));

    ContextElement contextElement = updateContext.getContextElements().get(0);
    assertEquals("OUT1234", contextElement.getEntityId().getId());
    assertEquals("TempSensorAvg", contextElement.getEntityId().getType());
    assertFalse(contextElement.getEntityId().getIsPattern());
    assertEquals(1, contextElement.getContextAttributeList().size());

    ContextAttribute attr = contextElement.getContextAttributeList().get(0);
    assertEquals("avgTemp", attr.getName());
    assertEquals("double", attr.getType());
    assertEquals(10.25, attr.getValue());
    assertEquals(1, attr.getMetadata().size());
    assertEquals("unit", attr.getMetadata().get(0).getName());
    assertEquals("string", attr.getMetadata().get(0).getType());
    assertEquals("celcius", attr.getMetadata().get(0).getValue());
}