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:org.eclipse.osee.framework.core.util.HttpProcessor.java

public static String post(URL url) throws Exception {
    AcquireResult result = new AcquireResult();
    String response = null;//from   w  ww  .j a  va  2 s  .c  o  m
    int statusCode = -1;

    PostMethod method = new PostMethod(url.toString());

    InputStream responseInputStream = null;
    try {
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        statusCode = executeMethod(url, method);
        responseInputStream = method.getResponseBodyAsStream();
        result.setContentType(getContentType(method));
        result.setEncoding(method.getResponseCharSet());
        if (statusCode != HttpStatus.SC_ACCEPTED) {
            String exceptionString = Lib.inputStreamToString(responseInputStream);
            throw new Exception(exceptionString);
        } else {
            responseInputStream = method.getResponseBodyAsStream();
            response = Lib.inputStreamToString(responseInputStream);
        }
    } finally {
        Lib.close(responseInputStream);
        method.releaseConnection();
    }
    return response;
}

From source file:org.eclipse.osee.framework.core.util.HttpProcessor.java

public static AcquireResult acquire(URL url, OutputStream outputStream, int soTimeout) throws Exception {
    AcquireResult result = new AcquireResult();
    int statusCode = -1;

    GetMethod method = new GetMethod(url.toString());

    InputStream inputStream = null;
    try {/*from   www. j  a v  a  2 s  .com*/
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        method.getParams().setSoTimeout(soTimeout);

        statusCode = executeMethod(url, method);
        result.setEncoding(method.getResponseCharSet());
        result.setContentType(getContentType(method));
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_ACCEPTED) {
            inputStream = method.getResponseBodyAsStream();
            Lib.inputStreamToOutputStream(inputStream, outputStream);
        } else {
            String response = method.getResponseBodyAsString();
            result.setResult(response);
        }
    } catch (Exception ex) {
        throw new Exception(
                String.format("Error acquiring resource: [%s] - status code: [%s]", url, statusCode), ex);
    } finally {
        Lib.close(inputStream);
        result.setCode(statusCode);
        method.releaseConnection();
    }
    return result;
}

From source file:org.eclipse.osee.framework.core.util.HttpProcessor.java

public static String delete(URL url) throws Exception {
    String response = null;//from w  w  w .java  2  s . c  o  m
    int statusCode = -1;
    DeleteMethod method = new DeleteMethod(url.toString());

    InputStream responseInputStream = null;
    try {
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        statusCode = executeMethod(url, method);
        if (statusCode == HttpStatus.SC_ACCEPTED) {
            responseInputStream = method.getResponseBodyAsStream();
            response = Lib.inputStreamToString(responseInputStream);
        }
    } catch (Exception ex) {
        throw new Exception(String.format("Error deleting resource: [%s] - status code: [%s]", url, statusCode),
                ex);
    } finally {
        Lib.close(responseInputStream);
        method.releaseConnection();
    }
    return response;
}

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  . j  a v a 2 s.  co 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.loadosophia.client.LoadosophiaAPIClient.java

public void sendOnlineData(JSONArray data) throws IOException {
    String uri = address + "api/active/receiver/data/";
    LinkedList<Part> partsList = new LinkedList<Part>();
    String dataStr = data.toString();
    log.debug("Sending active test data: " + dataStr);
    partsList.add(new StringPart("data", dataStr));
    multipartPost(partsList, uri, HttpStatus.SC_ACCEPTED);
}

From source file:org.openhab.action.telegram.internal.Telegram.java

@ActionDoc(text = "Sends a Telegram via Telegram REST API - direct message")
static public boolean sendTelegram(@ParamDoc(name = "group") String group,
        @ParamDoc(name = "message") String message) {

    if (groupTokens.get(group) == null) {
        logger.error("Bot '{}' not defined, action skipped", group);
        return false;
    }/*from  w  ww  .ja v  a 2  s. c  o  m*/

    String url = String.format(TELEGRAM_URL, groupTokens.get(group).getToken());

    HttpClient client = new HttpClient();

    PostMethod postMethod = new PostMethod(url);
    postMethod.getParams().setSoTimeout(HTTP_TIMEOUT);
    postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    NameValuePair[] data = { new NameValuePair("chat_id", groupTokens.get(group).getChatId()),
            new NameValuePair("text", message) };
    postMethod.setRequestBody(data);

    try {
        int statusCode = client.executeMethod(postMethod);

        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            return true;
        }

        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: {}", postMethod.getStatusLine());
            return false;
        }

        InputStream tmpResponseStream = postMethod.getResponseBodyAsStream();
        Header encodingHeader = postMethod.getResponseHeader("Content-Encoding");
        if (encodingHeader != null) {
            for (HeaderElement ehElem : encodingHeader.getElements()) {
                if (ehElem.toString().matches(".*gzip.*")) {
                    tmpResponseStream = new GZIPInputStream(tmpResponseStream);
                    logger.debug("GZipped InputStream from {}", url);
                } else if (ehElem.toString().matches(".*deflate.*")) {
                    tmpResponseStream = new InflaterInputStream(tmpResponseStream);
                    logger.debug("Deflated InputStream from {}", url);
                }
            }
        }

        String responseBody = IOUtils.toString(tmpResponseStream);
        if (!responseBody.isEmpty()) {
            logger.debug(responseBody);
        }

    } catch (HttpException e) {
        logger.error("Fatal protocol violation: {}", e.toString());
    } catch (IOException e) {
        logger.error("Fatal transport error: {}", e.toString());
    } finally {
        postMethod.releaseConnection();
    }

    return true;
}

