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:de.ii.xtraplatform.ogc.csw.client.CSWAdapter.java

private HttpResponse requestGET(CSWOperation operation) throws ParserConfigurationException {
    URI url = findUrl(operation.getOperation(), CSW.METHOD.GET);

    HttpClient httpClient = url.getScheme().equals("https") ? this.untrustedSslHttpClient : this.httpClient;

    URIBuilder uri = new URIBuilder(url);

    Map<String, String> params = operation.toKvp(nsStore, version);

    for (Map.Entry<String, String> param : params.entrySet()) {
        uri.addParameter(param.getKey(), param.getValue());
    }//  ww w. j a v a2 s .  co m
    //LOGGER.debug(FrameworkMessages.GET_REQUEST_OPERATION_URL, operation.toString(), uri.toString());

    boolean retried = false;
    HttpGet httpGet;
    HttpResponse response;

    try {

        // replace the + with %20
        String uristring = uri.build().toString();
        uristring = uristring.replaceAll("\\+", "%20");
        httpGet = new HttpGet(uristring);

        // TODO: temporary basic auth hack
        if (useBasicAuth) {
            String basic_auth = new String(Base64.encodeBase64((user + ":" + password).getBytes()));
            httpGet.addHeader("Authorization", "Basic " + basic_auth);
        }

        response = httpClient.execute(httpGet, new BasicHttpContext());

        // check http status
        checkResponseStatus(response.getStatusLine().getStatusCode(), uri);

    } catch (SocketTimeoutException ex) {
        if (ignoreTimeouts) {
            //LOGGER.warn(FrameworkMessages.GET_REQUEST_TIMED_OUT_AFTER_MS_URL_REQUEST, HttpConnectionParams.getConnectionTimeout(httpClient.getParams()), uri.toString());
        }
        response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "");
        response.setEntity(new StringEntity("", ContentType.TEXT_XML));
    } catch (IOException ex) {
        try {
            if (!isDefaultUrl(uri.build(), CSW.METHOD.GET)) {

                //LOGGER.info(FrameworkMessages.REMOVING_URL, uri.toString());
                this.urls.remove(operation.getOperation().toString());

                //LOGGER.info(FrameworkMessages.RETRY_WITH_DEFAULT_URL, this.urls.get("default"));
                return requestGET(operation);
            }
        } catch (URISyntaxException ex0) {
        }
        //LOGGER.error(FrameworkMessages.FAILED_REQUESTING_URL, uri.toString());
        throw new ReadError("Failed requesting URL: '{}'", uri);
    } catch (URISyntaxException ex) {
        //LOGGER.error(FrameworkMessages.FAILED_REQUESTING_URL, uri.toString());
        throw new ReadError("Failed requesting URL: '{}'", uri);
    }
    //LOGGER.debug(FrameworkMessages.WFS_REQUEST_SUBMITTED);
    return response;
}

From source file:org.wso2.carbon.connector.EWSIntegrationTest.java

@Test(enabled = true, groups = { "wso2.esb" }, description = "EWS test case", dependsOnMethods = {
        "testFindItemAndSendItem" })
