Example usage for org.apache.http.client.methods HttpPatch setEntity

List of usage examples for org.apache.http.client.methods HttpPatch setEntity

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPatch setEntity.

Prototype

public void setEntity(final HttpEntity entity) 

Source Link

Usage

From source file:org.fcrepo.integration.http.api.FedoraLdpIT.java

License:asdf

@Test
public void testBinaryLastModified() throws Exception {
    final String objid = getRandomUniqueId();
    final String objURI = serverAddress + objid;
    final String binURI = objURI + "/binary1";

    final Instant lastmod1;
    try (final CloseableHttpResponse response = execute(putDSMethod(objid, "binary1", "some test content"))) {
        assertEquals(CREATED.getStatusCode(), getStatus(response));
        lastmod1 = Instant.from(headerFormat.parse(response.getFirstHeader("Last-Modified").getValue()));
    }//from   www.  j av  a2s .c om

    sleep(1000); // wait a second to make sure last-modified value will be different

    try (final CloseableDataset dataset = getDataset(new HttpGet(binURI + "/fcr:metadata"))) {
        verifyModifiedMatchesCreated(dataset);
    }

    final HttpPatch patchBinary = new HttpPatch(binURI + "/fcr:metadata");
    patchBinary.addHeader(CONTENT_TYPE, "application/sparql-update");
    patchBinary.setEntity(new StringEntity("INSERT { <" + binURI + "> "
            + "<http://www.w3.org/TR/rdf-schema/label> \"this is a label\" } WHERE {}"));

    final Instant lastmod2;
    try (final CloseableHttpResponse response = execute(patchBinary)) {
        assertEquals(NO_CONTENT.getStatusCode(), getStatus(response));
        lastmod2 = Instant.from(headerFormat.parse(response.getFirstHeader("Last-Modified").getValue()));
        assertTrue(lastmod2.isAfter(lastmod1));
    }

    sleep(1000); // wait a second to make sure last-modified value will be different

    final Instant lastmod3;
    try (final CloseableHttpResponse response = execute(putDSMethod(objid, "binary1", "new test content"))) {
        assertEquals(NO_CONTENT.getStatusCode(), getStatus(response));
        lastmod3 = Instant.from(headerFormat.parse(response.getFirstHeader("Last-Modified").getValue()));
        assertTrue(lastmod3.isAfter(lastmod2));
    }
}

From source file:org.fcrepo.integration.http.api.FedoraLdpIT.java

License:asdf

@Test
public void testContainerLastModified() throws Exception {
    final String objid = getRandomUniqueId();
    final String objURI = serverAddress + objid;

    // create an object
    final long lastmod1;
    try (final CloseableHttpResponse response = execute(putObjMethod(objid))) {
        assertEquals(CREATED.getStatusCode(), getStatus(response));
        lastmod1 = Instant.from(headerFormat.parse(response.getFirstHeader("Last-Modified").getValue()))
                .toEpochMilli();//from ww w .ja v a 2 s.  co m
    }

    sleep(1000); // wait a second to make sure last-modified value will be different

    // initial created and last-modified properties should match
    try (final CloseableDataset dataset = getDataset(getObjMethod(objid))) {
        verifyModifiedMatchesCreated(dataset);
    }

    // update the object properties (last-modified should be updated)
    final HttpPatch patchObject = new HttpPatch(objURI);
    patchObject.addHeader(CONTENT_TYPE, "application/sparql-update");
    patchObject.setEntity(new StringEntity(
            "INSERT { <> " + "<http://www.w3.org/TR/rdf-schema/label> \"this is a label\" } WHERE {}"));
    final long lastmod2;
    try (final CloseableHttpResponse response = execute(patchObject)) {
        assertEquals(NO_CONTENT.getStatusCode(), getStatus(response));
        lastmod2 = Instant.from(headerFormat.parse(response.getFirstHeader("Last-Modified").getValue()))
                .toEpochMilli();
        assertTrue(lastmod2 > lastmod1);
    }

    sleep(1000); // wait a second to make sure last-modified value will be different

    // create a direct container (last-modified should be updated)
    final long lastmod3;
    final HttpPut createContainer = new HttpPut(objURI + "/members");
    createContainer.addHeader(CONTENT_TYPE, "text/turtle");
    final String membersRDF = "<> a <http://www.w3.org/ns/ldp#DirectContainer>; "
            + "<http://www.w3.org/ns/ldp#hasMemberRelation> <http://pcdm.org/models#hasMember>; "
            + "<http://www.w3.org/ns/ldp#membershipResource> <" + objURI + "> . ";
    createContainer.setEntity(new StringEntity(membersRDF));
    try (final CloseableHttpResponse response = execute(createContainer)) {
        assertEquals(CREATED.getStatusCode(), getStatus(response));
        lastmod3 = Instant.from(headerFormat.parse(response.getFirstHeader("Last-Modified").getValue()))
                .toEpochMilli();
        assertTrue(lastmod3 > lastmod2);
    }

    sleep(1000); // wait a second to make sure last-modified value will be different

    // create child in the container
    final long lastmod4;
    assertEquals(CREATED.getStatusCode(), getStatus(new HttpPut(objURI + "/members/member1")));

    // last-modified should be updated
    try (final CloseableHttpResponse response = execute(headObjMethod(objid))) {
        assertEquals(OK.getStatusCode(), getStatus(response));
        lastmod4 = Instant.from(headerFormat.parse(response.getFirstHeader("Last-Modified").getValue()))
                .toEpochMilli();
        assertTrue(lastmod4 > lastmod3);
    }
}

