Example usage for org.springframework.http MediaType APPLICATION_XML

List of usage examples for org.springframework.http MediaType APPLICATION_XML

Introduction

In this page you can find the example usage for org.springframework.http MediaType APPLICATION_XML.

Prototype

MediaType APPLICATION_XML

To view the source code for org.springframework.http MediaType APPLICATION_XML.

Click Source Link

Document

Public constant media type for application/xml .

Usage

From source file:com.orange.ngsi.client.NgsiClient.java

/**
 * The default HTTP request headers used for the requests.
 * @return the HTTP request headers.//w w  w .jav a2 s.  c  o  m
 */
public HttpHeaders getRequestHeaders() {
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.APPLICATION_XML);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
    return requestHeaders;
}

From source file:edu.sjsu.cmpe275.lab2.service.ManagePersonController.java

/** Get a person object
 2 Path: person/ {id}?format={json | xml | html}
 Method: GET/*w  w  w  . j  ava2 s.  c om*/
 This returns a full person object with the given ID in the given format in its HTTP payload.
 ? All existing fields, including the optional organization and list of friends should be
 returned.
  The payload should contain the full organization object, if present.
        
 The list of friends can be either (a) list of person IDs, or (b) list of  shallow ?
 person objects that do not have their friends list populated. If you take option
 (b), you want to use techniques like lazy loading to avoid serializing the whole
 social network starting from the requested person in the returned payload.
 ? If the person of the given user ID does not exist, the HTTP return code should be 404;
 otherwise, 200.
 ? The format parameter is optional, and the value is case insensitive. If missing, JSON is
 assumed.
        
 * @param a         Description of a
 * @param b         Description of b
 * @return         Description of c
 */

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<?> getPerson(@PathVariable("id") long id,
        @RequestParam(value = "format", required = true) String format) {
    Transaction transaction = null;
    Session session = null;
    Person person = null;
    HttpHeaders httpHeaders = new HttpHeaders();

    if ("json".equals(format)) {
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    } else if ("xml".equals(format)) {
        httpHeaders.setContentType((MediaType.APPLICATION_XML));
    } else if ("html".equals(format)) {
        httpHeaders.setContentType(MediaType.TEXT_HTML);
    } else {
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    }

    try {
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();
        person = (Person) session.get(Person.class, id);
        if (person == null) {
            throw new HibernateException("Can't find record with id = " + id);
        }
        transaction.commit();

    } catch (HibernateException e) {
        if (transaction != null) {
            transaction.rollback();
        }
        return new ResponseEntity<Object>("Can't find record with id = " + id, httpHeaders,
                HttpStatus.NOT_FOUND);
    } finally {
        if (session != null) {
            session.close();
        }
    }
    return new ResponseEntity<>(person, httpHeaders, HttpStatus.OK);
}

From source file:com.monarchapis.driver.spring.rest.ApiErrorResponseEntityExceptionHandlerTest.java

@Test
public void testHttpMediaTypeNotAcceptableException() {
    List<MediaType> supportedMediaTypes = Lists.newArrayList(//
            MediaType.APPLICATION_XML, //
            MediaType.APPLICATION_JSON);

    performTest(//
            new HttpMediaTypeNotAcceptableException(supportedMediaTypes), //
            400, //
            "mediaTypeNotAcceptable");
}

From source file:org.cloudfoundry.identity.uaa.security.web.UaaRequestMatcherTests.java

@Test
public void pathMatcherMatchesWithMultipleAccepts() throws Exception {
    // Accept only JSON
    UaaRequestMatcher matcher = new UaaRequestMatcher("/somePath");
    matcher.setAccept(Arrays.asList(MediaType.APPLICATION_JSON.toString()));
    assertTrue(matcher.matches(request("/somePath", String.format("%s,%s",
            MediaType.APPLICATION_JSON.toString(), MediaType.APPLICATION_XML.toString()))));
}

From source file:argendata.api.DatasetAPIService.java

@GET
@Path("/by/title/{t}.rdf")
@Produces("application/xml")
public String getDatasetByTitleRDFXML(@PathParam(value = "t") String title) {

    try {/*  ww  w. j a va  2  s  .  c  o m*/

        title = URLDecoder.decode(title, "UTF-8");
        validate(title);
        title = Parsing.withoutSpecialCharacters(title);
    } catch (Exception e1) {
        throw new NotFoundException("Recurso no encontrado");
    }

    QName qName = new QName(properties.getNamespace(), "Dataset:" + title);

    String rdfxml;
    try {
        rdfxml = repositoryGateway.getDatasetRDFByQName(qName);
    } catch (Exception e) {
        throw new NotFoundException("Recurso no encontrado");
    }

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_XML);

    return rdfxml;// new ResponseEntity<String>(rdfxml, responseHeaders,
                  // HttpStatus.CREATED);
}

From source file:org.cloudfoundry.identity.uaa.security.web.UaaRequestMatcherTests.java