public void testCreateUpdateDeleteItem() throws Exception {
    DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
    String createItemProxyUrl = getProxyServiceURL("createItemOperation");
    RestResponse<OMElement> esbSoapResponse = sendXmlRestRequest(createItemProxyUrl, "POST",
            esbRequestHeadersMap, "CreateItem.xml");
    OMElement omElement = esbSoapResponse.getBody();
    OMElement createItemResponseMessageOmelement = omElement.getFirstElement().getFirstChildWithName(new QName(
            "http://schemas.microsoft.com/exchange/services/2006/messages", "CreateItemResponseMessage", "m"));
    String success = createItemResponseMessageOmelement.getAttributeValue(new QName("ResponseClass"));
    // Assert if Create Message got successes
    Assert.assertEquals(success, "Success");
    //Extract Message Id and change Key
    itemId = (String) xPathEvaluate(omElement, "string(//t:ItemId/@Id)", namespaceMap);
    changeKey = (String) xPathEvaluate(omElement, "string(//t:ItemId/@ChangeKey)", namespaceMap);
    Assert.assertNotNull(itemId);//from w  ww. j a v a2 s .  c  o m
    Assert.assertNotNull(changeKey);
    //Sending CreateAttachment Request
    String createAttachmentOperation = getProxyServiceURL("createAttachmentOperation");
    FileInputStream fileInputStream = new FileInputStream(
            getESBResourceLocation() + File.separator + "config" + File.separator + "restRequests"
                    + File.separator + "sampleRequest" + File.separator + "CreateAttachment.xml");
    OMElement createAttachmentSoapRequest = AXIOMUtil.stringToOM(IOUtils.toString(fileInputStream));
    OMElement parentItemID = createAttachmentSoapRequest.getFirstChildWithName(new QName("ParentItemId"));
    parentItemID.getFirstChildWithName(new QName("Id")).setText(itemId);
    parentItemID.getFirstChildWithName(new QName("ChangeKey")).setText(changeKey);
    HttpPost httpPost = new HttpPost(createAttachmentOperation);
    httpPost.setEntity(new StringEntity(createAttachmentSoapRequest.toString(),
            ContentType.TEXT_XML.withCharset(Charset.forName("UTF-8"))));
    HttpResponse response = defaultHttpClient.execute(httpPost);
    OMElement createAttachmentResponse = AXIOMUtil
            .stringToOM(IOUtils.toString(response.getEntity().getContent()));
    String createAttachmentStatus = createAttachmentResponse.getFirstElement().getFirstElement()
            .getAttributeValue(new QName("ResponseClass"));
    String attachmentId = (String) xPathEvaluate(createAttachmentResponse, "string(//t:AttachmentId/@Id)",
            namespaceMap);
    //Checked for the attachment creation got Success
    Assert.assertEquals(createAttachmentStatus, "Success");

    //Send find Item Request
    String findItemOperation = getProxyServiceURL("findItemOperation");
    RestResponse<OMElement> findItemSoapResponse = sendXmlRestRequest(findItemOperation, "POST",
            esbRequestHeadersMap, "FindItem.xml");
    OMElement findItemSoapResponseOmElement = findItemSoapResponse.getBody();
    String findItemStatus = findItemSoapResponseOmElement.getFirstElement().getFirstElement()
            .getAttributeValue(new QName("ResponseClass"));
    //Check for success
    Assert.assertEquals(findItemStatus, "Success");
    //Extract Message unique Id and changeKey
    itemId = (String) xPathEvaluate(findItemSoapResponseOmElement, "string(//t:ItemId/@Id)", namespaceMap);
    changeKey = (String) xPathEvaluate(findItemSoapResponseOmElement, "string(//t:ItemId/@ChangeKey)",
            namespaceMap);
    Assert.assertNotNull(itemId);
    Assert.assertNotNull(changeKey);
    //Do Update into Item
    String updateItemPayload = "<UpdateItem>\n"
            + "    <MessageDisposition>SaveOnly</MessageDisposition><ConflictResolution>AutoResolve"
            + "</ConflictResolution><ItemChanges><ItemChange><ItemId Id=\"" + itemId + "\" ChangeKey=\""
            + changeKey + "\"/>"
            + "<Updates><AppendToItemField><FieldURI FieldURI=\"item:Body\"/><Message><Body BodyType=\"Text\">"
            + "Some additional text to append</Body></Message></AppendToItemField></Updates></ItemChange>"
            + "</ItemChanges></UpdateItem>";
    String updateItemProxyUrl = getProxyServiceURL("updateItemOperation");
    HttpPost updateItemPost = new HttpPost(updateItemProxyUrl);
    updateItemPost.setEntity(
            new StringEntity(updateItemPayload, ContentType.TEXT_XML.withCharset(Charset.forName("UTF-8"))));
    HttpResponse updateItemResponse = defaultHttpClient.execute(updateItemPost);
    OMElement updateItemResponsePayload = AXIOMUtil
            .stringToOM(IOUtils.toString(updateItemResponse.getEntity().getContent()));
    String updateItemStatus = updateItemResponsePayload.getFirstElement().getFirstElement()
            .getAttributeValue(new QName("ResponseClass"));
    //Checked for the Update  got Success
    Assert.assertEquals(updateItemStatus, "Success");
    //Get updated Message and check for the update Exist
    String getItemProxyUrl = getProxyServiceURL("getItemOperation");
    String getItemPayload = "<GetMessage>\n"
            + "<BaseShape>Default</BaseShape><IncludeMimeContent>true</IncludeMimeContent>\t\n" + "<ItemId><Id>"
            + itemId + "</Id><ChangeKey>" + changeKey + "</ChangeKey>\n" + "</ItemId></GetMessage>\n";
    HttpPost getItemPost = new HttpPost(getItemProxyUrl);
    getItemPost.setEntity(
            new StringEntity(getItemPayload, ContentType.TEXT_XML.withCharset(Charset.forName("UTF-8"))));
    OMElement getItemResponse = AXIOMUtil
            .stringToOM(IOUtils.toString(defaultHttpClient.execute(getItemPost).getEntity().getContent()));
    String updatedBody = (String) xPathEvaluate(getItemResponse, "string(//t:Body/text())", namespaceMap);
    Assert.assertEquals(updatedBody, "Priority - Update specificationSome additional text to append");
    //Do Delete Request
    String deleteProxyUrl = getProxyServiceURL("deleteItemOperation");
    String deletePayload = "<DeleteItem><DeleteType>HardDelete</DeleteType><ItemId><Id>" + itemId
            + "</Id><ChangeKey>" + changeKey + "</ChangeKey></ItemId></DeleteItem>";
    HttpPost deleteItemPost = new HttpPost(deleteProxyUrl);
    deleteItemPost.setEntity(
            new StringEntity(deletePayload, ContentType.TEXT_XML.withCharset(Charset.forName("UTF-8"))));
    OMElement deleteItemResponse = AXIOMUtil
            .stringToOM(IOUtils.toString(defaultHttpClient.execute(deleteItemPost).getEntity().getContent()));
    String deleteItemStatus = deleteItemResponse.getFirstElement().getFirstElement()
            .getAttributeValue(new QName("ResponseClass"));
    Assert.assertEquals(deleteItemStatus, "Success");
    //Check weather Item and Attachment is deleted Successfully
    getItemPost.setEntity(
            new StringEntity(getItemPayload, ContentType.TEXT_XML.withCharset(Charset.forName("UTF-8"))));
    OMElement getItemAfterDelete = AXIOMUtil
            .stringToOM(IOUtils.toString(defaultHttpClient.execute(getItemPost).getEntity().getContent()));
    String getItemAfterDeleteStatus = getItemAfterDelete.getFirstElement().getFirstElement()
            .getAttributeValue(new QName("ResponseClass"));
    Assert.assertEquals(getItemAfterDeleteStatus, "Error");
}

