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

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

Introduction

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

Prototype

public HttpPatch(final String uri) 

Source Link

Usage

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

License:asdf

private int patchWithSparql(final String path, final String sparqlUpdate) {
    try {/*  w  ww.  ja  v a2 s. c  om*/
        final HttpPatch patch = new HttpPatch(serverAddress + path);
        patch.addHeader(CONTENT_TYPE, "application/sparql-update");
        patch.setEntity(new StringEntity(sparqlUpdate));
        final CloseableHttpResponse r = client.execute(patch);
        final int code = r.getStatusLine().getStatusCode();
        r.close();
        return code;
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}

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  w w w .j av  a2 s.  c o m*/

    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();//  w w  w  .ja v  a2s.c  om
    }

    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/*  w  w  w  .j a v  a 2 s  . c  om*/
 */
@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 testPatchOnTimeMapContainer() throws Exception {
    createVersionedContainer(id);/*from   ww w  .j av  a 2  s.  com*/

    // status 405: PATCH On LPDCv is disallowed.
    assertEquals(405, getStatus(new HttpPatch(serverAddress + id + "/" + FCR_VERSIONS)));
}

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

@Test
public void testPatchOnMemento() throws Exception {
    createVersionedContainer(id);/*from  w  ww  . j  a  v  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//w w w . ja v  a  2s. co m
            .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 {// ww w .  j av  a  2  s.  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);//from   w w w  .  j av a  2s . co m
    if (body != null && body.length > 0) {
        patch.setEntity(new InputStreamEntity(new ByteArrayInputStream(body), body.length));
    }
    return execute(patch);
}

From source file:org.rapidoid.http.HttpClient.java

public Future<byte[]> request(String verb, String uri, Map<String, String> headers, Map<String, String> data,
        Map<String, String> files, byte[] body, String contentType, Callback<byte[]> callback,
        boolean fullResponse) {

    headers = U.safe(headers);//from   ww w . ja v a2 s  .  c om
    data = U.safe(data);
    files = U.safe(files);

    HttpRequestBase req;
    boolean canHaveBody = false;

    if ("GET".equalsIgnoreCase(verb)) {
        req = new HttpGet(uri);
    } else if ("DELETE".equalsIgnoreCase(verb)) {
        req = new HttpDelete(uri);
    } else if ("OPTIONS".equalsIgnoreCase(verb)) {
        req = new HttpOptions(uri);
    } else if ("HEAD".equalsIgnoreCase(verb)) {
        req = new HttpHead(uri);
    } else if ("TRACE".equalsIgnoreCase(verb)) {
        req = new HttpTrace(uri);
    } else if ("POST".equalsIgnoreCase(verb)) {
        req = new HttpPost(uri);
        canHaveBody = true;
    } else if ("PUT".equalsIgnoreCase(verb)) {
        req = new HttpPut(uri);
        canHaveBody = true;
    } else if ("PATCH".equalsIgnoreCase(verb)) {
        req = new HttpPatch(uri);
        canHaveBody = true;
    } else {
        throw U.illegalArg("Illegal HTTP verb: " + verb);
    }

    for (Entry<String, String> e : headers.entrySet()) {
        req.addHeader(e.getKey(), e.getValue());
    }

    if (canHaveBody) {
        HttpEntityEnclosingRequestBase entityEnclosingReq = (HttpEntityEnclosingRequestBase) req;

        if (body != null) {

            NByteArrayEntity entity = new NByteArrayEntity(body);

            if (contentType != null) {
                entity.setContentType(contentType);
            }

            entityEnclosingReq.setEntity(entity);
        } else {

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();

            for (Entry<String, String> entry : files.entrySet()) {
                String filename = entry.getValue();
                File file = IO.file(filename);
                builder = builder.addBinaryBody(entry.getKey(), file, ContentType.DEFAULT_BINARY, filename);
            }

            for (Entry<String, String> entry : data.entrySet()) {
                builder = builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.DEFAULT_TEXT);
            }

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            try {
                builder.build().writeTo(stream);
            } catch (IOException e) {
                throw U.rte(e);
            }

            byte[] bytes = stream.toByteArray();
            NByteArrayEntity entity = new NByteArrayEntity(bytes, ContentType.MULTIPART_FORM_DATA);

            entityEnclosingReq.setEntity(entity);
        }
    }

    Log.debug("Starting HTTP request", "request", req.getRequestLine());

    return execute(client, req, callback, fullResponse);
}