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:cuanto.api.CuantoConnector.java

/**
 * Creates a new TestRun on the Cuanto server using the values provided. A TestRun represents tests that were
 * executed together. The projectKey will be assigned the same projectKey as this CuantoConnector. The testRun
 * passed in will have it's id value assigned to the server-assigned ID of the created TestRun.
 *
 * @param testRun The test run to create.
 * @return The server-assigned ID of the created TestRun.
 *//* w  w  w. j  a va  2s .  c o  m*/
public Long addTestRun(TestRun testRun) {
    testRun.setProjectKey(getProjectKey());
    PostMethod post = (PostMethod) getHttpMethod(HTTP_POST, getCuantoUrl() + "/api/addTestRun");
    try {
        post.setRequestEntity(new StringRequestEntity(testRun.toJSON(), "application/json", null));
        int httpStatus = getHttpClient().executeMethod(post);
        if (httpStatus == HttpStatus.SC_CREATED) {
            TestRun created = TestRun.fromJSON(getResponseBodyAsString(post));
            testRun.setProjectKey(this.projectKey);
            testRun.setId(created.getId());
            return created.getId();
        } else {
            throw new RuntimeException("Adding the TestRun failed with HTTP status code " + httpStatus + ": \n"
                    + getResponseBodyAsString(post));
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ParseException e) {
        throw new RuntimeException("Error parsing server response", e);
    }
}

From source file:com.sun.faban.harness.util.DeployTask.java

/**
 * Executes the Faban deployment task./*from  ww  w.j  a  va 2s  .c om*/
 * @throws BuildException If there is an
 */
public void execute() throws BuildException {
    try {
        // First check the jar file and name
        if (jarFile == null)
            throw new BuildException("jar attribute missing for target deploy.");
        if (!jarFile.isFile())
            throw new BuildException("jar file not found.");
        String jarName = jarFile.getName();
        if (!jarName.endsWith(".jar"))
            throw new BuildException("Jar file name must end with \".jar\"");
        jarName = jarName.substring(0, jarName.length() - 4);
        if (jarName.indexOf('.') > -1)
            throw new BuildException("Jar file name must not have any " + "dots except ending with \".jar\"");

        // Prepare the parts for the request.
        ArrayList<Part> params = new ArrayList<Part>(4);
        if (user != null)
            params.add(new StringPart("user", user));
        if (password != null)
            params.add(new StringPart("password", password));
        if (clearConfig)
            params.add(new StringPart("clearconfig", "true"));
        params.add(new FilePart("jarfile", jarFile));
        Part[] parts = new Part[params.size()];
        parts = params.toArray(parts);

        // Prepare the post method.
        PostMethod post = new PostMethod(target + "/deploy");

        // Ensure text/plain is the only accept header.
        post.removeRequestHeader("Accept");
        post.setRequestHeader("Accept", "text/plain");
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        // Execute the multi-part post method.
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(post);
        StringBuilder b = new StringBuilder();
        InputStream respBody = post.getResponseBodyAsStream();
        byte[] readBuffer = new byte[8192];
        for (;;) {
            int size = respBody.read(readBuffer);
            if (size == -1)
                break;
            b.append(new String(readBuffer, 0, size));
        }
        String response = b.toString();

        // Check status.
        if (status == HttpStatus.SC_CONFLICT) {
            handleErrorFlush(response);
            throw new BuildException(
                    "Benchmark to deploy is currently " + "run or queued to be run. Please clear run queue "
                            + "of this benchmark before deployment");
        } else if (status == HttpStatus.SC_NOT_ACCEPTABLE) {
            handleErrorFlush(response);
            throw new BuildException(
                    "Benchmark deploy name or deploy " + "file invalid. Deploy file may contain errors. Name "
                            + "must have no '.' and file must have the " + "'.jar' extensions.");
        } else if (status != HttpStatus.SC_CREATED) {
            handleOutput(response);
            throw new BuildException(
                    "Faban responded with status code " + status + ". Status code 201 (SC_CREATED) expected.");
        }
    } catch (FileNotFoundException e) {
        throw new BuildException(e);
    } catch (HttpException e) {
        throw new BuildException(e);
    } catch (IOException e) {
        throw new BuildException(e);
    }
}

From source file:com.zimbra.cs.store.triton.TritonBlobStoreManager.java

@Override
protected void writeStreamToStore(InputStream in, long actualSize, Mailbox mbox, String locator)
        throws IOException, ServiceException {
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    if (actualSize < 0) {
        throw ServiceException.FAILURE(
                "Must use resumable upload (i.e. StoreManager.newIncomingBlob()) if size is unknown", null);
    } else if (actualSize == 0) {
        ZimbraLog.store.info("storing empty blob");
        return; //don't bother writing empty file to remote
    }//from   w  w  w .  j a  v a  2s  . c om
    PostMethod post = new PostMethod(blobApiUrl);
    ZimbraLog.store.info("posting to %s with locator %s", post.getURI(), locator);
    try {
        HttpClientUtil.addInputStreamToHttpMethod(post, in, actualSize, "application/octet-stream");
        post.addRequestHeader(TritonHeaders.CONTENT_LENGTH, actualSize + "");
        post.addRequestHeader(TritonHeaders.OBJECTID, locator);
        post.addRequestHeader(TritonHeaders.HASH_TYPE, hashType.toString());
        int statusCode = HttpClientUtil.executeMethod(client, post);
        if (statusCode == HttpStatus.SC_CREATED) {
            return;
        } else {
            ZimbraLog.store.error("failed with code %d response: %s", statusCode,
                    post.getResponseBodyAsString());
            throw ServiceException.FAILURE("unable to store blob " + statusCode + ":" + post.getStatusText(),
                    null);
        }
    } finally {
        post.releaseConnection();
    }
}

From source file:com.github.maven.plugin.client.impl.GithubClientImpl.java

public void upload(String artifactName, File file, String description, String repositoryUrl) {
    assertNotNull(artifactName, "artifactName");
    assertNotNull(file, "file");
    assertNotNull(repositoryUrl, "repositoryUrl");
    assertStartsWith(repositoryUrl, GITHUB_REPOSITORY_URL_PREFIX, "repositoryUrl");

    PostMethod githubPost = new PostMethod(toRepositoryDownloadUrl(repositoryUrl));
    githubPost.setRequestBody(new NameValuePair[] { new NameValuePair("login", login),
            new NameValuePair("token", token), new NameValuePair("file_name", artifactName),
            new NameValuePair("file_size", String.valueOf(file.length())),
            new NameValuePair("description", description == null ? "" : description) });

    try {/*ww  w .ja  v a 2s.  c o  m*/

        int response = httpClient.executeMethod(githubPost);

        if (response == HttpStatus.SC_OK) {

            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = mapper.readValue(githubPost.getResponseBodyAsString(), JsonNode.class);

            PostMethod s3Post = new PostMethod(GITHUB_S3_URL);

            Part[] parts = { new StringPart("Filename", artifactName),
                    new StringPart("policy", node.path("policy").getTextValue()),
                    new StringPart("success_action_status", "201"),
                    new StringPart("key", node.path("path").getTextValue()),
                    new StringPart("AWSAccessKeyId", node.path("accesskeyid").getTextValue()),
                    new StringPart("Content-Type", node.path("mime_type").getTextValue()),
                    new StringPart("signature", node.path("signature").getTextValue()),
                    new StringPart("acl", node.path("acl").getTextValue()), new FilePart("file", file) };

            MultipartRequestEntity partEntity = new MultipartRequestEntity(parts, s3Post.getParams());
            s3Post.setRequestEntity(partEntity);

            int s3Response = httpClient.executeMethod(s3Post);
            if (s3Response != HttpStatus.SC_CREATED) {
                throw new GithubException(
                        "Cannot upload " + file.getName() + " to repository " + repositoryUrl);
            }

            s3Post.releaseConnection();
        } else if (response == HttpStatus.SC_NOT_FOUND) {
            throw new GithubRepositoryNotFoundException("Cannot found repository " + repositoryUrl);
        } else if (response == HttpStatus.SC_UNPROCESSABLE_ENTITY) {
            throw new GithubArtifactAlreadyExistException(
                    "File " + artifactName + " already exist in " + repositoryUrl + " repository");
        } else {
            throw new GithubException("Error " + HttpStatus.getStatusText(response));
        }
    } catch (IOException e) {
        throw new GithubException(e);
    }

    githubPost.releaseConnection();
}

From source file:com.gisgraphy.rest.RestClient.java

private int executeAndCheckStatusCode(HttpMethod httpMethod)
        throws IOException, HttpException, RestClientException {
    int statusCode = httpClient.executeMethod(httpMethod);
    if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
            && statusCode != HttpStatus.SC_NO_CONTENT) {
        throw new RestClientException(statusCode, "restclient exception for " + httpMethod.getURI() + " : "
                + statusCode + ", " + HttpStatus.getStatusText(statusCode));
    }//from  ww w .  jav a  2s . c om
    return statusCode;
}