From source file:org.openhab.binding.nest.internal.messages.AbstractRequest.java

/**
 * Executes the given <code>url</code> with the given <code>httpMethod</code>. In the case of httpMethods that do
 * not support automatic redirection, manually handle the HTTP temporary redirect (307) and retry with the new URL.
 * //from w  w w  .j ava 2s  .  c  om
 * @param httpMethod
 *            the HTTP method to use
 * @param url
 *            the url to execute (in milliseconds)
 * @param contentString
 *            the content to be sent to the given <code>url</code> or <code>null</code> if no content should be
 *            sent.
 * @param contentType
 *            the content type of the given <code>contentString</code>
 * @return the response body or <code>NULL</code> when the request went wrong
 */
protected final String executeUrl(final String httpMethod, final String url, final String contentString,
        final String contentType) {

    HttpClient client = new HttpClient();

    HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(HTTP_REQUEST_TIMEOUT);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    for (String httpHeaderKey : HTTP_HEADERS.stringPropertyNames()) {
        method.addRequestHeader(new Header(httpHeaderKey, HTTP_HEADERS.getProperty(httpHeaderKey)));
    }

    // add content if a valid method is given ...
    if (method instanceof EntityEnclosingMethod && contentString != null) {
        EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
        InputStream content = new ByteArrayInputStream(contentString.getBytes());
        eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
    }

    if (logger.isDebugEnabled()) {
        try {
            logger.trace("About to execute '" + method.getURI().toString() + "'");
        } catch (URIException e) {
            logger.trace(e.getMessage());
        }
    }

    try {

        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            // perfectly fine but we cannot expect any answer...
            return null;
        }

        // Manually handle 307 redirects with a little tail recursion
        if (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
            Header[] headers = method.getResponseHeaders("Location");
            String newUrl = headers[headers.length - 1].getValue();
            return executeUrl(httpMethod, newUrl, contentString, contentType);
        }

        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: " + method.getStatusLine());
        }

        InputStream tmpResponseStream = method.getResponseBodyAsStream();
        Header encodingHeader = method.getResponseHeader("Content-Encoding");
        if (encodingHeader != null) {
            for (HeaderElement ehElem : encodingHeader.getElements()) {
                if (ehElem.toString().matches(".*gzip.*")) {
                    tmpResponseStream = new GZIPInputStream(tmpResponseStream);
                    logger.trace("GZipped InputStream from {}", url);
                } else if (ehElem.toString().matches(".*deflate.*")) {
                    tmpResponseStream = new InflaterInputStream(tmpResponseStream);
                    logger.trace("Deflated InputStream from {}", url);
                }
            }
        }

        String responseBody = IOUtils.toString(tmpResponseStream);
        if (!responseBody.isEmpty()) {
            logger.trace(responseBody);
        }

        return responseBody;
    } catch (HttpException he) {
        logger.error("Fatal protocol violation: {}", he.toString());
    } catch (IOException ioe) {
        logger.error("Fatal transport error: {}", ioe.toString());
    } finally {
        method.releaseConnection();
    }

    return null;
}

From source file:org.openhab.io.net.http.HttpUtil.java

/**
 * Executes the given <code>url</code> with the given <code>httpMethod</code>
 * /*from w  w w .j ava  2  s.co m*/
 * @param httpMethod the HTTP method to use
 * @param url the url to execute (in milliseconds)
 * @param httpHeaders optional HTTP headers which has to be set on request
 * @param content the content to be send to the given <code>url</code> or 
 * <code>null</code> if no content should be send.
 * @param contentType the content type of the given <code>content</code>
 * @param timeout the socket timeout to wait for data
 * @param proxyHost the hostname of the proxy
 * @param proxyPort the port of the proxy
 * @param proxyUser the username to authenticate with the proxy
 * @param proxyPassword the password to authenticate with the proxy
 * @param nonProxyHosts the hosts that won't be routed through the proxy
 * @return the response body or <code>NULL</code> when the request went wrong
 */