From source file:net.di2e.ddf.argo.probe.responder.ProbeHandler.java

/**
 * Sends the response using an HTTP POST
 *
 * @param endpoint/*w ww . j  a  v a  2s. c o  m*/
 *            URI of the service to send the POST to
 * @param responseStr
 *            Content for the response message
 * @param payloadType
 *            Encoding type of the response, should be either XML or JSON.
 */
private void sendResponse(String endpoint, String responseStr, String payloadType) {
    ContentType contentType = ContentType.TEXT_XML;
    if (Probe.JSON.equalsIgnoreCase(payloadType)) {
        contentType = ContentType.APPLICATION_JSON;
    }
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(endpoint);
    httpPost.setEntity(new ByteArrayEntity(responseStr.getBytes(), contentType));

    try {
        CloseableHttpResponse response = httpClient.execute(httpPost);
        LOGGER.debug("Response sent.");
        response.close();
    } catch (Exception e) {
        LOGGER.warn("Could not send message to server at " + endpoint.toString(), e);
    }
}

From source file:com.brienwheeler.svc.authorize_net.impl.CIMClientService.java

@Override
@MonitoredWork/*from  w ww.j  av  a2s  .co  m*/
@GracefulShutdown
@Transactional //(readOnly=true, propagation=Propagation.SUPPORTS)
public String getHostedProfilePageToken(DbId<User> userId, String returnUrl) {
    // More than two years later this still isn't in their Java SDK.  Oh well, let's just do it
    // the stupid way...

    String customerProfileId = userAttributeService.getAttribute(userId, ATTR_PROFILE_ID);
    if (customerProfileId == null)
        customerProfileId = createCustomerProfile(userId);

    StringBuffer buffer = new StringBuffer(4096);
    buffer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
    buffer.append("<getHostedProfilePageRequest xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\">\n");
    buffer.append("  <merchantAuthentication>\n");
    buffer.append("    <name>" + apiLoginID + "</name>");
    buffer.append("    <transactionKey>" + transactionKey + "</transactionKey>\n");
    buffer.append("  </merchantAuthentication>\n");
    buffer.append("  <customerProfileId>" + customerProfileId + "</customerProfileId> \n");
    buffer.append("  <hostedProfileSettings>\n");
    buffer.append("    <setting>\n");
    buffer.append("      <settingName>hostedProfileReturnUrl</settingName>\n");
    buffer.append("      <settingValue>" + returnUrl + "</settingValue>\n");
    buffer.append("    </setting>\n");
    buffer.append("  </hostedProfileSettings>\n");
    buffer.append("</getHostedProfilePageRequest>\n");

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(merchant.isSandboxEnvironment() ? TEST_URL : PRODUCTION_URL);
    EntityBuilder entityBuilder = EntityBuilder.create();
    entityBuilder.setContentType(ContentType.TEXT_XML);
    entityBuilder.setContentEncoding("utf-8");
    entityBuilder.setText(buffer.toString());
    httpPost.setEntity(entityBuilder.build());

    try {
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        String response = EntityUtils.toString(httpResponse.getEntity());
        int start = response.indexOf(ELEMENT_TOKEN_OPEN);
        if (start == -1)
            throw new AuthorizeNetException(
                    "error fetching hosted profile page token for " + userId + ", response: " + response);
        int end = response.indexOf(ELEMENT_TOKEN_CLOSE);
        if (end == -1)
            throw new AuthorizeNetException(
                    "error fetching hosted profile page token for " + userId + ", response: " + response);
        return response.substring(start + ELEMENT_TOKEN_OPEN.length(), end);

    } catch (ClientProtocolException e) {
        throw new AuthorizeNetException(e.getMessage(), e);
    } catch (IOException e) {
        throw new AuthorizeNetException(e.getMessage(), e);
    }
}

