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

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

Introduction

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

Prototype

int SC_ACCEPTED

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

Click Source Link

Document

<tt>202 Accepted</tt> (HTTP/1.0 - RFC 1945)

Usage

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 ww . 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:ai.grakn.engine.controller.TasksController.java

private Json buildResponseForTasks(Response response, Json responseJson,
        CompletableFuture<List<Json>> completableFuture)
        throws InterruptedException, java.util.concurrent.ExecutionException, TimeoutException {
    List<Json> results = completableFuture.get(MAX_EXECUTION_TIME.getSeconds(), TimeUnit.SECONDS);
    boolean hasFailures = false;
    for (Json resultForTask : results) {
        responseJson.add(resultForTask);
        if (resultForTask.at("code").asInteger() != HttpStatus.SC_OK) {
            LOG.error("Could not add task {}", resultForTask);
            hasFailures = true;//  w w  w.  j a v  a 2 s . com
        }
    }
    if (!hasFailures) {
        response.status(HttpStatus.SC_OK);
    } else if (responseJson.asJsonList().size() > 0) {
        response.status(HttpStatus.SC_ACCEPTED);
    } else {
        response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }
    return responseJson;
}

From source file:edu.unc.lib.dl.fedora.ManagementClient.java

public String upload(File file, boolean retry) {
    String result = null;/*w  ww  . ja v  a 2 s . com*/
    String uploadURL = this.getFedoraContextUrl() + "/upload";
    PostMethod post = new PostMethod(uploadURL);
    post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    log.debug("Uploading file with forwarded groups: " + GroupsThreadStore.getGroupString());
    post.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString());
    try {
        log.debug("Uploading to " + uploadURL);
        Part[] parts = { new FilePart("file", file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        int status = httpClient.executeMethod(post);

        StringWriter sw = new StringWriter();
        try (InputStream in = post.getResponseBodyAsStream(); PrintWriter pw = new PrintWriter(sw)) {
            int b;
            while ((b = in.read()) != -1) {
                pw.write(b);
            }
        }

        switch (status) {
        case HttpStatus.SC_OK:
        case HttpStatus.SC_CREATED:
        case HttpStatus.SC_ACCEPTED:
            result = sw.toString().trim();
            log.info("Upload complete, response=" + result);
            break;
        case HttpStatus.SC_FORBIDDEN:
            log.warn("Authorization to Fedora failed, attempting to reestablish connection.");
            try {
                this.initializeConnections();
                return upload(file, false);
            } catch (Exception e) {
                log.error("Failed to reestablish connection to Fedora", e);
            }
            break;
        case HttpStatus.SC_SERVICE_UNAVAILABLE:
            throw new FedoraTimeoutException("Fedora service unavailable, upload failed");
        default:
            log.warn("Upload failed, response=" + HttpStatus.getStatusText(status));
            log.debug(sw.toString().trim());
            break;
        }
    } catch (ServiceException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ServiceException(ex);
    } finally {
        post.releaseConnection();
    }
    return result;
}

From source file:edu.unc.lib.dl.fedora.ManagementClient.java

public String upload(byte[] bytes, String fileName) {
    String result = null;//www.j a  va2 s . co  m
    // construct a post request to Fedora upload service
    String uploadURL = this.getFedoraContextUrl() + "/upload";
    PostMethod post = new PostMethod(uploadURL);
    post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    log.debug("Uploading XML with forwarded groups: " + GroupsThreadStore.getGroupString());
    post.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString());
    try {
        log.debug("Uploading to " + uploadURL);
        Part[] parts = { new FilePart("file", new ByteArrayPartSource(fileName, bytes)) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        int status = httpClient.executeMethod(post);

        StringWriter sw = new StringWriter();
        try (InputStream in = post.getResponseBodyAsStream(); PrintWriter pw = new PrintWriter(sw)) {
            int b;
            while ((b = in.read()) != -1) {
                pw.write(b);
            }
        }
        if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_ACCEPTED) {
            result = sw.toString().trim();
            log.debug("Upload complete, response=" + result);
        } else {
            log.warn("Upload failed, response=" + HttpStatus.getStatusText(status));
            log.debug(sw.toString().trim());
        }
    } catch (Exception ex) {
        log.error("Upload failed due to error", ex);
        throw new ServiceException(ex);
    } finally {
        post.releaseConnection();
    }
    return result;
}