public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content,
        String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser,
        String proxyPassword, String nonProxyHosts) {

    HttpClient client = new HttpClient();

    // only configure a proxy if a host is provided
    if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) {
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);
        if (StringUtils.isNotBlank(proxyUser)) {
            client.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
        }
    }

    HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(timeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    if (httpHeaders != null) {
        for (String httpHeaderKey : httpHeaders.stringPropertyNames()) {
            method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey)));
        }
    }
    // add content if a valid method is given ...
    if (method instanceof EntityEnclosingMethod && content != null) {
        EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
        eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
    }

    Credentials credentials = extractCredentials(url);
    if (credentials != null) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }

    if (logger.isDebugEnabled()) {
        try {
            logger.debug("About to execute '" + method.getURI().toString() + "'");
        } catch (URIException e) {
            logger.debug(e.getMessage());
        }
    }

    try {

        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            // perfectly fine but we cannot expect any answer...
            return null;
        }

        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: " + method.getStatusLine());
        }

        InputStream tmpResponseStream = method.getResponseBodyAsStream();
        Header encodingHeader = method.getResponseHeader("Content-Encoding");
        if (encodingHeader != null) {
            for (HeaderElement ehElem : encodingHeader.getElements()) {
                if (ehElem.toString().matches(".*gzip.*")) {
                    tmpResponseStream = new GZIPInputStream(tmpResponseStream);
                    logger.debug("GZipped InputStream from {}", url);
                } else if (ehElem.toString().matches(".*deflate.*")) {
                    tmpResponseStream = new InflaterInputStream(tmpResponseStream);
                    logger.debug("Deflated InputStream from {}", url);
                }
            }
        }

        String responseBody = IOUtils.toString(tmpResponseStream);
        if (!responseBody.isEmpty()) {
            logger.debug(responseBody);
        }

        return responseBody;
    } catch (HttpException he) {
        logger.error("Fatal protocol violation: {}", he.toString());
    } catch (IOException ioe) {
        logger.error("Fatal transport error: {}", ioe.toString());
    } finally {
        method.releaseConnection();
    }

    return null;
}

From source file:org.openo.gso.roa.impl.ServicemgrRoaModuleImpl.java

/**
 * Create service instance.<br/>/*from   w w  w. ja v  a2 s.  co  m*/
 * 
 * @param servletReq http request
 * @return response
 * @since GSO 0.5
 */
@Override
public Response createService(HttpServletRequest servletReq) {
    LOGGER.info("Start to create service instance.");

    // 1. Check validation
    String reqContent = RestUtils.getRequestBody(servletReq);
    ValidateUtil.assertStringNotNull(reqContent, Constant.RESPONSE_CONTENT_MESSAGE);
    LOGGER.info("create service instance: {}", reqContent);

    // 2. Create service
    ServiceDetailModel svcDetail = serviceManager.createService(reqContent, servletReq);

    // 3. assemble response data.
    String serviceId = ((null != svcDetail) && (null != svcDetail.getServiceModel()))
            ? svcDetail.getServiceModel().getServiceId()
            : null;
    String operationId = ((null != svcDetail) && (null != svcDetail.getServiceOperation()))
            ? svcDetail.getServiceOperation().getOperationId()
            : null;
    Map<String, String> ids = new HashMap<>();
    ids.put(Constant.SERVICE_INSTANCE_ID, serviceId);
    ids.put(Constant.SERVICE_OPERATION_ID, operationId);
    Map<String, Object> rsp = new HashMap<>();
    rsp.put(Constant.SERVICE_INDENTIFY, ids);

    LOGGER.info("create service response: {}", rsp);

    return Response.status(HttpStatus.SC_ACCEPTED).entity(rsp).build();
}

From source file:org.openo.gso.roa.impl.ServicemgrRoaModuleImpl.java

/**
 * Delete service instance.<br/>/*from w w  w.  ja  v a  2s .  com*/
 * 
 * @param serviceId service instance id
 * @param servletReq http request
 * @return response
 * @since GSO 0.5
 */
@Override
public Response deleteService(String serviceId, HttpServletRequest servletReq) {
    LOGGER.info("Start to delete service instance.");

    // 1. Delete service and return operation id
    ValidateUtil.assertStringNotNull(serviceId, Constant.SERVICE_ID);
    String operationId = serviceManager.deleteService(serviceId, servletReq);
    LOGGER.info("delete service, the operation id is: {}", operationId);

    // 2. Build response
    Map<String, String> rps = new HashMap<>();
    rps.put(Constant.SERVICE_OPERATION_ID, operationId);
    return Response.status(HttpStatus.SC_ACCEPTED).entity(rps).build();
}