From source file:eu.scapeproject.fcrepo.integration.PlanIT.java

private void putPlanExecutionState(String planId, ExecutionState executionState)
        throws JAXBException, IOException {

    PlanExecutionState state = new PlanExecutionState(new Date(), executionState);
    HttpPost post = new HttpPost(SCAPE_URL + "/plan-execution-state/" + planId);
    ByteArrayOutputStream sink = new ByteArrayOutputStream();
    ScapeMarshaller.newInstance().serialize(state, sink);
    post.setEntity(new StringEntity(new String(sink.toByteArray()), ContentType.TEXT_XML));
    HttpResponse resp = this.client.execute(post);
    assertEquals(201, resp.getStatusLine().getStatusCode());
    post.releaseConnection();/*from  w  ww  . j  av  a  2s.  co m*/
}

From source file:de.ii.xtraplatform.ogc.api.wfs.client.WFSAdapter.java

private HttpResponse requestPOST(WfsOperation operation)
        throws ParserConfigurationException, TransformerException, IOException, SAXException {

    URI url = findUrl(operation.getOperation(), WFS.METHOD.POST);

    HttpClient httpClient = url.getScheme().equals("https") ? this.untrustedSslHttpClient : this.httpClient;

    URIBuilder uri = new URIBuilder(url);

    String xml = operation.asXml(new XMLDocumentFactory(nsStore), versions).toString(false);

    LOGGER.debug("{}\n{}", uri, xml);

    HttpPost httpPost;/*w ww  . j a  va  2  s  .c om*/
    HttpResponse response = null;

    try {
        httpPost = new HttpPost(uri.build());

        /*for( String key : operation.getRequestHeaders().keySet()) {
        httpPost.setHeader(key, operation.getRequestHeaders().get(key));
        }*/

        // TODO: temporary basic auth hack
        if (useBasicAuth) {
            httpPost.addHeader("Authorization", "Basic " + basicAuthCredentials);
        }

        StringEntity xmlEntity = new StringEntity(xml, ContentType.create("text/plain", "UTF-8"));
        httpPost.setEntity(xmlEntity);

        response = httpClient.execute(httpPost, new BasicHttpContext());

        // check http status
        checkResponseStatus(response.getStatusLine().getStatusCode(), uri);

    } catch (SocketTimeoutException ex) {
        if (ignoreTimeouts) {
            LOGGER.warn("POST request timed out after %d ms, URL: {} \\nRequest: {}",
                    HttpConnectionParams.getConnectionTimeout(httpClient.getParams()), uri, xml);
        }
        response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "");
        response.setEntity(new StringEntity("", ContentType.TEXT_XML));
    } catch (IOException ex) {
        //LOGGER.error(ERROR_IN_POST_REQUEST_TO_URL_REQUEST, uri.toString(), xml, ex);
        //LOGGER.debug("Error requesting URL: {}", uri.toString());

        try {
            if (!isDefaultUrl(uri.build(), WFS.METHOD.POST)) {

                LOGGER.info("Removing URL: {}", uri);
                this.urls.remove(operation.getOperation().toString());

                LOGGER.info("Retry with default URL: {}", this.urls.get("default"));
                return requestPOST(operation);
            }
        } catch (URISyntaxException ex0) {
        }

        LOGGER.error("Failed requesting URL: '{}'", uri);
        throw new ReadError("Failed requesting URL: '{}'", uri);
    } catch (URISyntaxException ex) {
        LOGGER.error("Failed requesting URL: '{}'", uri);
        throw new ReadError("Failed requesting URL: '{}'", uri);
    } catch (ReadError ex) {
        LOGGER.error("Failed requesting URL: '{}'", uri);
        throw ex;
    }
    LOGGER.debug("WFS request submitted");
    return response;
}

