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

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

Introduction

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

Prototype

ContentType TEXT_XML

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

Click Source Link

Usage

From source file:org.wise.vle.domain.webservice.crater.CRaterHttpClient.java

/**
 * Handles POSTing a CRater Request to the CRater Servlet and returns the 
 * CRater response string./*from   w w  w. j ava  2  s.  c  o m*/
 * 
 * @param cRaterUrl the CRater url
 * @param bodyData the xml body data to be sent to the CRater server
 * @return the response from the CRater server
 */
public static String post(String cRaterUrl, String bodyData) {
    String responseString = null;

    if (cRaterUrl != null) {
        HttpClient client = HttpClientBuilder.create().build();

        // Create a method instance.
        HttpPost post = new HttpPost(cRaterUrl);

        try {
            //System.out.println("CRater request bodyData:" + bodyData);
            post.setEntity(new StringEntity(bodyData, ContentType.TEXT_XML));

            // Execute the method.
            HttpResponse response = client.execute(post);

            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                System.err.println("Method failed: " + response.getStatusLine());
            }

            // Read the response body.
            responseString = IOUtils.toString(response.getEntity().getContent());
            //System.out.println("responseString: " + responseString);
        } catch (IOException e) {
            System.err.println("Fatal transport error: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // Release the connection.
            post.releaseConnection();
        }
    }

    return responseString;
}

From source file:com.sonatype.nexus.perftest.maven.ArtifactDeployer.java

/**
 * Deploys provided pom.xml file under specified groupId, artifactId and version. The contents of the pom is updated
 * to match specified groupId, artifactId and version.
 */// w  w w  . j av a  2s  . com
public void deployPom(String groupId, String artifactId, String version, File pomTemplate) throws IOException {
    final Document pom = XMLParser.parse(pomTemplate);

    pom.getRootElement().getChild("groupId").setText(groupId);
    pom.getRootElement().getChild("artifactId").setText(artifactId);
    pom.getRootElement().getChild("version").setText(version);
    // pom.getRootElement().getChild( "packaging" ).setText( "pom" );
    StringWriter buf = new StringWriter();
    XMLWriter writer = new XMLWriter(buf);
    pom.toXML(writer);
    HttpEntity pomEntity = new StringEntity(buf.toString(), ContentType.TEXT_XML);

    deploy(pomEntity, groupId, artifactId, version, ".pom");
}

From source file:eu.scape_project.fcrepo.integration.ReferencedContentIntellectualEntitiesIT.java

@Test
public void testIngestIntellectualEntityAndCheckRedirectForBinary() throws Exception {
    HttpPost post = new HttpPost(SCAPE_URL + "/entity");
    post.setEntity(//from   ww w  .ja v a2s  .  c om
            new InputStreamEntity(this.getClass().getClassLoader().getResourceAsStream("ONB_mets_small.xml"),
                    -1, ContentType.TEXT_XML));
    HttpResponse resp = this.client.execute(post);
    String id = EntityUtils.toString(resp.getEntity());
    post.releaseConnection();

    HttpGet get = new HttpGet(SCAPE_URL + "/entity/" + id);
    resp = client.execute(get);
    assertEquals(200, resp.getStatusLine().getStatusCode());
    IntellectualEntity e = this.marshaller.deserialize(IntellectualEntity.class, resp.getEntity().getContent());
    get.releaseConnection();

    for (Representation r : e.getRepresentations()) {
        for (File f : r.getFiles()) {
            get = new HttpGet(SCAPE_URL + "/file/" + e.getIdentifier().getValue() + "/"
                    + r.getIdentifier().getValue() + "/" + f.getIdentifier().getValue());
            this.client.getParams().setBooleanParameter("http.protocol.handle-redirects", false);
            resp = this.client.execute(get);
            assertEquals(307, resp.getStatusLine().getStatusCode());
            assertEquals(f.getUri().toASCIIString(), resp.getFirstHeader("Location").getValue());
            get.releaseConnection();
        }
    }
}

From source file:au.csiro.casda.sodalint.Validator.java

/**
 * Retrieve the content from an address using a GET request.
 *  //from w w  w . j a  v a2  s . com
 * @param address The address to be queried.
 * @return The content, or null if no content could be read.
 * @throws HttpResponseException If a non 200 response code is returned.
 * @throws UnsupportedEncodingException If the content does not have an XML format. 
 * @throws IOException If the content could not be read.
 */
protected String getXmlContentFromUrl(String address)
        throws HttpResponseException, UnsupportedEncodingException, IOException {
    Response response = Request.Get(address).execute();
    HttpResponse httpResponse = response.returnResponse();
    StatusLine statusLine = httpResponse.getStatusLine();
    final int statusCodeOk = 200;
    if (statusLine.getStatusCode() != statusCodeOk) {
        throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
    }
    HttpEntity entity = httpResponse.getEntity();
    if (entity == null) {
        return null;
    }
    ContentType contentType = ContentType.getOrDefault(entity);
    if (!ContentType.APPLICATION_XML.getMimeType().equals(contentType.getMimeType())
            && !ContentType.TEXT_XML.getMimeType().equals(contentType.getMimeType())) {
        throw new UnsupportedEncodingException(contentType.toString());
    }
    String content = readTextContent(entity);
    if (StringUtils.isBlank(content)) {
        return null;
    }

    return content;
}

From source file:eu.scape_project.fcrepo.integration.AbstractIT.java

