Example usage for org.apache.http.entity ContentType APPLICATION_XML

List of usage examples for org.apache.http.entity ContentType APPLICATION_XML

Introduction

In this page you can find the example usage for org.apache.http.entity ContentType APPLICATION_XML.

Prototype

ContentType APPLICATION_XML

To view the source code for org.apache.http.entity ContentType APPLICATION_XML.

Click Source Link

Usage

From source file:com.hp.octane.integrations.services.tests.TestsServiceImpl.java

@Override
public OctaneResponse pushTestsResult(InputStream testsResult, String jobId, String buildId)
        throws IOException {
    if (testsResult == null) {
        throw new IllegalArgumentException("tests result MUST NOT be null");
    }/*from  ww w.  j  ava  2  s .c om*/
    if (jobId == null || jobId.isEmpty()) {
        throw new IllegalArgumentException("job ID MUST NOT be null nor empty");
    }
    if (buildId == null || buildId.isEmpty()) {
        throw new IllegalArgumentException("build ID MUST NOT be null nor empty");
    }

    OctaneRestClient octaneRestClient = restService.obtainOctaneRestClient();
    Map<String, String> headers = new HashMap<>();
    headers.put(RestService.CONTENT_TYPE_HEADER, ContentType.APPLICATION_XML.getMimeType());
    String uri;
    try {
        uri = new URIBuilder(getAnalyticsContextPath(configurer.octaneConfiguration.getUrl(),
                configurer.octaneConfiguration.getSharedSpace()) + "test-results")
                        .addParameter("skip-errors", "false")
                        .addParameter("instance-id", configurer.octaneConfiguration.getInstanceId())
                        .addParameter("job-ci-id", jobId).addParameter("build-ci-id", buildId).build()
                        .toString();
    } catch (URISyntaxException urise) {
        throw new PermanentException("failed to build URL to Octane's 'test-results' resource", urise);
    }
    OctaneRequest request = dtoFactory.newDTO(OctaneRequest.class).setMethod(HttpMethod.POST).setUrl(uri)
            .setHeaders(headers).setBody(testsResult);
    OctaneResponse response = octaneRestClient.execute(request);
    logger.info("tests result pushed; status: " + response.getStatus() + ", response: " + response.getBody());
    return response;
}

From source file:org.wuspba.ctams.ws.ITBandContestEntryController.java

private static void add() throws Exception {
    ITVenueController.add();/*from   w ww  . j  a  v  a2 s  . c  om*/
    ITJudgeController.add();
    ITBandController.add();
    ITBandContestController.add();

    CTAMSDocument doc = new CTAMSDocument();
    doc.getVenues().add(TestFixture.INSTANCE.venue);
    doc.getJudges().add(TestFixture.INSTANCE.judgeAndy);
    doc.getJudges().add(TestFixture.INSTANCE.judgeJamie);
    doc.getJudges().add(TestFixture.INSTANCE.judgeBob);
    doc.getJudges().add(TestFixture.INSTANCE.judgeEoin);
    doc.getBandContests().add(TestFixture.INSTANCE.bandContest);
    doc.getBands().add(TestFixture.INSTANCE.skye);
    doc.getBandContestEntry().add(TestFixture.INSTANCE.bandContestEntry);

    String xml = XMLUtils.marshal(doc);

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpPost httpPost = new HttpPost(uri);

    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    CloseableHttpResponse response = null;

    try {
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        TestFixture.INSTANCE.bandContestEntry.setId(doc.getBandContestEntry().get(0).getId());

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }
}

From source file:org.wuspba.ctams.ws.ITSoloContestEntryController.java

