Example usage for org.apache.commons.httpclient HttpStatus SC_CREATED

List of usage examples for org.apache.commons.httpclient HttpStatus SC_CREATED

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_CREATED.

Prototype

int SC_CREATED

To view the source code for org.apache.commons.httpclient HttpStatus SC_CREATED.

Click Source Link

Document

<tt>201 Created</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:org.eclipse.lyo.testsuite.oslcv2.CreationAndUpdateBaseTests.java

private HttpResponse createResource(String contentType, String accept, String createContent)
        throws IOException {
    HttpResponse resp = OSLCUtils.postDataToUrl(currentUrl, basicCreds, accept, contentType, createContent,
            headers);/*w ww .  j  a v  a2 s  .  c om*/

    // Assert the response gave a 201 Created
    EntityUtils.consume(resp.getEntity());
    assertEquals(HttpStatus.SC_CREATED, resp.getStatusLine().getStatusCode());
    return resp;
}

From source file:org.eclipse.lyo.testsuite.oslcv2.OAuthTests.java

@Test
public void oAuthAccessTokenReceived() throws OAuthException, IOException, URISyntaxException {
    OAuthClient client = new OAuthClient(new HttpClient3(new TestHttpClientPool()));
    OAuthAccessor accessor = new OAuthAccessor(consumer);
    client.getRequestToken(accessor);//from  ww  w  . ja va  2 s .com

    HttpResponse resp = OSLCUtils.getResponseFromUrl("", setupBaseUrl, basicCreds, OSLCConstants.CT_XML);
    EntityUtils.consume(resp.getEntity());

    resp = OSLCUtils.postDataToUrl(provider.userAuthorizationURL + "?oauth_token=" + accessor.requestToken,
            basicCreds, "", "application/x-www-form-urlencoded",
            postParameters + "&oauth_token=" + accessor.requestToken, headers);
    EntityUtils.consume(resp.getEntity());
    int sc = resp.getStatusLine().getStatusCode();
    assertTrue(sc == HttpStatus.SC_OK || sc == HttpStatus.SC_CREATED);
    try {
        // Trade the request token for an access token.
        client.getAccessToken(accessor, OAuthMessage.POST, null);
    } catch (OAuthProblemException e) {
        Assert.fail("Exception while requesting access token: " + e.getMessage());
    }
    // Make sure we got an access token that is not empty.
    assertNotNull(accessor.accessToken);
    assertFalse(accessor.accessToken.isEmpty());
}

From source file:org.fao.geonet.doi.client.DoiClient.java

/**
 * See https://support.datacite.org/docs/mds-api-guide#section-register-metadata
 *///from  w w  w  . ja v  a  2  s . co m
private void create(String url, String body, String contentType, String entity) throws DoiClientException {

    ClientHttpResponse httpResponse = null;
    HttpPost postMethod = null;

    try {
        Log.debug(LOGGER_NAME, "   -- URL: " + url);

        postMethod = new HttpPost(url);

        ((HttpUriRequest) postMethod)
                .addHeader(new BasicHeader("Content-Type", contentType + ";charset=UTF-8"));
        Log.debug(LOGGER_NAME, "   -- Request body: " + body);

        StringEntity requestEntity = new StringEntity(body, contentType, "UTF-8");

        postMethod.setEntity(requestEntity);

        httpResponse = requestFactory.execute(postMethod, new UsernamePasswordCredentials(username, password),
                AuthScope.ANY);
        int status = httpResponse.getRawStatusCode();

        Log.debug(LOGGER_NAME, "   -- Request status code: " + status);

        if (status != HttpStatus.SC_CREATED) {
            String message = String.format("Failed to create '%s' with '%s'. Status is %d. Error is %s.", url,
                    body, status, httpResponse.getStatusText());

            Log.info(LOGGER_NAME, message);
            throw new DoiClientException(message);
        } else {
            Log.info(LOGGER_NAME, String.format("DOI metadata created at %s.", url));
        }
    } catch (Exception ex) {
        Log.error(LOGGER_NAME, "   -- Error (exception): " + ex.getMessage());
        throw new DoiClientException(ex.getMessage());

    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
        // Release the connection.
        IOUtils.closeQuietly(httpResponse);
    }
}

From source file:org.fcrepo.client.FedoraClient.java

/**
 * Upload the given file to Fedora's upload interface via HTTP POST.
 *
 * @return the temporary id which can then be passed to API-M requests as a
 *         URL. It will look like uploaded://123
 *//*w  w w .  ja  v a 2s .com*/