From source file:opendap.xml.Transformer.java

public static Document getXMLDoc(String s) throws Exception {

    // get a validating jdom parser to parse and validate the XML document.
    SAXBuilder parser = new SAXBuilder("org.apache.xerces.parsers.SAXParser", false);
    parser.setFeature("http://apache.org/xml/features/validation/schema", false);

    Document doc;//from w ww . j  a  v  a  2s .  co m

    if (s.startsWith("http://")) {
        log.debug("Appears to be a URL: " + s);

        GetMethod request = new GetMethod(s);
        InputStream is = null;
        try {

            HttpClient httpClient = new HttpClient();
            // Execute the method.
            int statusCode = httpClient.executeMethod(request);

            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_ACCEPTED) {
                is = request.getResponseBodyAsStream();
                doc = parser.build(is);
            } else {
                log.error("HttpClient failed to executeMethod(). Status: " + request.getStatusLine());
                doc = null;
            }

            return doc;

        } finally {
            if (is != null)
                is.close();
            log.debug("Releasing Http connection.");
            request.releaseConnection();
        }

    } else {
        File file = new File(s);
        if (!file.exists()) {
            throw new IOException("Cannot find file: " + s);
        }

        if (!file.canRead()) {
            throw new IOException("Cannot read file: " + s);
        }

        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            doc = parser.build(fis);
        } finally {
            if (fis != null) {
                fis.close();
            }
        }

        return doc;

    }

}

From source file:org.apache.ambari.funtest.server.utils.RestApiUtils.java

/**
 * Executes a web request and throws an exception if the status code is incorrect.
 *
 * @param request/*from w w w  .j a  va 2s. com*/
 * @return
 * @throws Exception
 */
public static JsonElement executeRequest(WebRequest request) throws Exception {
    WebResponse response = request.getResponse();
    int responseCode = response.getStatusCode();
    String responseBody = response.getContent();

    if (responseCode != HttpStatus.SC_OK && responseCode != HttpStatus.SC_CREATED
            && responseCode != HttpStatus.SC_ACCEPTED) {
        throw new RuntimeException(String.format("%d:%s", responseCode, responseBody));
    }

    return new JsonParser().parse(new JsonReader(new StringReader(responseBody)));
}

From source file:org.apache.axis2.transport.http.HTTPSender.java

/**
 * Used to handle the HTTP Response/*from w  w  w  . ja  va 2 s .co  m*/
 *
 * @param msgContext - The MessageContext of the message
 * @param method     - The HTTP method used
 * @throws IOException - Thrown in case an exception occurs
 */
private void handleResponse(MessageContext msgContext, HttpMethodBase method) throws IOException {
    int statusCode = method.getStatusCode();
    HTTPStatusCodeFamily family = getHTTPStatusCodeFamily(statusCode);
    log.trace("Handling response - " + statusCode);
    Set<Integer> nonErrorCodes = (Set<Integer>) msgContext
            .getProperty(HTTPConstants.NON_ERROR_HTTP_STATUS_CODES);
    Set<Integer> errorCodes = new HashSet<Integer>();
    String strRetryErrorCodes = (String) msgContext.getProperty(HTTPConstants.ERROR_HTTP_STATUS_CODES); // Fixing
    // ESBJAVA-3178
    if (strRetryErrorCodes != null && !strRetryErrorCodes.trim().equals("")) {
        for (String strRetryErrorCode : strRetryErrorCodes.split(",")) {
            try {
                errorCodes.add(Integer.valueOf(strRetryErrorCode));
            } catch (NumberFormatException e) {
                log.warn(strRetryErrorCode + " is not a valid status code");
            }
        }
    }
    if (statusCode == HttpStatus.SC_ACCEPTED) {
        /* When an HTTP 202 Accepted code has been received, this will be the case of an execution 
         * of an in-only operation. In such a scenario, the HTTP response headers should be returned,
         * i.e. session cookies. */
        obtainHTTPHeaderInformation(method, msgContext);
        // Since we don't expect any content with a 202 response, we must release the connection
        method.releaseConnection();
    } else if (HTTPStatusCodeFamily.SUCCESSFUL.equals(family)) {
        // Save the HttpMethod so that we can release the connection when cleaning up
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        processResponse(method, msgContext);
    } else if (!errorCodes.contains(statusCode) && (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR
            || statusCode == HttpStatus.SC_BAD_REQUEST || statusCode == HttpStatus.SC_CONFLICT)) {
        // Save the HttpMethod so that we can release the connection when cleaning up
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        Header contenttypeHeader = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        String value = null;
        if (contenttypeHeader != null) {
            value = contenttypeHeader.getValue();
        }
        OperationContext opContext = msgContext.getOperationContext();
        if (opContext != null) {
            MessageContext inMessageContext = opContext.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
            if (inMessageContext != null) {
                inMessageContext.setProcessingFault(true);
            }
        }
        if (value != null) {

            processResponse(method, msgContext);
        }

        if (org.apache.axis2.util.Utils.isClientThreadNonBlockingPropertySet(msgContext)) {
            throw new AxisFault(
                    Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText()));
        }
    } else if (nonErrorCodes != null && nonErrorCodes.contains(statusCode)) {
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        processResponse(method, msgContext);
        return;
    } else {
        // Since we don't process the response, we must release the connection immediately
        method.releaseConnection();
        throw new AxisFault(
                Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText()));
    }
}

