Example usage for org.apache.commons.httpclient HttpMethod getStatusLine

List of usage examples for org.apache.commons.httpclient HttpMethod getStatusLine

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getStatusLine.

Prototype

public abstract StatusLine getStatusLine();

Source Link

Usage

From source file:org.mule.ibeans.module.http.HttpClientMessageRequester2.java

/**
 * Make a specific request to the underlying transport
 *
 * @param timeout the maximum time the operation should block before returning.
 *                The call should return immediately if there is data available. If
 *                no data becomes available before the timeout elapses, null will be
 *                returned//from   w w  w.j av a2  s . com
 * @return the result of the request wrapped in a MuleMessage object. Null will be
 *         returned if no data was avaialable
 * @throws Exception if the call to the underlying protocal cuases an exception
 */
protected MuleMessage doRequest(long timeout) throws Exception {
    HttpMethod httpMethod = new GetMethod(endpoint.getEndpointURI().getAddress());

    if (endpoint.getProperties().containsKey(HttpConstants.HEADER_AUTHORIZATION)) {
        httpMethod.setDoAuthentication(true);
        client.getParams().setAuthenticationPreemptive(true);
        httpMethod.setRequestHeader(HttpConstants.HEADER_AUTHORIZATION,
                (String) endpoint.getProperty(HttpConstants.HEADER_AUTHORIZATION));
    }

    boolean releaseConn = false;
    try {
        HttpClient client = new HttpClient();

        if (etag != null && checkEtag) {
            httpMethod.setRequestHeader(HttpConstants.HEADER_IF_NONE_MATCH, etag);
        }
        client.executeMethod(httpMethod);

        if (httpMethod.getStatusCode() < 400) {
            MuleMessage message = new HttpMuleMessageFactory(connector.getMuleContext()).create(httpMethod,
                    null /* encoding */);
            etag = message.getInboundProperty(HttpConstants.HEADER_ETAG, null);

            if (httpMethod.getStatusCode() == HttpStatus.SC_OK
                    || (httpMethod.getStatusCode() != HttpStatus.SC_NOT_MODIFIED || !checkEtag)) {
                if (StringUtils.EMPTY.equals(message.getPayload())) {
                    releaseConn = true;
                }
                return message;
            } else {
                //Not modified, we should really cache the whole message and return it
                return new DefaultMuleMessage(NullPayload.getInstance(), getConnector().getMuleContext());
            }
        } else {
            releaseConn = true;
            throw new ReceiveException(
                    HttpMessages.requestFailedWithStatus(httpMethod.getStatusLine().toString()), endpoint,
                    timeout);
        }

    } catch (ReceiveException e) {
        releaseConn = true;
        throw e;
    } catch (Exception e) {
        releaseConn = true;
        throw new ReceiveException(endpoint, timeout, e);
    } finally {
        if (releaseConn) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:org.mule.transport.as2.As2MuleMessageFactory.java

@Override
protected void addProperties(DefaultMuleMessage message, Object transportMessage) throws Exception {
    String method;/*from   w  w w.j a v  a  2 s  .co m*/
    HttpVersion httpVersion;
    String uri;
    String statusCode = null;
    Map<String, Object> headers;
    Map<String, Object> httpHeaders = new HashMap<String, Object>();
    Map<String, Object> queryParameters = new HashMap<String, Object>();

    if (transportMessage instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) transportMessage;
        method = httpRequest.getRequestLine().getMethod();
        httpVersion = httpRequest.getRequestLine().getHttpVersion();
        uri = httpRequest.getRequestLine().getUri();
        headers = convertHeadersToMap(httpRequest.getHeaders(), uri);
        convertMultiPartHeaders(headers);
    } else if (transportMessage instanceof HttpMethod) {
        HttpMethod httpMethod = (HttpMethod) transportMessage;
        method = httpMethod.getName();
        httpVersion = HttpVersion.parse(httpMethod.getStatusLine().getHttpVersion());
        uri = httpMethod.getURI().toString();
        statusCode = String.valueOf(httpMethod.getStatusCode());
        headers = convertHeadersToMap(httpMethod.getResponseHeaders(), uri);
    } else {
        // This should never happen because of the supported type checking in our superclass
        throw new MessageTypeNotSupportedException(transportMessage, getClass());
    }

    rewriteConnectionAndKeepAliveHeaders(headers);

    headers = processIncomingHeaders(headers);

    httpHeaders.put(HttpConnector.HTTP_HEADERS, new HashMap<String, Object>(headers));

    String encoding = getEncoding(headers);

    queryParameters.put(HttpConnector.HTTP_QUERY_PARAMS, processQueryParams(uri, encoding));

    //Make any URI params available ans inbound message headers
    addUriParamsAsHeaders(headers, uri);

    headers.put(HttpConnector.HTTP_METHOD_PROPERTY, method);
    headers.put(HttpConnector.HTTP_REQUEST_PROPERTY, uri);
    headers.put(HttpConnector.HTTP_VERSION_PROPERTY, httpVersion.toString());
    if (enableCookies) {
        headers.put(HttpConnector.HTTP_COOKIE_SPEC_PROPERTY, cookieSpec);
    }

    if (statusCode != null) {
        headers.put(HttpConnector.HTTP_STATUS_PROPERTY, statusCode);
    }

    message.addInboundProperties(headers);
    message.addInboundProperties(httpHeaders);
    message.addInboundProperties(queryParameters);

    // The encoding is stored as message property. To avoid overriding it from the message
    // properties, it must be initialized last
    initEncoding(message, encoding);
}

From source file:org.mule.transport.http.HttpClientMessageRequester.java

/**
 * Make a specific request to the underlying transport
 *
 * @param timeout the maximum time the operation should block before returning.
 *            The call should return immediately if there is data available. If
 *            no data becomes available before the timeout elapses, null will be
 *            returned//from  w ww. j a v a2s.c  o m
 * @return the result of the request wrapped in a MuleMessage object. Null will be
 *         returned if no data was avaialable
 * @throws Exception if the call to the underlying protocal cuases an exception
 */
protected MuleMessage doRequest(long timeout) throws Exception {
    HttpMethod httpMethod = new GetMethod(endpoint.getEndpointURI().getAddress());
    connector.setupClientAuthorization(null, httpMethod, client, endpoint);

    boolean releaseConn = false;
    try {
        HttpClient client = new HttpClient();
        client.executeMethod(httpMethod);

        if (httpMethod.getStatusCode() == HttpStatus.SC_OK) {
            MuleMessage res = (MuleMessage) receiveTransformer.transform(httpMethod);
            if (StringUtils.EMPTY.equals(res.getPayload())) {
                releaseConn = true;
            }
            return res;
        } else {
            releaseConn = true;
            throw new ReceiveException(
                    HttpMessages.requestFailedWithStatus(httpMethod.getStatusLine().toString()), endpoint,
                    timeout);
        }
    } catch (ReceiveException e) {
        releaseConn = true;
        throw e;
    } catch (Exception e) {
        releaseConn = true;
        throw new ReceiveException(endpoint, timeout, e);
    } finally {
        if (releaseConn) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:org.mule.transport.http.HttpMuleMessageFactoryTestCase.java

private HttpMethod createMockHttpMethod(String method, InputStream body, String uri, Header[] headers)
        throws Exception {
    HttpMethod httpMethod = mock(HttpMethod.class);
    when(httpMethod.getName()).thenReturn(method);
    when(httpMethod.getStatusLine()).thenReturn(new StatusLine("HTTP/1.1 200 OK"));
    when(httpMethod.getStatusCode()).thenReturn(HttpConstants.SC_OK);
    when(httpMethod.getURI()).thenReturn(new URI(uri, false));
    when(httpMethod.getResponseHeaders()).thenReturn(headers);
    when(httpMethod.getResponseBodyAsStream()).thenReturn(body);

    return httpMethod;
}

From source file:org.obm.caldav.client.AbstractPushTest.java

private synchronized Document doRequest(HttpMethod hm) {
    Document xml = null;/*from  w w  w . j  a va  2  s.c  o  m*/
    try {
        int ret = hc.executeMethod(hm);
        Header[] hs = hm.getResponseHeaders();
        for (Header h : hs) {
            System.err.println("head[" + h.getName() + "] => " + h.getValue());
        }
        if (ret == HttpStatus.SC_UNAUTHORIZED) {
            UsernamePasswordCredentials upc = new UsernamePasswordCredentials(login, password);
            authenticate = hm.getHostAuthState().getAuthScheme().authenticate(upc, hm);
            return null;
        } else if (ret == HttpStatus.SC_OK || ret == HttpStatus.SC_MULTI_STATUS) {
            InputStream is = hm.getResponseBodyAsStream();
            if (is != null) {
                if ("text/xml".equals(hm.getRequestHeader("Content-Type"))) {
                    xml = DOMUtils.parse(is);
                    DOMUtils.logDom(xml);
                } else {
                    System.out.println(FileUtils.streamString(is, false));
                }
            }
        } else {
            System.err.println("method failed:\n" + hm.getStatusLine() + "\n" + hm.getResponseBodyAsString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        hm.releaseConnection();
    }
    return xml;
}

From source file:org.olat.core.commons.modules.glossary.morphService.MorphologicalServiceDEImpl.java

private InputStream retreiveXMLReply(String partOfSpeech, String word) {
    HttpClient client = HttpClientFactory.getHttpClientInstance();
    HttpMethod method = new GetMethod(MORPHOLOGICAL_SERVICE_ADRESS);
    NameValuePair posValues = new NameValuePair(PART_OF_SPEECH_PARAM, partOfSpeech);
    NameValuePair wordValues = new NameValuePair(GLOSS_TERM_PARAM, word);
    if (log.isDebug()) {
        String url = MORPHOLOGICAL_SERVICE_ADRESS + "?" + PART_OF_SPEECH_PARAM + "=" + partOfSpeech + "&"
                + GLOSS_TERM_PARAM + "=" + word;
        log.debug("Send GET request to morph-service with URL: " + url);
    }/*www  . j  av  a2s  .  c om*/
    method.setQueryString(new NameValuePair[] { posValues, wordValues });
    try {
        client.executeMethod(method);
        int status = method.getStatusCode();
        if (status == HttpStatus.SC_NOT_MODIFIED || status == HttpStatus.SC_OK) {
            if (log.isDebug()) {
                log.debug("got a valid reply!");
            }
        } else if (method.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            log.error("Morphological Service unavailable (404)::" + method.getStatusLine().toString());
        } else {
            log.error("Unexpected HTTP Status::" + method.getStatusLine().toString());
        }
    } catch (Exception e) {
        log.error("Unexpected exception trying to get flexions!", e);
    }
    Header responseHeader = method.getResponseHeader("Content-Type");
    if (responseHeader == null) {
        // error
        log.error("URL not found!");
    }
    HttpRequestMediaResource mr = new HttpRequestMediaResource(method);
    InputStream inputStream = mr.getInputStream();

    return inputStream;
}

From source file:org.olat.core.commons.modules.glossary.morphService.MorphologicalServiceFRImpl.java

private InputStream retreiveXMLReply(String word) {
    HttpClient client = HttpClientFactory.getHttpClientInstance();
    HttpMethod method = new GetMethod(MORPHOLOGICAL_SERVICE_ADRESS);
    NameValuePair wordValues = new NameValuePair(GLOSS_TERM_PARAM, word);
    if (isLogDebugEnabled()) {
        String url = MORPHOLOGICAL_SERVICE_ADRESS + "?" + GLOSS_TERM_PARAM + "=" + word;
        logDebug("Send GET request to morph-service with URL: " + url);
    }/*w  w w.j  a va2 s .c  o m*/
    method.setQueryString(new NameValuePair[] { wordValues });
    try {
        client.executeMethod(method);
        int status = method.getStatusCode();
        if (status == HttpStatus.SC_NOT_MODIFIED || status == HttpStatus.SC_OK) {
            if (isLogDebugEnabled()) {
                logDebug("got a valid reply!");
            }
        } else if (method.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            logError("Morphological Service unavailable (404)::" + method.getStatusLine().toString(), null);
        } else {
            logError("Unexpected HTTP Status::" + method.getStatusLine().toString(), null);
        }
    } catch (Exception e) {
        logError("Unexpected exception trying to get flexions!", e);
    }
    Header responseHeader = method.getResponseHeader("Content-Type");
    if (responseHeader == null) {
        // error
        logError("URL not found!", null);
    }
    HttpRequestMediaResource mr = new HttpRequestMediaResource(method);
    InputStream inputStream = mr.getInputStream();

    return inputStream;
}

From source file:org.openhab.binding.frontiersiliconradio.internal.FrontierSiliconRadioConnection.java

/**
 * Perform login/establish a new session. Uses the PIN number and when successful saves the assigned sessionID for
 * future requests.//from   w ww  . jav a2s  .  c o m
 * 
 * @return <code>true</code> if login was successful; <code>false</code> otherwise.
 */
public boolean doLogin() {
    isLoggedIn = false; // reset login flag

    if (httpClient == null) {
        httpClient = new HttpClient();
    }

    final String url = "http://" + hostname + ":" + port + "/fsapi/CREATE_SESSION?pin=" + pin;

    logger.trace("opening URL:" + url);

    final HttpMethod method = new GetMethod(url);
    method.getParams().setSoTimeout(SOCKET_TIMEOUT);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

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

        final String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
        if (!responseBody.isEmpty()) {
            logger.trace("login response: " + responseBody);
        }

        try {
            final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody);
            if (result.isStatusOk()) {
                logger.trace("login successful");
                sessionId = result.getSessionId();
                isLoggedIn = true;
                return true; // login successful :-)
            }
        } catch (Exception e) {
            logger.error("Parsing response failed");
        }

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

From source file:org.openhab.binding.frontiersiliconradio.internal.FrontierSiliconRadioConnection.java

/**
 * Performs a request to the radio with addition parameters.
 * //from   www.jav a2  s. c  o  m
 * Typically used for changing parameters.
 * 
 * @param REST
 *            API requestString, e.g. "SET/netRemote.sys.power"
 * @param params
 *            , e.g. "value=1"
 * @return request result
 */
public FrontierSiliconRadioApiResult doRequest(String requestString, String params) {

    // 3 retries upon failure
    for (int i = 0; i < 3; i++) {
        if (!isLoggedIn && !doLogin()) {
            continue; // not logged in and login was not successful - try again!
        }

        final String url = "http://" + hostname + ":" + port + "/fsapi/" + requestString + "?pin=" + pin
                + "&sid=" + sessionId + (params == null || params.trim().length() == 0 ? "" : "&" + params);

        logger.trace("calling url: '" + url + "'");

        final HttpMethod method = new GetMethod(url);
        method.getParams().setSoTimeout(SOCKET_TIMEOUT);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        try {

            final int statusCode = httpClient.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK) {
                logger.warn("Method failed: " + method.getStatusLine());
                isLoggedIn = false;
                method.releaseConnection();
                continue;
            }

            final String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
            if (!responseBody.isEmpty()) {
                logger.trace("got result: " + responseBody);
            } else {
                logger.debug("got empty result");
                isLoggedIn = false;
                method.releaseConnection();
                continue;
            }

            final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody);
            if (result.isStatusOk())
                return result;

            isLoggedIn = false;
            method.releaseConnection();
            continue; // try again
        } catch (HttpException he) {
            logger.error("Fatal protocol violation: {}", he.toString());
            isLoggedIn = false;
        } catch (IOException ioe) {
            logger.error("Fatal transport error: {}", ioe.toString());
        } finally {
            method.releaseConnection();
        }
    }
    isLoggedIn = false; // 3 tries failed. log in again next time, maybe our session went invalid (radio restarted?)
    return null;
}

From source file:org.openhab.binding.garadget.internal.Connection.java

/**
 * Send a command to the Particle REST API (convenience function).
 *
 * @param device//from www . ja  va 2 s  .c om
 *            the device context, or <code>null</code> if not needed for this command.
 * @param funcName
 *            the function name to call, or variable/field to retrieve if <code>command</code> is
 *            <code>null</code>.
 * @param user
 *            the user name to use in Basic Authentication if the funcName would require Basic Authentication.
 * @param pass
 *            the password to use in Basic Authentication if the funcName would require Basic Authentication.
 * @param command
 *            the command to send to the API.
 * @param proc
 *            a callback object that receives the status code and response body, or <code>null</code> if not
 *            needed.
 */
public void sendCommand(AbstractDevice device, String funcName, String user, String pass, String command,
        HttpResponseHandler proc) {
    String url = null;
    String httpMethod = null;
    String content = null;
    String contentType = null;
    Properties headers = new Properties();
    logger.trace("sendCommand: funcName={}", funcName);

    switch (funcName) {
    case "createToken":
        httpMethod = HTTP_POST;
        url = TOKEN_URL;
        content = command;
        contentType = APPLICATION_FORM_URLENCODED;
        break;
    case "deleteToken":
        httpMethod = HTTP_DELETE;
        url = String.format(ACCESS_TOKENS_URL, tokens.accessToken);
        break;
    case "getDevices":
        httpMethod = HTTP_GET;
        url = String.format(GET_DEVICES_URL, tokens.accessToken);
        break;
    default:
        url = String.format(DEVICE_FUNC_URL, device.getId(), funcName, tokens.accessToken);
        if (command == null) {
            // retrieve a variable
            httpMethod = HTTP_GET;
        } else {
            // call a function
            httpMethod = HTTP_POST;
            content = command;
            contentType = APPLICATION_JSON;
        }
        break;
    }

    HttpClient client = new HttpClient();

    // Only perform basic authentication when we aren't using OAuth

    if (!url.contains("access_token=")) {
        Credentials credentials = new UsernamePasswordCredentials(user, pass);
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }

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

    for (String httpHeaderKey : headers.stringPropertyNames()) {
        method.addRequestHeader(new Header(httpHeaderKey, headers.getProperty(httpHeaderKey)));
        logger.trace("Header key={}, value={}", httpHeaderKey, headers.getProperty(httpHeaderKey));
    }

    try {
        // add content if a valid method is given ...
        if (method instanceof EntityEnclosingMethod && content != null) {
            EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
            eeMethod.setRequestEntity(new StringRequestEntity(content, contentType, null));
            logger.trace("content='{}', contentType='{}'", content, contentType);
        }

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

        int statusCode = client.executeMethod(method);
        if (statusCode >= HttpStatus.SC_BAD_REQUEST) {
            logger.debug("Method failed: " + method.getStatusLine());
        }

        String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
        if (!responseBody.isEmpty()) {
            logger.debug("Body of response: {}", responseBody);
        }

        if (proc != null) {
            proc.handleResponse(statusCode, responseBody);
        }
    } catch (HttpException he) {
        logger.warn("{}", he);
    } catch (IOException ioe) {
        logger.debug("{}", ioe);
    } finally {
        method.releaseConnection();
    }
}