From source file:at.gv.egiz.sl.util.BKUSLConnector.java

private String performHttpBulkRequestToBKU(String xmlRequest, BulkRequestPackage pack, SignParameter parameter)
        throws ClientProtocolException, IOException, IllegalStateException {
    CloseableHttpClient client = null;/* ww  w .  j  a v  a 2s.c o  m*/
    try {
        client = buildHttpClient();
        HttpPost post = new HttpPost(this.bkuUrl);

        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setCharset(Charset.forName("UTF-8"));
        entityBuilder.addTextBody(XMLREQUEST, xmlRequest,
                ContentType.TEXT_XML.withCharset(Charset.forName("UTF-8")));

        if (parameter != null) {
            String transactionId = parameter.getTransactionId();
            if (transactionId != null) {
                entityBuilder.addTextBody("TransactionId_", transactionId);
            }
        }

        for (SignRequestPackage signRequestPackage : pack.getSignRequestPackages()) {

            if (pack != null && signRequestPackage != null
                    && signRequestPackage.getCmsRequest().getSignatureData() != null) {
                entityBuilder.addBinaryBody("fileupload",
                        PDFUtils.blackOutSignature(signRequestPackage.getCmsRequest().getSignatureData(),
                                signRequestPackage.getCmsRequest().getByteRange()));
            }

        }

        post.setEntity(entityBuilder.build());

        HttpResponse response = client.execute(post);
        logger.debug("Response Code : " + response.getStatusLine().getStatusCode());

        if (parameter instanceof BKUHeaderHolder) {
            BKUHeaderHolder holder = (BKUHeaderHolder) parameter;
            Header[] headers = response.getAllHeaders();

            if (headers != null) {
                for (int i = 0; i < headers.length; i++) {
                    BKUHeader hdr = new BKUHeader(headers[i].getName(), headers[i].getValue());
                    logger.debug("Response Header : {}", hdr.toString());
                    holder.getProcessInfo().add(hdr);
                }
            }

            BKUHeader hdr = new BKUHeader(ErrorConstants.STATUS_INFO_SIGDEVICE, SIGNATURE_DEVICE);
            logger.debug("Response Header : {}", hdr.toString());
            holder.getProcessInfo().add(hdr);
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        rd.close();
        response = null;
        rd = null;

        logger.trace(result.toString());
        return result.toString();
    } catch (PDFIOException e) {
        throw new PdfAsWrappedIOException(e);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:de.ii.xtraplatform.ogc.api.wfs.client.WFSAdapter.java

private HttpResponse requestPOST(WFSOperation operation) throws ParserConfigurationException {

    URI url = findUrl(operation.getOperation(), WFS.METHOD.POST);

    HttpClient httpClient = url.getScheme().equals("https") ? this.untrustedSslHttpClient : this.httpClient;

    URIBuilder uri = new URIBuilder(url);

    String xml = operation.getPOSTXML(nsStore, versions);

    LOGGER.debug("{}\n{}", uri, xml);

    HttpPost httpPost;/* w  ww .  j av  a2  s . c  o  m*/
    HttpResponse response = null;

    try {
        httpPost = new HttpPost(uri.build());

        for (String key : operation.getRequestHeaders().keySet()) {
            httpPost.setHeader(key, operation.getRequestHeaders().get(key));
        }

        // TODO: temporary basic auth hack
        if (useBasicAuth) {
            httpPost.addHeader("Authorization", "Basic " + basicAuthCredentials);
        }

        StringEntity xmlEntity = new StringEntity(xml, ContentType.create("text/plain", "UTF-8"));
        httpPost.setEntity(xmlEntity);

        response = httpClient.execute(httpPost, new BasicHttpContext());

        // check http status
        checkResponseStatus(response.getStatusLine().getStatusCode(), uri);

    } catch (SocketTimeoutException ex) {
        if (ignoreTimeouts) {
            LOGGER.warn("POST request timed out after %d ms, URL: {} \\nRequest: {}",
                    HttpConnectionParams.getConnectionTimeout(httpClient.getParams()), uri, xml);
        }
        response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "");
        response.setEntity(new StringEntity("", ContentType.TEXT_XML));
    } catch (IOException ex) {
        //LOGGER.error(ERROR_IN_POST_REQUEST_TO_URL_REQUEST, uri.toString(), xml, ex);
        //LOGGER.debug("Error requesting URL: {}", uri.toString());

        try {
            if (!isDefaultUrl(uri.build(), WFS.METHOD.POST)) {

                LOGGER.info("Removing URL: {}", uri);
                this.urls.remove(operation.getOperation().toString());

                LOGGER.info("Retry with default URL: {}", this.urls.get("default"));
                return requestPOST(operation);
            }
        } catch (URISyntaxException ex0) {
        }

        LOGGER.error("Failed requesting URL: '{}'", uri);
        throw new ReadError("Failed requesting URL: '{}'", uri);
    } catch (URISyntaxException ex) {
        LOGGER.error("Failed requesting URL: '{}'", uri);
        throw new ReadError("Failed requesting URL: '{}'", uri);
    } catch (ReadError ex) {
        LOGGER.error("Failed requesting URL: '{}'", uri);
        throw ex;
    }
    LOGGER.debug("WFS request submitted");
    return response;
}

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

@Test
public void testIngestAndUpdateIntellectualEntity() throws Exception {
    IntellectualEntity ie1 = TestUtil.createTestEntity("entity-17");
    this.postEntity(ie1);

    org.purl.dc.elements._1.ObjectFactory dcFac = new org.purl.dc.elements._1.ObjectFactory();
    ElementContainer cnt = dcFac.createElementContainer();
    SimpleLiteral lit_title = new SimpleLiteral();
    lit_title.getContent().add("Object Updated");
    cnt.getAny().add(dcFac.createTitle(lit_title));

    IntellectualEntity ie2 = new IntellectualEntity.Builder(ie1).descriptive(cnt).build();

    /* update the current object */
    HttpPut put = new HttpPut(SCAPE_URL + "/entity/entity-17");
    ByteArrayOutputStream sink = new ByteArrayOutputStream();
    this.marshaller.serialize(ie2, sink);
    put.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink.toByteArray()), sink.size(),
            ContentType.TEXT_XML));
    HttpResponse resp = this.client.execute(put);
    assertEquals(200, resp.getStatusLine().getStatusCode());
    put.releaseConnection();//from  w ww  . j  a v a2 s. co m

    /* check that the new version is returned */
    HttpGet get = new HttpGet(SCAPE_URL + "/entity/entity-17");
    resp = this.client.execute(get);
    assertEquals(200, resp.getStatusLine().getStatusCode());
    IntellectualEntity fetched = this.marshaller.deserialize(IntellectualEntity.class,
            resp.getEntity().getContent());
    get.releaseConnection();
    assertNotNull(fetched.getDescriptive());
    assertEquals(ElementContainer.class, fetched.getDescriptive().getClass());
    ElementContainer dc = (ElementContainer) fetched.getDescriptive();
    assertEquals("Object Updated", dc.getAny().get(0).getValue().getContent().get(0));

    /* check that the old version is returned when specifically asked for */
    get = new HttpGet(SCAPE_URL + "/entity/entity-17/1");
    resp = this.client.execute(get);
    assertEquals(200, resp.getStatusLine().getStatusCode());
    fetched = this.marshaller.deserialize(IntellectualEntity.class, resp.getEntity().getContent());
    get.releaseConnection();
    assertNotNull(fetched.getDescriptive());
    assertEquals(ElementContainer.class, fetched.getDescriptive().getClass());
    dc = (ElementContainer) fetched.getDescriptive();
    assertEquals("Object 1", dc.getAny().get(0).getValue().getContent().get(0));

    /* check that the new version is returned when specifically asked for */
    get = new HttpGet(SCAPE_URL + "/entity/entity-17/2");
    resp = this.client.execute(get);
    assertEquals(200, resp.getStatusLine().getStatusCode());
    fetched = this.marshaller.deserialize(IntellectualEntity.class, resp.getEntity().getContent());
    get.releaseConnection();
    assertNotNull(fetched.getDescriptive());
    assertEquals(ElementContainer.class, fetched.getDescriptive().getClass());
    dc = (ElementContainer) fetched.getDescriptive();
    assertEquals("Object Updated", dc.getAny().get(0).getValue().getContent().get(0));
}