From source file:org.fcrepo.integration.http.api.FedoraTransactionsIT.java

/**
 * Tests whether a Sparql update is visible within a transaction
 * and if the update is made persistent along with the commit.
 * @throws Exception/*www  .  j a v  a2  s. co  m*/
 */
@Test
public void testIngestNewWithSparqlPatchWithinTransaction() throws Exception {
    final String objectInTxCommit = randomUUID().toString();

    /* create new tx */
    final String txLocation = createTransaction();

    client = createClient();
    final HttpPost postNew = new HttpPost(txLocation);
    postNew.addHeader("Slug", objectInTxCommit);
    HttpResponse resp = execute(postNew);
    assertEquals(201, resp.getStatusLine().getStatusCode());
    final String newObjectLocation = resp.getFirstHeader("Location").getValue();

    /* update sparql */
    final HttpPatch method = new HttpPatch(newObjectLocation);
    method.addHeader("Content-Type", "application/sparql-update");
    final BasicHttpEntity entity = new BasicHttpEntity();
    final String title = "this is a new title";
    entity.setContent(new ByteArrayInputStream(
            ("INSERT { <> <http://purl.org/dc/elements/1.1/title> \"" + title + "\" } WHERE {}").getBytes()));
    method.setEntity(entity);
    final HttpResponse responseFromPatch = client.execute(method);
    final int status = responseFromPatch.getStatusLine().getStatusCode();
    assertEquals("Didn't get a 204 status! Got status:\n" + status, NO_CONTENT.getStatusCode(), status);

    /* make sure the change was made within the tx */
    final HttpGet httpGet = new HttpGet(newObjectLocation);
    final GraphStore graphStore = getGraphStore(httpGet);
    assertTrue("The sparql update did not succeed within a transaction", graphStore.contains(ANY,
            createResource(newObjectLocation).asNode(), DC_TITLE.asNode(), createPlainLiteral(title).asNode()));

    /* commit */
    client = createClient();
    final HttpPost commitTx = new HttpPost(txLocation + "/fcr:tx/fcr:commit");
    resp = execute(commitTx);

    assertEquals(204, resp.getStatusLine().getStatusCode());

    /* it must exist after commit */
    client = createClient();
    final HttpGet getObjCommitted = new HttpGet(serverAddress + objectInTxCommit);
    final GraphStore graphStoreAfterCommit = getGraphStore(getObjCommitted);
    assertTrue("The inserted triple does not exist after the transaction has committed",
            graphStoreAfterCommit.contains(ANY, ANY, DC_TITLE.asNode(), createPlainLiteral(title).asNode()));

}

From source file:org.fcrepo.integration.http.api.FedoraVersioningIT.java

