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.apache.excalibur.source.factories.HTTPClientSource.java

/**
 * Method to update whether a referenced resource exists, after
 * executing a particular {@link HttpMethod}.
 *
 * <p>REVISIT: exists() would be better called canRead()
 * or similar, as a resource can exist but not be readable.</p>
 *
 * @param method {@link HttpMethod} executed.
 *//*  www  . java2s.c  o m*/
private void updateExists(final HttpMethod method) {
    final int response = method.getStatusCode();

    // The following returns true, if the user can successfully get
    // an InputStream without receiving errors? ie. if we receive a
    // HTTP 200 (OK), 201 (CREATED), 206 (PARTIAL CONTENT)

    // REVISIT(MC): need a special way to handle 304 (NOT MODIFIED)
    // 204 & 205 in the future

    // resource does not exist if HttpClient returns a 404 or a 410
    this.m_exists = (response == HttpStatus.SC_OK || response == HttpStatus.SC_CREATED
            || response == HttpStatus.SC_PARTIAL_CONTENT);
}

From source file:org.apache.gobblin.kafka.schemareg.LiKafkaSchemaRegistry.java

/**
 * Register a schema to the Kafka schema registry
 *
 * @param schema/*  w w w.  j av a 2  s. com*/
 * @param post
 * @return schema ID of the registered schema
 * @throws SchemaRegistryException if registration failed
 */
public synchronized MD5Digest register(Schema schema, PostMethod post) throws SchemaRegistryException {

    // Change namespace if override specified
    if (this.namespaceOverride.isPresent()) {
        schema = AvroUtils.switchNamespace(schema, this.namespaceOverride.get());
    }

    LOG.info("Registering schema " + schema.toString());

    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:org.apache.gobblin.metrics.kafka.KafkaAvroSchemaRegistry.java

/**
 * Register a schema to the Kafka schema registry
 *
 * @param schema/*from w w  w  .j  a v  a2s.  c  o  m*/
 * @return schema ID of the registered schema
 * @throws SchemaRegistryException if registration failed
 */
@Override
public synchronized String register(Schema schema) throws SchemaRegistryException {

    // Change namespace if override specified
    if (this.namespaceOverride.isPresent()) {
        schema = AvroUtils.switchNamespace(schema, this.namespaceOverride.get());
    }

    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:org.apache.manifoldcf.examples.ManifoldCFAPIConnect.java

/** Perform an API PUT operation.
*@param restPath is the URL path of the REST object, starting with "/".
*@param input is the input JSON.//from  w  ww  . j  a  v  a2  s.c  om
*@return the json response.
*/
public String performAPIRawPutOperation(String restPath, String input) throws IOException {
    HttpClient client = new HttpClient();
    PutMethod method = new PutMethod(formURL(restPath));
    method.setRequestHeader("Content-type", "text/plain; charset=UTF-8");
    method.setRequestBody(input);
    int response = client.executeMethod(method);
    byte[] responseData = method.getResponseBody();
    // We presume that the data is utf-8, since that's what the API
    // uses throughout.
    String responseString = new String(responseData, "utf-8");
    if (response != HttpStatus.SC_OK && response != HttpStatus.SC_CREATED)
        throw new IOException("API http error; expected " + HttpStatus.SC_OK + " or " + HttpStatus.SC_CREATED
                + ", saw " + Integer.toString(response) + ": " + responseString);
    return responseString;
}

From source file:org.apache.manifoldcf.examples.ManifoldCFAPIConnect.java

/** Perform an API POST operation.
*@param restPath is the URL path of the REST object, starting with "/".
*@param input is the input JSON./*from w  w  w  . j a va  2 s  .  co m*/
*@return the json response.
*/
public String performAPIRawPostOperation(String restPath, String input) throws IOException {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(formURL(restPath));
    method.setRequestHeader("Content-type", "text/plain; charset=UTF-8");
    method.setRequestBody(input);
    int response = client.executeMethod(method);
    byte[] responseData = method.getResponseBody();
    // We presume that the data is utf-8, since that's what the API
    // uses throughout.
    String responseString = new String(responseData, "utf-8");
    if (response != HttpStatus.SC_CREATED)
        throw new IOException("API http error; expected " + HttpStatus.SC_CREATED + ", saw "
                + Integer.toString(response) + ": " + responseString);
    return responseString;
}

From source file:org.apache.maven.wagon.providers.webdav.AbstractHttpClientWagon.java

private void put(Resource resource, File source, RequestEntityImplementation requestEntityImplementation,
        String url) throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException {

    // preemptive true for put
    client.getParams().setAuthenticationPreemptive(true);

    //Parent directories need to be created before posting
    try {/*from   w ww.  j  a  v  a 2 s . c  om*/
        mkdirs(PathUtils.dirname(resource.getName()));
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);
    }

    PutMethod putMethod = new PutMethod(url);

    firePutStarted(resource, source);

    try {
        putMethod.setRequestEntity(requestEntityImplementation);

        int statusCode;
        try {
            statusCode = execute(putMethod);

        } catch (IOException e) {
            fireTransferError(resource, e, TransferEvent.REQUEST_PUT);

            throw new TransferFailedException(e.getMessage(), e);
        }

        fireTransferDebug(url + " - Status code: " + statusCode);

        // Check that we didn't run out of retries.
        switch (statusCode) {
        // Success Codes
        case HttpStatus.SC_OK: // 200
        case HttpStatus.SC_CREATED: // 201
        case HttpStatus.SC_ACCEPTED: // 202
        case HttpStatus.SC_NO_CONTENT: // 204
            break;

        // handle all redirect even if http specs says " the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user"
        case HttpStatus.SC_MOVED_PERMANENTLY: // 301
        case HttpStatus.SC_MOVED_TEMPORARILY: // 302
        case HttpStatus.SC_SEE_OTHER: // 303
            String relocatedUrl = calculateRelocatedUrl(putMethod);
            fireTransferDebug("relocate to " + relocatedUrl);
            put(resource, source, requestEntityImplementation, relocatedUrl);
            return;

        case SC_NULL: {
            TransferFailedException e = new TransferFailedException("Failed to transfer file: " + url);
            fireTransferError(resource, e, TransferEvent.REQUEST_PUT);
            throw e;
        }

        case HttpStatus.SC_FORBIDDEN:
            fireSessionConnectionRefused();
            throw new AuthorizationException("Access denied to: " + url);

        case HttpStatus.SC_NOT_FOUND:
            throw new ResourceDoesNotExistException("File: " + url + " does not exist");

            //add more entries here
        default: {
            TransferFailedException e = new TransferFailedException(
                    "Failed to transfer file: " + url + ". Return code is: " + statusCode);
            fireTransferError(resource, e, TransferEvent.REQUEST_PUT);
            throw e;
        }
        }

        firePutCompleted(resource, source);
    } finally {
        putMethod.releaseConnection();
    }
}

From source file:org.apache.maven.wagon.providers.webdav.WebDavWagon.java

/**
 * Create directories in server as needed.
 * They are created one at a time until the whole path exists.
 *
 * @param dir path to be created in server from repository basedir
 * @throws IOException/* ww  w .  ja  v a  2  s . com*/
 * @throws HttpException
 * @throws TransferFailedException
 */
protected void mkdirs(String dir) throws IOException {
    Repository repository = getRepository();
    String basedir = repository.getBasedir();

    String baseUrl = repository.getProtocol() + "://" + repository.getHost();
    if (repository.getPort() != WagonConstants.UNKNOWN_PORT) {
        baseUrl += ":" + repository.getPort();
    }

    // create relative path that will always have a leading and trailing slash
    String relpath = FileUtils.normalize(getPath(basedir, dir) + "/");

    PathNavigator navigator = new PathNavigator(relpath);

    // traverse backwards until we hit a directory that already exists (OK/NOT_ALLOWED), or that we were able to
    // create (CREATED), or until we get to the top of the path
    int status = SC_NULL;
    do {
        String url = baseUrl + "/" + navigator.getPath();
        status = doMkCol(url);
        if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED
                || status == HttpStatus.SC_METHOD_NOT_ALLOWED) {
            break;
        }
    } while (navigator.backward());

    // traverse forward creating missing directories
    while (navigator.forward()) {
        String url = baseUrl + "/" + navigator.getPath();
        status = doMkCol(url);
        if (status != HttpStatus.SC_OK && status != HttpStatus.SC_CREATED) {
            throw new IOException("Unable to create collection: " + url + "; status code = " + status);
        }
    }
}