From source file:org.opentravel.schemacompiler.repository.impl.RemoteRepositoryClient.java

/**
 * @see org.opentravel.schemacompiler.repository.Repository#listItems(java.lang.String, boolean,
 *      boolean)/*from   ww w . ja v a2 s . c  o  m*/
 */
@SuppressWarnings("unchecked")
@Override
public List<RepositoryItem> listItems(String baseNamespace, boolean latestVersionsOnly,
        boolean includeDraftVersions) throws RepositoryException {
    try {
        String baseNS = RepositoryNamespaceUtils.normalizeUri(baseNamespace);
        HttpPost request = newPostRequest(LIST_ITEMS_ENDPOINT);
        Marshaller marshaller = RepositoryFileManager.getSharedJaxbContext().createMarshaller();
        ListItemsRQType listItemsRQ = new ListItemsRQType();
        StringWriter xmlWriter = new StringWriter();

        listItemsRQ.setNamespace(baseNS);
        listItemsRQ.setLatestVersionOnly(latestVersionsOnly);
        listItemsRQ.setIncludeDraft(includeDraftVersions);
        marshaller.marshal(objectFactory.createListItemsRQ(listItemsRQ), xmlWriter);
        request.setEntity(new StringEntity(xmlWriter.toString(), ContentType.TEXT_XML));

        HttpResponse response = executeWithAuthentication(request);

        if (response.getStatusLine().getStatusCode() != HTTP_RESPONSE_STATUS_OK) {
            throw new RepositoryException(getResponseErrorMessage(response));
        }
        Unmarshaller unmarshaller = RepositoryFileManager.getSharedJaxbContext().createUnmarshaller();
        JAXBElement<LibraryInfoListType> jaxbElement = (JAXBElement<LibraryInfoListType>) unmarshaller
                .unmarshal(response.getEntity().getContent());
        List<RepositoryItem> itemList = new ArrayList<RepositoryItem>();

        for (LibraryInfoType itemMetadata : jaxbElement.getValue().getLibraryInfo()) {
            RepositoryItemImpl item = RepositoryUtils.createRepositoryItem(manager, itemMetadata);

            RepositoryUtils.checkItemState(item, manager);
            itemList.add(item);
        }
        return itemList;

    } catch (JAXBException e) {
        throw new RepositoryException("The format of the service response is unreadable.", e);

    } catch (IOException e) {
        throw new RepositoryException("The remote repository is unavailable.", e);
    }
}