From source file:fedora.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
 */// www  .j a v a  2  s  .  c  o  m
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) {
            LOG.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:gobblin.kafka.schemareg.LiKafkaSchemaRegistry.java

/**
 * Register a schema to the Kafka schema registry
 *
 * @param schema//from   w  w  w  .  j av a2  s  .  c  om
 * @return schema ID of the registered schema
 * @throws SchemaRegistryException if registration failed
 */
public synchronized MD5Digest register(Schema schema) throws SchemaRegistryException {
    LOG.info("Registering schema " + schema.toString());

    PostMethod post = new PostMethod(url);
    post.addParameter("schema", schema.toString());

    HttpClient httpClient = this.borrowClient();
    try {
        LOG.debug("Loading: " + post.getURI());
        int statusCode = httpClient.executeMethod(post);
        if (statusCode != HttpStatus.SC_CREATED) {
            throw new SchemaRegistryException("Error occurred while trying to register schema: " + statusCode);
        }

        String response;
        response = post.getResponseBodyAsString();
        if (response != null) {
            LOG.info("Received response " + response);
        }

        String schemaKey;
        Header[] headers = post.getResponseHeaders(SCHEMA_ID_HEADER_NAME);
        if (headers.length != 1) {
            throw new SchemaRegistryException(
                    "Error reading schema id returned by registerSchema call: headers.length = "
                            + headers.length);
        } else if (!headers[0].getValue().startsWith(SCHEMA_ID_HEADER_PREFIX)) {
            throw new SchemaRegistryException(
                    "Error parsing schema id returned by registerSchema call: header = "
                            + headers[0].getValue());
        } else {
            LOG.info("Registered schema successfully");
            schemaKey = headers[0].getValue().substring(SCHEMA_ID_HEADER_PREFIX.length());
        }
        MD5Digest schemaId = MD5Digest.fromString(schemaKey);
        return schemaId;
    } catch (Throwable t) {
        throw new SchemaRegistryException(t);
    } finally {
        post.releaseConnection();
        this.httpClientPool.returnObject(httpClient);
    }
}

From source file:com.kodokux.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  .  j a v a2 s  . c  o  m
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_FORBIDDEN:
        String message = getErrorMessage(method);
        if (message.contains("API rate limit exceeded")) {
            throw new GithubRateLimitExceededException(message);
        }
        throw new GithubAuthenticationException("Request response: " + message);
    default:
        throw new GithubStatusCodeException(code + ": " + getErrorMessage(method), code);
    }
}