From source file:org.apache.maven.wagon.shared.http.AbstractHttpClientWagon.java

private void put(final InputStream stream, Resource resource, File source)
        throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException {
    String url = getRepository().getUrl();
    String[] parts = StringUtils.split(resource.getName(), "/");
    for (int i = 0; i < parts.length; i++) {
        // TODO: Fix encoding...
        // url += "/" + URLEncoder.encode( parts[i], System.getProperty("file.encoding") );
        url += "/" + URLEncoder.encode(parts[i]);
    }//from www  .  ja v  a2 s.  c o  m

    //Parent directories need to be created before posting
    try {
        mkdirs(PathUtils.dirname(resource.getName()));
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);
    }

    PutMethod putMethod = new PutMethod(url);

    firePutStarted(resource, source);

    try {
        putMethod.setRequestEntity(new RequestEntityImplementation(stream, resource, this, source));

        int statusCode;
        try {
            statusCode = execute(putMethod);
        } catch (IOException e) {
            fireTransferError(resource, e, TransferEvent.REQUEST_PUT);

            throw new TransferFailedException(e.getMessage(), e);
        }

        fireTransferDebug(url + " - Status code: " + statusCode);

        // Check that we didn't run out of retries.
        switch (statusCode) {
        // Success Codes
        case HttpStatus.SC_OK: // 200
        case HttpStatus.SC_CREATED: // 201
        case HttpStatus.SC_ACCEPTED: // 202
        case HttpStatus.SC_NO_CONTENT: // 204
            break;

        case SC_NULL: {
            TransferFailedException e = new TransferFailedException("Failed to transfer file: " + url);
            fireTransferError(resource, e, TransferEvent.REQUEST_PUT);
            throw e;
        }

        case HttpStatus.SC_FORBIDDEN:
            fireSessionConnectionRefused();
            throw new AuthorizationException("Access denied to: " + url);

        case HttpStatus.SC_NOT_FOUND:
            throw new ResourceDoesNotExistException("File: " + url + " does not exist");

            //add more entries here
        default: {
            TransferFailedException e = new TransferFailedException(
                    "Failed to transfer file: " + url + ". Return code is: " + statusCode);
            fireTransferError(resource, e, TransferEvent.REQUEST_PUT);
            throw e;
        }
        }

        firePutCompleted(resource, source);
    } finally {
        putMethod.releaseConnection();
    }
}