private static void add() throws Exception {
    ITVenueController.add();/*from w w  w.  j  a v a  2  s . co m*/
    ITJudgeController.add();
    ITPersonController.add();
    ITSoloContestController.add();

    CTAMSDocument doc = new CTAMSDocument();
    doc.getVenues().add(TestFixture.INSTANCE.venue);
    doc.getJudges().add(TestFixture.INSTANCE.judgeAndy);
    doc.getJudges().add(TestFixture.INSTANCE.judgeJamie);
    doc.getJudges().add(TestFixture.INSTANCE.judgeBob);
    doc.getJudges().add(TestFixture.INSTANCE.judgeEoin);
    doc.getSoloContests().add(TestFixture.INSTANCE.soloContest);
    doc.getPeople().add(TestFixture.INSTANCE.elaine);
    doc.getSoloContestEntry().add(TestFixture.INSTANCE.soloContestEntry);

    String xml = XMLUtils.marshal(doc);

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpPost httpPost = new HttpPost(uri);

    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    CloseableHttpResponse response = null;

    try {
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        TestFixture.INSTANCE.soloContestEntry.setId(doc.getSoloContestEntry().get(0).getId());

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }
}

From source file:org.sonatype.nexus.plugins.crowd.client.rest.RestClient.java

/**
 * Authenticates a user with crowd. If authentication failed, raises a <code>RemoteException</code>
 * //from w w w  . ja v  a  2  s .c o  m
 * @param username
 * @param password
 * @return session token
 * @throws RemoteException
 */
public void authenticate(String username, String password) throws RemoteException {
    HttpClientContext hc = HttpClientContext.create();
    HttpPost post = new HttpPost(crowdServer.resolve("authentication?username=" + urlEncode(username)));

    if (LOG.isDebugEnabled()) {
        LOG.debug("authentication attempt for '{}'", username);
        LOG.debug(post.getURI().toString());
    }

    AuthenticatePost creds = new AuthenticatePost();
    creds.value = password;
    try {
        acceptXmlResponse(post);
        StringWriter writer = new StringWriter();
        JAXB.marshal(creds, writer);
        post.setEntity(EntityBuilder.create().setText(writer.toString())
                .setContentType(ContentType.APPLICATION_XML).setContentEncoding("UTF-8").build());

        enablePreemptiveAuth(post, hc);
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() != 200) {
            handleHTTPError(response);
        }

    } catch (IOException | AuthenticationException ioe) {
        handleError(ioe);
    } finally {
        post.releaseConnection();
    }
}

From source file:org.wuspba.ctams.ws.ITHiredJudgeController.java

protected static void add() throws Exception {
    ITJudgeController.add();/*  w w  w.j av a2s  . c  o  m*/

    CTAMSDocument doc = new CTAMSDocument();
    doc.getPeople().add(TestFixture.INSTANCE.andy);
    doc.getPeople().add(TestFixture.INSTANCE.jamie);
    doc.getPeople().add(TestFixture.INSTANCE.bob);
    doc.getPeople().add(TestFixture.INSTANCE.eoin);
    doc.getJudges().add(TestFixture.INSTANCE.judgeAndy);
    doc.getJudges().add(TestFixture.INSTANCE.judgeJamie);
    doc.getJudges().add(TestFixture.INSTANCE.judgeBob);
    doc.getJudges().add(TestFixture.INSTANCE.judgeEoin);
    doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeAndy);
    doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeJamie);
    doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeBob);
    doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeEoin);

    String xml = XMLUtils.marshal(doc);

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpPost httpPost = new HttpPost(uri);

    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    CloseableHttpResponse response = null;

    try {
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        for (HiredJudge j : doc.getHiredJudges()) {
            if (j.getJudge().getId().equals(TestFixture.INSTANCE.judgeAndy.getId())) {
                TestFixture.INSTANCE.hiredJudgeAndy.setId(j.getId());
            } else if (j.getJudge().getId().equals(TestFixture.INSTANCE.judgeBob.getId())) {
                TestFixture.INSTANCE.hiredJudgeBob.setId(j.getId());
            } else if (j.getJudge().getId().equals(TestFixture.INSTANCE.judgeJamie.getId())) {
                TestFixture.INSTANCE.hiredJudgeJamie.setId(j.getId());
            } else if (j.getJudge().getId().equals(TestFixture.INSTANCE.judgeEoin.getId())) {
                TestFixture.INSTANCE.hiredJudgeEoin.setId(j.getId());
            }
        }

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }
}