From source file:gobblin.metrics.kafka.KafkaAvroSchemaRegistry.java

/**
 * Register a schema to the Kafka schema registry
 *
 * @param schema//from  w ww  .j  a v  a2 s . c o m
 * @return schema ID of the registered schema
 * @throws SchemaRegistryException if registration failed
 */
@Override
public synchronized String register(Schema schema) throws SchemaRegistryException {
    LOG.info("Registering schema " + schema.toString());

    PostMethod post = new PostMethod(url);
    post.addParameter("schema", schema.toString());

    HttpClient httpClient = this.borrowClient();
    try {
        LOG.debug("Loading: " + post.getURI());
        int statusCode = httpClient.executeMethod(post);
        if (statusCode != HttpStatus.SC_CREATED) {
            throw new SchemaRegistryException("Error occurred while trying to register schema: " + statusCode);
        }

        String response;
        response = post.getResponseBodyAsString();
        if (response != null) {
            LOG.info("Received response " + response);
        }

        String schemaKey;
        Header[] headers = post.getResponseHeaders(SCHEMA_ID_HEADER_NAME);
        if (headers.length != 1) {
            throw new SchemaRegistryException(
                    "Error reading schema id returned by registerSchema call: headers.length = "
                            + headers.length);
        } else if (!headers[0].getValue().startsWith(SCHEMA_ID_HEADER_PREFIX)) {
            throw new SchemaRegistryException(
                    "Error parsing schema id returned by registerSchema call: header = "
                            + headers[0].getValue());
        } else {
            LOG.info("Registered schema successfully");
            schemaKey = headers[0].getValue().substring(SCHEMA_ID_HEADER_PREFIX.length());
        }

        return schemaKey;
    } catch (Throwable t) {
        throw new SchemaRegistryException(t);
    } finally {
        post.releaseConnection();
        this.httpClientPool.returnObject(httpClient);
    }
}

From source file:com.cerema.cloud2.lib.resources.files.CopyRemoteFileOperation.java

protected boolean isSuccess(int status) {
    return status == HttpStatus.SC_CREATED || status == HttpStatus.SC_NO_CONTENT;
}