@Test
public void testMementoExternalReference() throws Exception {
    createVersionedContainer(id);/*from w  w w  .j a  va 2 s  .c o m*/

    final String pid = getRandomUniqueId();
    final String resource = serverAddress + pid;
    createObjectAndClose(pid);

    final HttpPatch updateObjectGraphMethod = patchObjMethod(id);
    updateObjectGraphMethod.addHeader(CONTENT_TYPE, "application/sparql-update");
    updateObjectGraphMethod.setEntity(new StringEntity(
            "INSERT {" + " <> <http://pcdm.org/models#hasMember> <" + resource + "> } WHERE {}"));
    executeAndClose(updateObjectGraphMethod);

    // create memento
    final String mementoUri = createContainerMementoWithBody(subjectUri, MEMENTO_DATETIME);

    // Remove the referencing resource
    assertEquals("Expected delete to succeed", NO_CONTENT.getStatusCode(), getStatus(new HttpDelete(resource)));

    // Ensure that the resource reference is gone
    try (final CloseableHttpResponse getResponse1 = execute(new HttpGet(subjectUri));
            final CloseableDataset dataset = getDataset(getResponse1);) {
        final DatasetGraph graph = dataset.asDatasetGraph();
        assertFalse("Expected NOT to have resource: " + graph,
                graph.contains(ANY, ANY, createURI("http://pcdm.org/models#hasMember"), createURI(resource)));
    }

    try (final CloseableHttpResponse getResponse1 = execute(new HttpGet(mementoUri));
            final CloseableDataset dataset = getDataset(getResponse1);) {

        final DatasetGraph graph = dataset.asDatasetGraph();

        // Ensure that the resource reference is still in memento
        assertTrue("Expected resource NOT found: " + graph,
                graph.contains(ANY, ANY, createURI("http://pcdm.org/models#hasMember"), createURI(resource)));

        // Ensure that the subject of the memento is the original reosurce
        assertTrue("Subjects should be the original resource, not the memento: " + graph,
                !graph.contains(ANY, createURI(mementoUri), ANY, ANY));
    }
}

From source file:org.fcrepo.integration.http.api.FedoraVersioningIT.java

@Test
public void testDescriptionMementoReference() throws Exception {
    // Create binary with description referencing other resource
    createVersionedBinary(id);//from   w  ww.  j a  v  a  2 s .  co  m

    final String referencedPid = getRandomUniqueId();
    final String referencedResource = serverAddress + referencedPid;
    createObjectAndClose(referencedPid);

    final String metadataId = id + "/fcr:metadata";
    final String metadataUri = serverAddress + metadataId;

    final String relation = "http://purl.org/dc/elements/1.1/relation";
    final HttpPatch updateObjectGraphMethod = patchObjMethod(metadataId);
    updateObjectGraphMethod.addHeader(CONTENT_TYPE, "application/sparql-update");
    updateObjectGraphMethod.setEntity(
            new StringEntity("INSERT {" + " <> <" + relation + "> <" + referencedResource + "> } WHERE {}"));
    executeAndClose(updateObjectGraphMethod);

    // Create memento
    final String mementoUri = createMemento(subjectUri, null, null, null);
    assertMementoUri(mementoUri, subjectUri);

    // Delete referenced resource
    assertEquals("Expected delete to succeed", NO_CONTENT.getStatusCode(),
            getStatus(new HttpDelete(referencedResource)));

    final Node originalBinaryNode = createURI(serverAddress + id);
    // Ensure that the resource reference is gone
    try (final CloseableHttpResponse getResponse1 = execute(new HttpGet(metadataUri));
            final CloseableDataset dataset = getDataset(getResponse1);) {
        final DatasetGraph graph = dataset.asDatasetGraph();
        assertFalse("Expected NOT to have resource: " + graph,
                graph.contains(ANY, originalBinaryNode, createURI(relation), createURI(referencedResource)));
    }

    final String descMementoUrl = mementoUri.replace(FCR_VERSIONS, "fcr:metadata/fcr:versions");
    // Ensure that the resource reference is still in memento
    try (final CloseableHttpResponse getResponse1 = execute(new HttpGet(descMementoUrl));
            final CloseableDataset dataset = getDataset(getResponse1);) {
        final DatasetGraph graph = dataset.asDatasetGraph();
        assertTrue("Expected resource NOT found: " + graph,
                graph.contains(ANY, originalBinaryNode, createURI(relation), createURI(referencedResource)));

        // Verify that described by link persists and there is only one
        final Iterator<Quad> describedIt = graph.find(ANY, originalBinaryNode, DESCRIBED_BY.asNode(), ANY);
        assertEquals(metadataUri, describedIt.next().getObject().getURI());
        assertFalse(describedIt.hasNext());
    }
}