From source file:org.epics.archiverappliance.retrieval.channelarchiver.ChannelArchiverReadOnlyPlugin.java

private List<Callable<EventStream>> getDataForPV(BasicContext context, String pvName, Timestamp startTime,
        Timestamp endTime, int archiveKey, PostProcessor postProcessor) throws IOException {
    try {//from   ww w  . j  av  a 2s. c  o  m
        // TODO the only thing that seems to get similar charts in ArchiveViewer for production data is using plot-binning.
        // This is hardcoded somewhere in the Data server or the ArchiveViewer code....
        // Need to figure out where it and and how to address it.
        String howStr = "3";
        String pvNameForCall = pvName;
        if (context.getPvNameFromRequest() != null) {
            logger.info("Using pvName from request " + context.getPvNameFromRequest()
                    + " when making a call to the ChannelArchiver for pv " + pvName);
            pvNameForCall = context.getPvNameFromRequest();
        }

        String archiveValuesStr = new String("<?xml version=\"1.0\"?>\n" + "<methodCall>\n"
                + "<methodName>archiver.values</methodName>\n" + "<params>\n" + "<param><value><i4>"
                + archiveKey + "</i4></value></param>\n" + "<param><value><array><data><value><string>"
                + pvNameForCall + "</string></value></data></array></value></param>\n" + "<param><value><i4>"
                + TimeUtils.convertToEpochSeconds(startTime) + "</i4></value></param>\n" + "<param><value><i4>"
                + startTime.getNanos() + "</i4></value></param>\n" + "<param><value><i4>"
                + TimeUtils.convertToEpochSeconds(endTime) + "</i4></value></param>\n" + "<param><value><i4>"
                + endTime.getNanos() + "</i4></value></param>\n" + "<param><value><i4>" + valuesRequested
                + "</i4></value></param>\n" + "<param><value><i4>" + howStr + "</i4></value></param>\n"
                + "</params>\n" + "</methodCall>\n");
        URI serverURI = new URI(serverURL);
        if (serverURI.getScheme().equals("file")) {
            logger.info("Using a file provider for Channel Archiver data - this better be a unit test.");
            // We use the file scheme for unit testing... Yeah, the extensions are hardcoded...
            InputStream is = new BufferedInputStream(
                    new FileInputStream(new File(serverURI.getPath() + File.separator + pvName + ".xml")));
            // ArchiverValuesHandler takes over the burden of closing the input stream.
            ArchiverValuesHandler handler = new ArchiverValuesHandler(pvName, is,
                    serverURL.toString() + "\n" + archiveValuesStr, context.getRetrievalExpectedDBRType());
            if (postProcessor != null) {
                return CallableEventStream.makeOneStreamCallableList(handler, postProcessor, true);
            } else {
                return CallableEventStream.makeOneStreamCallableList(handler);
            }
        } else {
            StringEntity archiverValues = new StringEntity(archiveValuesStr, ContentType.APPLICATION_XML);
            if (logger.isDebugEnabled()) {
                logger.debug(getDescription() + " making call to channel archiver with " + archiveValuesStr);
            }

            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost postMethod = new HttpPost(serverURL);
            postMethod.addHeader("Content-Type", "text/xml");
            postMethod.setEntity(archiverValues);
            if (logger.isDebugEnabled()) {
                logger.debug("About to make a POST with " + archiveValuesStr);
            }
            HttpResponse response = httpclient.execute(postMethod);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode >= 200 && statusCode <= 206) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    logger.debug("Obtained a HTTP entity of length " + entity.getContentLength());
                    // ArchiverValuesHandler takes over the burden of closing the input stream.
                    InputStream is = entity.getContent();
                    ArchiverValuesHandler handler = new ArchiverValuesHandler(pvName, is,
                            serverURL.toString() + "\n" + archiveValuesStr,
                            context.getRetrievalExpectedDBRType());
                    if (postProcessor != null) {
                        return CallableEventStream.makeOneStreamCallableList(handler, postProcessor, true);
                    } else {
                        return CallableEventStream.makeOneStreamCallableList(handler);
                    }
                } else {
                    throw new IOException("HTTP response did not have an entity associated with it");
                }
            } else {
                logger.error("Got an invalid status code " + statusCode + " from the server " + serverURL
                        + " for PV " + pvName + " so returning null");
                return null;
            }
        }
    } catch (UnsupportedEncodingException ex) {
        throw new IOException("Exception making call to Channel Archiver", ex);
    } catch (URISyntaxException e) {
        throw new IOException("Invalid URL " + serverURL, e);
    }
}