From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.java

/**
 * Used to handle the HTTP Response/* w  w w  .  ja v  a  2 s  .co m*/
 * 
 * @param msgContext
 *            - The MessageContext of the message
 * @param method
 *            - The HTTP method used
 * @throws IOException
 *             - Thrown in case an exception occurs
 */
protected void handleResponse(MessageContext msgContext, Object httpMethodBase) throws IOException {
    HttpMethodBase method;
    if (httpMethodBase instanceof HttpMethodBase) {
        method = (HttpMethodBase) httpMethodBase;
    } else {
        log.trace("HttpMethodBase expected, but found - " + httpMethodBase);
        return;
    }
    int statusCode = method.getStatusCode();
    HTTPStatusCodeFamily family = getHTTPStatusCodeFamily(statusCode);
    log.trace("Handling response - " + statusCode);
    if (statusCode == HttpStatus.SC_ACCEPTED) {
        /* When an HTTP 202 Accepted code has been received, this will be the case of an execution 
         * of an in-only operation. In such a scenario, the HTTP response headers should be returned,
         * i.e. session cookies. */
        obtainHTTPHeaderInformation(method, msgContext);
        // Since we don't expect any content with a 202 response, we must release the connection
        method.releaseConnection();
    } else if (HTTPStatusCodeFamily.SUCCESSFUL.equals(family)) {
        // Save the HttpMethod so that we can release the connection when cleaning up
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        processResponse(method, msgContext);
    } else if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR || statusCode == HttpStatus.SC_BAD_REQUEST) {
        // Save the HttpMethod so that we can release the connection when
        // cleaning up
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        Header contenttypeHeader = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        String value = null;
        if (contenttypeHeader != null) {
            value = contenttypeHeader.getValue();
        }
        OperationContext opContext = msgContext.getOperationContext();
        if (opContext != null) {
            MessageContext inMessageContext = opContext.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
            if (inMessageContext != null) {
                inMessageContext.setProcessingFault(true);
            }
        }
        if (value != null) {

            processResponse(method, msgContext);
        }

        if (org.apache.axis2.util.Utils.isClientThreadNonBlockingPropertySet(msgContext)) {
            throw new AxisFault(
                    Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText()));
        }
    } else {
        // Since we don't process the response, we must release the
        // connection immediately
        method.releaseConnection();
        throw new AxisFault(
                Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText()));
    }
}

From source file:org.apache.excalibur.source.factories.HTTPClientSource.java

/**
 * According to RFC2616 (HTTP 1.1) valid responses for a HTTP DELETE
 * are 200 (OK), 202 (Accepted) and 204 (No Content).
 *
 * @param response response code from the HTTP PUT
 * @return true if upload was successful, false otherwise.
 *///from w w w. j  ava2s.  c o  m
private boolean deleteSuccessful(final int response) {
    return response == HttpStatus.SC_OK || response == HttpStatus.SC_ACCEPTED
            || response == HttpStatus.SC_NO_CONTENT;
}

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 {/*w w  w  .j  a v a2s .  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();
    }
}