From source file:org.fcrepo.integration.http.api.FedoraVersioningIT.java

@Test
public void testPatchOnMemento() throws Exception {
    createVersionedContainer(id);/*from   ww w.j av a  2 s  .co m*/

    final String mementoUri = createContainerMementoWithBody(subjectUri, MEMENTO_DATETIME);
    final HttpPatch patch = new HttpPatch(mementoUri);
    patch.addHeader(CONTENT_TYPE, "application/sparql-update");
    patch.setEntity(new StringEntity("INSERT DATA { <> <" + title.getURI() + "> \"Memento title\" } "));

    // status 405: PATCH on memento is not allowed.
    assertEquals(405, getStatus(patch));
}

From source file:org.fcrepo.integration.http.api.FedoraVersioningIT.java

private static void patchLiteralProperty(final String url, final String predicate, final String literal)
        throws IOException {
    final HttpPatch updateObjectGraphMethod = new HttpPatch(url);
    updateObjectGraphMethod.addHeader(CONTENT_TYPE, "application/sparql-update");
    updateObjectGraphMethod
            .setEntity(new StringEntity("INSERT DATA { <> <" + predicate + "> \"" + literal + "\" } "));
    assertEquals(NO_CONTENT.getStatusCode(), getStatus(updateObjectGraphMethod));
}

From source file:org.onosproject.protocol.rest.ctl.RestSBControllerImpl.java

@Override
public boolean patch(DeviceId device, String request, InputStream payload, String mediaType) {
    try {//from   w  ww  .  j  a va2s  .  c  om
        log.debug("Url request {} ", getUrlString(device, request));
        HttpPatch httprequest = new HttpPatch(getUrlString(device, request));
        if (deviceMap.get(device).username() != null) {
            String pwd = deviceMap.get(device).password() == null ? ""
                    : COLON + deviceMap.get(device).password();
            String userPassword = deviceMap.get(device).username() + pwd;
            String base64string = Base64.getEncoder()
                    .encodeToString(userPassword.getBytes(StandardCharsets.UTF_8));
            httprequest.addHeader(AUTHORIZATION_PROPERTY, BASIC_AUTH_PREFIX + base64string);
        }
        if (payload != null) {
            StringEntity input = new StringEntity(IOUtils.toString(payload, StandardCharsets.UTF_8));
            input.setContentType(mediaType);
            httprequest.setEntity(input);
        }
        CloseableHttpClient httpClient;
        if (deviceMap.containsKey(device) && deviceMap.get(device).protocol().equals(HTTPS)) {
            httpClient = getApacheSslBypassClient();
        } else {
            httpClient = HttpClients.createDefault();
        }
        int responseStatusCode = httpClient.execute(httprequest).getStatusLine().getStatusCode();
        return checkStatusCode(responseStatusCode);
    } catch (IOException | NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        log.error("Cannot do PATCH {} request on device {}", request, device, e);
    }
    return false;
}

From source file:org.openrepose.nodeservice.httpcomponent.RequestProxyServiceImpl.java

@Override
public ServiceClientResponse patch(String baseUri, String path, Map<String, String> headers, byte[] body) {
    HttpPatch patch = new HttpPatch(StringUriUtilities.appendPath(baseUri, path));
    setHeaders(patch, headers);//w  w w  .  ja  va  2  s  .  co m
    if (body != null && body.length > 0) {
        patch.setEntity(new InputStreamEntity(new ByteArrayInputStream(body), body.length));
    }
    return execute(patch);
}