protected void postEntity(IntellectualEntity ie) throws IOException {
    HttpPost post = new HttpPost(SCAPE_URL + "/entity");
    ByteArrayOutputStream sink = new ByteArrayOutputStream();
    try {//from w ww.  j a  v a 2s.c  om
        this.marshaller.serialize(ie, sink);
    } catch (JAXBException e) {
        throw new IOException(e);
    }
    post.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink.toByteArray()), sink.size(),
            ContentType.TEXT_XML));
    HttpResponse resp = this.client.execute(post);
    assertEquals(201, resp.getStatusLine().getStatusCode());
    String id = EntityUtils.toString(resp.getEntity());
    assertTrue(id.length() > 0);
    post.releaseConnection();
}

From source file:org.obm.sync.push.client.XMLOPClient.java

private ByteArrayEntity getRequestEntity(Document doc)
        throws UnsupportedEncodingException, TransformerException {
    try {/*from  w  w  w  .j  ava 2 s  .  co  m*/
        String xmlData = DOMUtils.serialize(doc);
        return new ByteArrayEntity(xmlData.getBytes("UTF8"), ContentType.TEXT_XML);
    } catch (TransformerException e) {
        throw new TransformerException("Cannot serialize data to xml", e);
    }
}

From source file:com.axelor.apps.account.ebics.client.HttpRequestSender.java

/**
 * Sends the request contained in the <code>ContentFactory</code>.
 * The <code>ContentFactory</code> will deliver the request as
 * an <code>InputStream</code>.
 *
 * @param request the ebics request//from   ww w .  j  a va 2 s. com
 * @return the HTTP return code
* @throws AxelorException 
 */
public final int send(ContentFactory request) throws IOException, AxelorException {
    HttpClient httpClient;
    String proxyConfiguration;
    InputStream input;
    int retCode;

    httpClient = new HttpClient();
    EbicsBank bank = session.getUser().getEbicsPartner().getEbicsBank();
    DefaultHttpClient client = getSecuredHttpClient(EbicsCertificateService.getCertificate(bank, "ssl"));

    proxyConfiguration = AppSettings.get().get("http.proxy.host");

    if (proxyConfiguration != null && !proxyConfiguration.equals("")) {
        HostConfiguration hostConfig;
        String proxyHost;
        int proxyPort;

        hostConfig = httpClient.getHostConfiguration();
        proxyHost = AppSettings.get().get("http.proxy.host").trim();
        proxyPort = Integer.parseInt(AppSettings.get().get("http.proxy.port").trim());
        hostConfig.setProxy(proxyHost, proxyPort);
        if (!AppSettings.get().get("http.proxy.user").equals("")) {
            String user;
            String pwd;
            UsernamePasswordCredentials credentials;
            AuthScope authscope;

            user = AppSettings.get().get("http.proxy.user").trim();
            pwd = AppSettings.get().get("http.proxy.password").trim();
            credentials = new UsernamePasswordCredentials(user, pwd);
            authscope = new AuthScope(proxyHost, proxyPort);
            httpClient.getState().setProxyCredentials(authscope, credentials);
        }
    }

    input = request.getContent();
    retCode = -1;
    HttpPost post = new HttpPost(bank.getUrl());
    ContentType type = ContentType.TEXT_XML;
    HttpEntity entity = new InputStreamEntity(input, retCode, type);
    post.setEntity(entity);
    HttpResponse responseHttp = client.execute(post);
    retCode = responseHttp.getStatusLine().getStatusCode();
    response = new InputStreamContentFactory(responseHttp.getEntity().getContent());
    return retCode;
}

From source file:org.n52.ses.common.integration.test.UTF8SpecialCharacterIT.java

@Test
public void shouldCreateSoapFault() throws OXFException, XmlException, IOException {
    ServiceInstance.getInstance().waitUntilAvailable();

    String notify = readNotification();
    ParameterContainer parameter = new ParameterContainer();
    parameter.addParameterShell(ISESRequestBuilder.NOTIFY_SES_URL,
            ServiceInstance.getInstance().getHost().toExternalForm());
    parameter.addParameterShell(ISESRequestBuilder.NOTIFY_XML_MESSAGE, notify);

    try {/*  w w  w. j a va  2 s .  co m*/
        String payload = SESRequestBuilderFactory.generateRequestBuilder("0.0.0").buildNotifyRequest(parameter);
        HttpClient httpClient = new ProxyAwareHttpClient(new SimpleHttpClient());
        HttpResponse httpResponse = httpClient.executePost(
                ServiceInstance.getInstance().getHost().toExternalForm(), payload, ContentType.TEXT_XML);
        HttpEntity responseEntity = httpResponse.getEntity();
        if (responseEntity != null && responseEntity.getContent() != null) {
            EnvelopeDocument xo = EnvelopeDocument.Factory.parse(responseEntity.getContent());
            Collection<XmlError> errors = XMLBeansParser.validate(xo);

            Assert.assertTrue("Response is not valid", errors.isEmpty());
            Body body = xo.getEnvelope().getBody();
            XmlCursor cur = body.newCursor();
            cur.toFirstChild();

            Assert.assertTrue("Not a SoapFault!", cur.getObject() instanceof Fault);
            cur.dispose();

            logger.info("Received an expected SoapFault: " + xo);
        } else
            throw new IllegalStateException("No response available.");
    } catch (HttpClientException e) {
        throw new OXFException("Could not send request.", e);
    } catch (IllegalStateException e) {
        throw new OXFException("Could not send request.", e);
    } catch (IOException e) {
        throw new OXFException("Could not send request.", e);
    } catch (XmlException e) {
        throw new OXFException("Could not send request.", e);
    }

}