From source file:org.apache.sling.maven.bundlesupport.AbstractBundleInstallMojo.java

/**
 * Perform the operation via POST to SlingPostServlet
 * @param targetURL the URL of the Sling instance to post the file to.
 * @param file the file being interacted with the POST to Sling.
 * @throws MojoExecutionException//from  w ww.j av a2  s  .  co m
 */
protected void postToSling(String targetURL, File file) throws MojoExecutionException {

    /* truncate off trailing slash as this has special behaviorisms in
     * the SlingPostServlet around created node name conventions */
    if (targetURL.endsWith("/")) {
        targetURL = targetURL.substring(0, targetURL.length() - 1);
    }
    // append pseudo path after root URL to not get redirected for nothing
    final PostMethod filePost = new PostMethod(targetURL);

    try {

        Part[] parts = new Part[2];
        // Add content type to force the configured mimeType value
        parts[0] = new FilePart("*", new FilePartSource(file.getName(), file), mimeType, null);
        // Add TypeHint to have jar be uploaded as file (not as resource)
        parts[1] = new StringPart("*@TypeHint", "nt:file");

        /* Request JSON response from Sling instead of standard HTML, to
         * reduce the payload size (if the PostServlet supports it). */
        filePost.setRequestHeader("Accept", JSON_MIME_TYPE);
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        int status = getHttpClient().executeMethod(filePost);
        // SlingPostServlet may return 200 or 201 on creation, accept both
        if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED) {
            getLog().info("Bundle installed");
        } else {
            String msg = "Installation failed, cause: " + HttpStatus.getStatusText(status);
            if (failOnError) {
                throw new MojoExecutionException(msg);
            } else {
                getLog().error(msg);
            }
        }
    } catch (Exception ex) {
        throw new MojoExecutionException("Installation on " + targetURL + " failed, cause: " + ex.getMessage(),
                ex);
    } finally {
        filePost.releaseConnection();
    }
}

From source file:org.apache.sling.maven.bundlesupport.AbstractBundleInstallMojo.java

private void createIntermediaryPaths(String targetURL)
        throws HttpException, IOException, MojoExecutionException {
    // extract all intermediate URIs (longest one first)
    List<String> intermediateUris = IntermediateUrisExtractor.extractIntermediateUris(targetURL);

    // 1. go up to the node in the repository which exists already (HEAD request towards the root node)
    String existingIntermediateUri = null;
    // go through all intermediate URIs (longest first)
    for (String intermediateUri : intermediateUris) {
        // until one is existing
        int result = performHead(intermediateUri);
        if (result == HttpStatus.SC_OK) {
            existingIntermediateUri = intermediateUri;
            break;
        } else if (result != HttpStatus.SC_NOT_FOUND) {
            throw new MojoExecutionException("Failed getting intermediate path at " + intermediateUri + "."
                    + " Reason: " + HttpStatus.getStatusText(result));
        }/*from w  ww  . j a va2s.  c  o m*/
    }

    if (existingIntermediateUri == null) {
        throw new MojoExecutionException(
                "Could not find any intermediate path up until the root of " + targetURL + ".");
    }

    // 2. now create from that level on each intermediate node individually towards the target path
    int startOfInexistingIntermediateUri = intermediateUris.indexOf(existingIntermediateUri);
    if (startOfInexistingIntermediateUri == -1) {
        throw new IllegalStateException(
                "Could not find intermediate uri " + existingIntermediateUri + " in the list");
    }

    for (int index = startOfInexistingIntermediateUri - 1; index >= 0; index--) {
        // use MKCOL to create the intermediate paths
        String intermediateUri = intermediateUris.get(index);
        int result = performMkCol(intermediateUri);
        if (result == HttpStatus.SC_CREATED || result == HttpStatus.SC_OK) {
            getLog().debug("Intermediate path at " + intermediateUri + " successfully created");
            continue;
        } else {
            throw new MojoExecutionException("Failed creating intermediate path at '" + intermediateUri + "'."
                    + " Reason: " + HttpStatus.getStatusText(result));
        }
    }
}