From source file:org.mobicents.servlet.restcomm.provisioning.number.bandwidth.BandwidthNumberProvisioningManager.java

public boolean cancelNumber(PhoneNumber phoneNumberObj) {
    String phoneNumber = phoneNumberObj.getPhoneNumber();
    boolean isSucceeded = false;
    phoneNumber = phoneNumber.substring(2);
    DisconnectTelephoneNumberOrder order = new DisconnectTelephoneNumberOrder();
    order.setName("Disconnect Order For Number: " + phoneNumber);
    DisconnectTelephoneNumberOrderType disconnectTelephoneNumberOrderType = new DisconnectTelephoneNumberOrderType();
    disconnectTelephoneNumberOrderType.getTelephoneNumberList().add(phoneNumber);
    order.setDisconnectTelephoneNumberOrderType(disconnectTelephoneNumberOrderType);
    try {//from www.  j a v  a2s. c  o  m
        HttpPost post = new HttpPost(buildDisconnectsUri());
        StringEntity entity = new StringEntity(XmlUtils.toXml(order), ContentType.APPLICATION_XML);
        post.setEntity(entity);
        if (telestaxProxyEnabled)
            addTelestaxProxyHeaders(post, ProvisionProvider.REQUEST_TYPE.RELEASEDID.name());
        DisconnectTelephoneNumberOrderResponse response = (DisconnectTelephoneNumberOrderResponse) XmlUtils
                .fromXml(executeRequest(post), DisconnectTelephoneNumberOrderResponse.class);
        if (response.getErrorList().size() == 0 && response.getorderRequest()
                .getDisconnectTelephoneNumberOrderType().getTelephoneNumberList().get(0).equals(phoneNumber)) {
            isSucceeded = true;
        }
        //TODO: get order status and check it before returning.
    } catch (Exception e) {
        logger.error(String.format("Error disconnecting number: %s : %s ", phoneNumber, e.getMessage()));
        isSucceeded = false;
    }
    return isSucceeded;
}

From source file:org.wuspba.ctams.ws.ITVenueController.java

protected static void add() throws Exception {
    CTAMSDocument doc = new CTAMSDocument();
    doc.getVenues().add(TestFixture.INSTANCE.venue);
    String xml = XMLUtils.marshal(doc);

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpPost httpPost = new HttpPost(uri);

    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    CloseableHttpResponse response = null;

    try {//  w w  w .j  av  a2  s  .co m
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        TestFixture.INSTANCE.venue.setId(doc.getVenues().get(0).getId());

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }
}

From source file:tech.sirwellington.alchemy.http.HttpVerbImplTest.java

@Test
public void testExecuteWhenContentTypeInvalid() throws IOException {
    List<ContentType> invalidContentTypes = Arrays.asList(ContentType.APPLICATION_ATOM_XML,
            ContentType.TEXT_HTML, ContentType.TEXT_XML, ContentType.APPLICATION_XML,
            ContentType.APPLICATION_OCTET_STREAM, ContentType.create(one(alphabeticString())));

    ContentType invalidContentType = Lists.oneOf(invalidContentTypes);

    String string = one(alphanumericString());
    entity = new StringEntity(string, invalidContentType);

    when(apacheResponse.getEntity()).thenReturn(entity);

    HttpResponse result = instance.execute(apacheClient, request);
    assertThat(result.bodyAsString(), is(string));
    verify(apacheResponse).close();/*w  ww.  j  av a2 s. com*/
}