@Test
public void pathMatcherMatchesWithMultipleAcceptTargets() throws Exception {
    // Accept only JSON
    UaaRequestMatcher matcher = new UaaRequestMatcher("/somePath");
    matcher.setAccept(Arrays.asList(MediaType.APPLICATION_JSON.toString(),
            MediaType.APPLICATION_FORM_URLENCODED.toString()));
    assertTrue(matcher.matches(request("/somePath", String.format("%s,%s",
            MediaType.APPLICATION_JSON.toString(), MediaType.APPLICATION_XML.toString()))));
}

From source file:com.orange.ngsi.client.UpdateContextSubscriptionTest.java

@Test
public void updateContextSubscriptionRequestOK_XML() throws Exception {

    ngsiClient.protocolRegistry.registerHost(baseUrl);
    String responseBody = xml(xmlConverter, createUpdateContextSubscriptionResponseTemperature());

    this.mockServer.expect(requestTo(baseUrl + "/ngsi10/updateContextSubscription"))
            .andExpect(method(HttpMethod.POST))
            .andExpect(header("Content-Type", MediaType.APPLICATION_XML_VALUE))
            .andExpect(header("Accept", MediaType.APPLICATION_XML_VALUE))
            .andExpect(xpath("updateContextSubscriptionRequest/subscriptionId").string("12345678"))
            .andExpect(xpath("updateContextSubscriptionRequest/duration").string("P1M"))
            .andExpect(xpath("updateContextSubscriptionRequest/throttling").string("PT1S"))
            .andExpect(xpath("updateContextSubscriptionRequest/restriction/attributeExpression")
                    .string("xpath/expression"))
            .andExpect(xpath("updateContextSubscriptionRequest/restriction/scope/operationScope/scopeType")
                    .string("type"))
            .andExpect(xpath("updateContextSubscriptionRequest/restriction/scope/operationScope/scopeValue")
                    .string("value"))
            .andRespond(withSuccess(responseBody, MediaType.APPLICATION_XML));

    UpdateContextSubscriptionResponse response = ngsiClient
            .updateContextSubscription(baseUrl, null, createUpdateContextSubscriptionTemperature()).get();
    this.mockServer.verify();

    Assert.assertNull(response.getSubscribeError());
    Assert.assertEquals("12345678", response.getSubscribeResponse().getSubscriptionId());
    Assert.assertEquals("P1M", response.getSubscribeResponse().getDuration());
}

From source file:se.skltp.cooperation.web.rest.v1.controller.ServiceConsumerControllerTest.java

@Test
public void getAllAsXml_shouldReturnAll() throws Exception {

    when(serviceConsumerServiceMock.findAll(any(ServiceConsumerCriteria.class)))
            .thenReturn(Arrays.asList(c1, c2));
    when(mapperMock.map(c1, ServiceConsumerDTO.class)).thenReturn(dto1);
    when(mapperMock.map(c2, ServiceConsumerDTO.class)).thenReturn(dto2);

    mockMvc.perform(get("/api/v1/serviceConsumers").accept(MediaType.APPLICATION_XML))
            .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_XML))
            .andExpect(xpath("/serviceConsumers/serviceConsumer[1]/id").string(is(dto1.getId().toString())))
            .andExpect(/*from  w w w  .ja  v a 2 s  .  com*/
                    xpath("/serviceConsumers/serviceConsumer[1]/description").string(is(dto1.getDescription())))
            .andExpect(xpath("/serviceConsumers/serviceConsumer[1]/hsaId").string(is(dto1.getHsaId())))
            .andExpect(xpath("/serviceConsumers/serviceConsumer[2]/id").string(is(dto2.getId().toString())))
            .andExpect(
                    xpath("/serviceConsumers/serviceConsumer[2]/description").string(is(dto2.getDescription())))
            .andExpect(xpath("/serviceConsumers/serviceConsumer[2]/hsaId").string(is(dto2.getHsaId())));

    verify(serviceConsumerServiceMock, times(1)).findAll(any(ServiceConsumerCriteria.class));
    verifyNoMoreInteractions(serviceConsumerServiceMock);

}

From source file:org.wcy123.ProtobufMessageConverter.java

@Override
protected void writeInternal(Message message, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    MediaType contentType = outputMessage.getHeaders().getContentType();
    Charset charset = getCharset(contentType);

    if (MediaType.TEXT_HTML.isCompatibleWith(contentType)) {
        throw new UnsupportedOperationException("not supported yet");
    } else if (MediaType.APPLICATION_JSON.isCompatibleWith(contentType)) {
        final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputMessage.getBody(), charset);
        printer.appendTo(message, outputStreamWriter);
        outputStreamWriter.flush();/*  w  ww. j a va 2 s .c  o m*/
    } else if (MediaType.TEXT_PLAIN.isCompatibleWith(contentType)) {
        final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputMessage.getBody(), charset);
        TextFormat.print(message, outputStreamWriter);
        outputStreamWriter.flush();
    } else if (MediaType.APPLICATION_XML.isCompatibleWith(contentType)) {
        throw new UnsupportedOperationException("not supported yet");
    } else if (PROTOBUF.isCompatibleWith(contentType)) {
        setProtoHeader(outputMessage, message);
        FileCopyUtils.copy(message.toByteArray(), outputMessage.getBody());
    }
}