public String uploadFile(File file) throws IOException {
    PostMethod post = null;
    try {
        // prepare the post method
        post = new PostMethod(getUploadURL());
        post.setDoAuthentication(true);
        post.getParams().setParameter("Connection", "Keep-Alive");

        // chunked encoding is not required by the Fedora server,
        // but makes uploading very large files possible
        post.setContentChunked(true);

        // add the file part
        Part[] parts = { new FilePart("file", file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        // execute and get the response
        int responseCode = getHttpClient().executeMethod(post);
        String body = null;
        try {
            body = post.getResponseBodyAsString();
        } catch (Exception e) {
            logger.warn("Error reading response body", e);
        }
        if (body == null) {
            body = "[empty response body]";
        }
        body = body.trim();
        if (responseCode != HttpStatus.SC_CREATED) {
            throw new IOException("Upload failed: " + HttpStatus.getStatusText(responseCode) + ": "
                    + replaceNewlines(body, " "));
        } else {
            return replaceNewlines(body, "");
        }
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:org.hydracache.client.http.HttpHydraCacheClient.java

/**
 * Validate the response code/*w  w w.  j a va 2  s.  c  o  m*/
 * 
 * @param executeMethod
 * @throws IOException
 */
private void validateResponseCode(int rc) throws IOException {
    if (rc != HttpStatus.SC_OK && rc != HttpStatus.SC_CREATED)
        throw new IOException("Error HTTP response received: " + rc);
}

From source file:org.hydracache.client.partition.Messager.java

private void registerDefaultHandlers() {
    transport.registerHandler(HttpStatus.SC_CONFLICT, new ConflictStatusHandler());
    transport.registerHandler(HttpStatus.SC_OK, new DefaultResponseMessageHandler());
    transport.registerHandler(HttpStatus.SC_CREATED, new DefaultResponseMessageHandler());
}

From source file:org.hydracache.client.transport.DefaultResponseMessageHandler.java

@Override
public ResponseMessage accept(int responseCode, byte[] responseBody) throws Exception {
    ResponseMessage responseMessage = null;
    if (responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_CREATED) {
        responseMessage = new ResponseMessage(true);
        responseMessage.setResponseBody(responseBody);
    }//w w w.j  a  v a2 s . c o m
    return responseMessage;
}

From source file:org.jetbrains.plugins.github.api.GithubApiUtil.java

private static void checkStatusCode(@NotNull HttpMethod method) throws IOException {
    int code = method.getStatusCode();
    switch (code) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
    case HttpStatus.SC_NO_CONTENT:
        return;/*from   w  w  w.  ja v a  2  s. c o m*/
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_FORBIDDEN:
        throw new GithubAuthenticationException("Request response: " + getErrorMessage(method));
    default:
        throw new GithubStatusCodeException(code + ": " + getErrorMessage(method), code);
    }
}

From source file:org.ldp4j.server.frontend.ServerFrontendITest.java

/**
 * Enforce http://tools.ietf.org/html/rfc7232#section-2.2:
 * if the clock in the request is ahead of the clock of the origin
 * server (e.g., I request from Spain the update of a resource held in USA)
 * the last-modified data should be changed to that of the request and not
 * a generated date from the origin server
 *//* w  ww  .j  a v a 2  s.  c om*/
@Test
@Category({ HappyPath.class })
@OperateOnDeployment(DEPLOYMENT)
public void testProperLastModified(@ArquillianResource final URL url) throws Exception {
    LOGGER.info("Started {}", testName.getMethodName());
    HELPER.base(url);
    HELPER.setLegacy(false);

    long now = System.currentTimeMillis();
    Date clientPostDate = new Date(now - 24 * 60 * 60 * 1000);
    Date clientPutDate = new Date(now + 24 * 60 * 60 * 1000);

    HttpPost post = HELPER.newRequest(MyApplication.ROOT_PERSON_CONTAINER_PATH, HttpPost.class);
    post.setEntity(new StringEntity(TEST_SUITE_BODY, ContentType.create("text/turtle", "UTF-8")));
    post.setHeader("Date", DateUtils.formatDate(clientPostDate));

    Metadata postResponse = HELPER.httpRequest(post);
    assertThat(postResponse.status, equalTo(HttpStatus.SC_CREATED));

    String path = HELPER.relativize(postResponse.location);
    HttpGet get = HELPER.newRequest(path, HttpGet.class);

    Metadata getResponse = HELPER.httpRequest(get);
    assertThat(DateUtils.parseDate(getResponse.lastModified).after(clientPostDate), equalTo(true));

    HttpPut put = HELPER.newRequest(path, HttpPut.class);
    put.setEntity(new StringEntity(getResponse.body, ContentType.create("text/turtle", "UTF-8")));
    put.setHeader(HttpHeaders.IF_MATCH, getResponse.etag);
    put.setHeader("Date", DateUtils.formatDate(clientPutDate));

    Metadata putResponse = HELPER.httpRequest(put);
    Date lastModified = DateUtils.parseDate(putResponse.lastModified);
    assertThat(lastModified.getTime(), equalTo(trunk(clientPutDate.getTime())));

    LOGGER.info("Completed {}", testName.getMethodName());
}

From source file:org.loadosophia.client.LoadosophiaAPIClient.java

public String startOnline() throws IOException {
    String uri = address + "api/active/receiver/start/";
    LinkedList<Part> partsList = new LinkedList<Part>();
    partsList.add(new StringPart("token", token));
    partsList.add(new StringPart("projectKey", project));
    partsList.add(new StringPart("title", title));
    String[] res = multipartPost(partsList, uri, HttpStatus.SC_CREATED);
    JSONObject obj = JSONObject.fromObject(res[0]);
    return address + "gui/active/" + obj.optString("OnlineID", "N/A") + "/";
}