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

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

Introduction

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

Prototype

public abstract int getStatusCode();

Source Link

Usage

From source file:com.zimbra.qa.unittest.prov.soap.TestAutoProvision.java

@Test
public void preauthServlet() throws Exception {
    String testName = getTestName();

    String externalPassword = "test456";
    String extAcctLocalPart = testName;
    String extAcctName = createExternalAcctEntry(extAcctLocalPart, externalPassword, null);

    Map<String, Object> zimbraDomainAttrs = commonZimbraDomainAttrs();
    // setup auto prov
    // commonZimbraDomainAttrs added only LDAP, add preauth here
    StringUtil.addToMultiMap(zimbraDomainAttrs, Provisioning.A_zimbraAutoProvAuthMech,
            AutoProvAuthMech.PREAUTH.name());
    zimbraDomainAttrs.put(Provisioning.A_zimbraAutoProvLdapSearchBase, extDomainDn);
    zimbraDomainAttrs.put(Provisioning.A_zimbraAutoProvLdapSearchFilter, "(uid=%u)");
    // setup external LDAP auth
    zimbraDomainAttrs.put(Provisioning.A_zimbraAuthMech, AuthMech.ldap.name());
    zimbraDomainAttrs.put(Provisioning.A_zimbraAuthLdapURL, "ldap://localhost:389");
    zimbraDomainAttrs.put(Provisioning.A_zimbraAuthLdapBindDn, "uid=%u,ou=people," + extDomainDn);
    // setup preauth
    String preAuthKey = PreAuthKey.generateRandomPreAuthKey();
    zimbraDomainAttrs.put(Provisioning.A_zimbraPreAuthKey, preAuthKey);

    Domain zimbraDomain = createZimbraDomain(testName, zimbraDomainAttrs);

    String loginName = extAcctLocalPart + "@" + zimbraDomain.getName();

    // preauth data
    String preAuthUrl = TestPreAuthServlet.genPreAuthUrl(preAuthKey, loginName, false, false);

    // do the preauth servlet request
    String url = TestUtil.getBaseUrl() + preAuthUrl;

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);

    boolean ok = false;
    try {//from  w w  w  . jav  a2  s .c o m
        int respCode = HttpClientUtil.executeMethod(client, method);
        int statusCode = method.getStatusCode();
        String statusLine = method.getStatusLine().toString();

        ok = (respCode == 200);

        /*
        System.out.println("respCode=" + respCode);
        System.out.println("statusCode=" + statusCode);
        System.out.println("statusLine=" + statusLine);
                
        System.out.println("Headers");
        Header[] respHeaders = method.getResponseHeaders();
        for (int i=0; i < respHeaders.length; i++) {
        String header = respHeaders[i].toString();
        System.out.println(header);
        }
        */

        /*
        String respBody = method.getResponseBodyAsString();
        System.out.println(respBody);
        */

    } catch (HttpException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        method.releaseConnection();
    }

    assertTrue(ok);

    /*
    String encodedAuthToken = response.getElement(AccountConstants.E_AUTH_TOKEN).getText();
    assertNotNull(encodedAuthToken);
    AuthToken authToken = AuthToken.getAuthToken(encodedAuthToken);
    String acctId = authToken.getAccountId();
    Account acct = prov.get(AccountBy.id, acctId);
    verifyAcctAutoProvisioned(acct, loginName.toLowerCase());
    */
}

From source file:com.gs.jrpip.client.ThankYouWriter.java

void sendThankYouRequest(CoalesceThankYouNotesKey key) {
    boolean success = false;
    List requestList = this.removeRequestList(key);
    if (done || requestList == null) {
        return;//from w w w.ja  v a2 s  . c  o  m
    }
    HttpMethod streamedPostMethod = null;
    try {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Sending thank you for {}", requestList.size());
        }
        AuthenticatedUrl url = key.getAuthenticatedUrl();
        HttpClient httpClient = FastServletProxyFactory.getHttpClient(url);
        httpClient.getState().addCookies(key.getCookies());
        OutputStreamWriter writer = new ThankYouStreamWriter(requestList);
        streamedPostMethod = FastServletProxyFactory.serverSupportsChunking(url)
                ? new StreamedPostMethod(url.getPath() + "?thanks", writer)
                : new BufferedPostMethod(url.getPath() + "?thanks", writer);
        httpClient.executeMethod(streamedPostMethod);

        int code = streamedPostMethod.getStatusCode();

        streamedPostMethod.getResponseBodyAsStream().close();
        streamedPostMethod.releaseConnection();
        streamedPostMethod = null;
        success = code == 200;
    } catch (Exception e) {
        LOGGER.warn("Exception in JRPIP thank you note for URL: {} Retrying.", key.toString(), e);
    } finally {
        if (streamedPostMethod != null) {
            streamedPostMethod.releaseConnection();
        }
    }
    if (!success) {
        this.readList(key, requestList);
    }
}

From source file:net.sourceforge.jwbf.actions.HttpActionClient.java

/**
 * Process a GET Message.//from  w w  w.  ja v  a2s  .com
 * 
 * @param authgets
 *            a
 * @param cp
 *            a
 * @return a returning message, not null
 * @throws IOException on problems
 * @throws CookieException on problems
 * @throws ProcessException on problems
 */
protected String get(HttpMethod authgets, ContentProcessable cp)
        throws IOException, CookieException, ProcessException {
    showCookies(client);
    String out = "";
    authgets.getParams().setParameter("http.protocol.content-charset", MediaWikiBot.CHARSET);
    //      System.err.println(authgets.getParams().getParameter("http.protocol.content-charset"));

    client.executeMethod(authgets);
    cp.validateReturningCookies(client.getState().getCookies(), authgets);
    LOG.debug(authgets.getURI());
    LOG.debug("GET: " + authgets.getStatusLine().toString());

    out = authgets.getResponseBodyAsString();

    out = cp.processReturningText(out, authgets);
    // release any connection resources used by the method
    authgets.releaseConnection();
    int statuscode = authgets.getStatusCode();

    if (statuscode == HttpStatus.SC_NOT_FOUND) {
        LOG.warn("Not Found: " + authgets.getQueryString());

        throw new FileNotFoundException(authgets.getQueryString());
    }

    return out;
}

From source file:com.jackbe.mapreduce.EMMLRestRunner.java

protected String executeRESTCall(String scriptName, String encodedValue) {

    // "http://localhost:8080/presto/edge/api/rest/StockQuoteMapper/runMashup?x-presto-resultFormat=xml&value=<encodedValue>"
    HttpMethod httpMethod = null;
    String result = null;//ww w .j  a v  a 2  s.  co  m

    if (encodedValue != null) {
        httpMethod = new GetMethod(protocol + host + ":" + port + path + scriptName + "/" + operation + "?"
                + format + "&value=" + encodedValue);
        log.debug("Invoking REST service: " + protocol + host + ":" + port + path + scriptName + "/" + operation
                + "?" + format + "&value=" + encodedValue);
    } else {
        httpMethod = new GetMethod(
                protocol + host + ":" + port + path + scriptName + "/" + operation + "?" + format);
        log.debug("Invoking REST service: " + protocol + host + ":" + port + path + scriptName + "/" + operation
                + "?" + format);
    }

    try {
        client.executeMethod(httpMethod);

        if (httpMethod.getStatusCode() != HttpStatus.SC_OK) {
            log.error("HTTP Error status connecting to Presto: " + httpMethod.getStatusCode());
            log.error("HTTP Error message connecting to Presto: " + httpMethod.getStatusText());
            return null;
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Status code: " + httpMethod.getStatusCode());
                Header contentTypeHeader = httpMethod.getResponseHeader("content-type");
                log.debug("Mimetype: " + contentTypeHeader.getValue());
            }
        }

        result = httpMethod.getResponseBodyAsString();
        // log.debug(httpMethod.getStatusText());
        if (log.isDebugEnabled())
            log.debug("Response: " + result);
    } catch (Exception e) {
        log.error("Exception executing REST call: " + e, e);
    } finally {
        httpMethod.releaseConnection();
    }

    return result;

}

From source file:ait.ffma.service.preservation.riskmanagement.api.PreservationRiskmanagementServiceImpl.java

/**
 * This method tries to establish HTTP connection for passed URI
 * @param uri The URI to verify/*from  w w w .  ja v a 2 s.c  om*/
 * @param responseLineList 
 *        This list collects response lines for broken URIs
 * @param brokenUriList
 *        This list collects broken URIs
 */
private void verifyUri(String uri, List<String> responseLineList, List<String> brokenUriList) {
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
    try {
        HttpMethod method = new GetMethod(uri);
        method.setFollowRedirects(true);
        client.executeMethod(method);
        int response = method.getStatusCode();
        if (response != 200) {
            StatusLine responseLine = method.getStatusLine();
            log.info("uri: " + uri + ", response: " + response + ", responseLine: " + responseLine.toString());
            brokenUriList.add(uri);
            responseLineList.add(responseLine.toString());
        }
        method.releaseConnection();
    } catch (IOException e) {
        log.info("Unable to connect to " + uri + " verification error: " + e);
        brokenUriList.add(uri);
        responseLineList.add(e.getMessage());
    }
}

From source file:com.gs.jrpip.client.FastServletProxyInvocationHandler.java

protected Object invokeRemoteMethod(Object proxy, Method method, Object[] args) throws Throwable {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("starting remote method {}.{}", method.getDeclaringClass(), method.getName());
    }//from  w  w  w.j av  a  2 s .  co  m
    RequestId requestId = new RequestId(this.proxyId);
    int retries = RETRY_COUNT;
    int state = SEND_PARAMETERS_STATE;
    Exception lastException = null;
    boolean checkServerStatus = false;
    while (retries > 0) {
        InputStream is = null;
        byte status = StreamBasedInvocator.FAULT_STATUS;
        Object returned = null;
        HttpClient httpClient = FastServletProxyFactory.getHttpClient(this.url);
        httpClient.getState().addCookies(this.cookies);
        boolean gotResult = false;
        HttpMethod postMethod = null;
        try {
            OutputStreamWriter writer = null;
            switch (state) {
            case SEND_PARAMETERS_STATE:
                writer = new ParameterWriter(proxy, method, args, requestId);
                break;
            case RECEIVE_RESULT_STATE:
                writer = new ResultResendWriter(requestId);
                break;
            }
            postMethod = this.getPostMethod(writer);

            this.setMethodTimeout(postMethod, method);

            httpClient.executeMethod(postMethod);

            this.cookies = httpClient.getState().getCookies();

            state = RECEIVE_RESULT_STATE;

            int code = postMethod.getStatusCode();

            if (code != 200) {
                checkServerStatus = true;
                this.analyzeServerErrorAndThrow(code, postMethod);
            }

            is = postMethod.getResponseBodyAsStream();

            //if (CAUSE_RANDOM_ERROR) if (Math.random() > ERROR_RATE) throw new IOException("Random error, for testing only!");

            status = (byte) is.read();
            if (status != StreamBasedInvocator.REQUEST_NEVER_ARRVIED_STATUS) {
                returned = this.getResult(method, args, is);
            }
            gotResult = true;
            is.close();
            is = null;
            postMethod.releaseConnection();
            postMethod = null;
        } catch (SocketTimeoutException e) {
            LOGGER.debug("Socket timeout reached for JRPIP invocation", e);
            throw new JrpipTimeoutException("Remote method " + method.getName() + " timed out." + this.url, e);
        } catch (NotSerializableException e) {
            throw new JrpipRuntimeException("Method arguments are not serializable!", e);
        } catch (ClassNotFoundException e) {
            throw new JrpipRuntimeException("Method call successfully completed but result class not found", e);
        } catch (Exception e) {
            retries--;
            lastException = e;
            LOGGER.debug("Exception in JRPIP invocation. Retries left {}", retries, e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.debug("Could not close stream. See previous exception for cause", e);
                }
            }
            if (postMethod != null) {
                postMethod.releaseConnection();
            }
        }
        if (gotResult) {
            switch (status) {
            case StreamBasedInvocator.OK_STATUS:
                ThankYouWriter.getINSTANCE().addRequest(this.url, this.cookies, requestId);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("finished remote method normally {}.{}", method.getDeclaringClass(),
                            method.getName());
                }
                return returned;
            case StreamBasedInvocator.FAULT_STATUS:
                ThankYouWriter.getINSTANCE().addRequest(this.url, this.cookies, requestId);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("finished remote method {}.{} with exception {}", method.getDeclaringClass(),
                            method.getName(), returned.getClass().getName(),
                            new JrpipRuntimeException("for tracing local invocation context"));
                }
                Class[] exceptions = method.getExceptionTypes();
                for (int i = 0; i < exceptions.length; i++) {
                    if (exceptions[i].isAssignableFrom(returned.getClass())) {
                        throw (Throwable) returned;
                    }
                }
                if (RuntimeException.class.isAssignableFrom(returned.getClass())) {
                    throw (RuntimeException) returned;
                }
                if (Error.class.isAssignableFrom(returned.getClass())) {
                    throw (Error) returned;
                }
                if (Throwable.class.isAssignableFrom(returned.getClass())
                        && !Exception.class.isAssignableFrom(returned.getClass())) {
                    throw (Throwable) returned;
                }
                throw new JrpipRuntimeException(
                        "Could not throw returned exception, as it was not declared in the method signature for method "
                                + method.getName(),
                        (Throwable) returned);
            case StreamBasedInvocator.REQUEST_NEVER_ARRVIED_STATUS:
                state = SEND_PARAMETERS_STATE;
                break;
            }
        } else {
            checkServerStatus = true;
        }
        if (checkServerStatus) {
            this.determineServerStatus(state == RECEIVE_RESULT_STATE);
            checkServerStatus = false;
        }
    }
    throw new JrpipRuntimeException(
            "Could not invoke remote method " + method.getName() + " while accessing " + this.url,
            lastException);
}

From source file:com.intuit.tank.http.BaseRequest.java

public void sendRequest(BaseResponse response, @Nonnull HttpMethod method, String requestBody) {
    String uri = null;/*  w  w  w.j  a v  a 2  s .  co m*/
    long waitTime = 0L;
    try {
        this.response = response;
        uri = method.getURI().toString();
        logger.debug(
                LogUtil.getLogMessage("About to POST request to " + uri + " with requestBody  " + requestBody,
                        LogEventType.Informational));
        logRequest(uri, requestBody, method.getName(), headerInformation, httpclient, false);
        BaseRequestHandler.setHeaders(method, headerInformation);
        long startTime = System.currentTimeMillis();
        timestamp = new Date(startTime);
        httpclient.executeMethod(method);

        // read response body
        byte[] responseBody = new byte[0];
        // check for no content headers
        if (method.getStatusCode() != 203 && method.getStatusCode() != 202 && method.getStatusCode() != 204) {
            try {
                InputStream httpInputStream = method.getResponseBodyAsStream();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                int curByte = httpInputStream.read();
                while (curByte >= 0) {
                    out.write(curByte);
                    curByte = httpInputStream.read();
                }
                responseBody = out.toByteArray();
            } catch (Exception e) {
                logger.warn("could not get response body: " + e);
            }
        }
        long endTime = System.currentTimeMillis();
        BaseRequestHandler.processResponse(responseBody, startTime, endTime, response, method.getStatusText(),
                method.getStatusCode(), method.getResponseHeaders(), httpclient.getState());
        waitTime = endTime - startTime;
    } catch (Exception ex) {
        logger.error(LogUtil.getLogMessage(
                "Could not do " + method.getName() + " to url " + uri + " |  error: " + ex.toString(),
                LogEventType.IO), ex);
        throw new RuntimeException(ex);
    } finally {
        method.releaseConnection();
    }
    if (waitTime != 0) {
        doWaitDueToLongResponse(waitTime, uri);
    }
}

From source file:com.hp.alm.ali.rest.client.AliRestClient.java

private void writeResponse(ResultInfo result, HttpMethod method, boolean writeBodyAndHeaders) {
    OutputStream bodyStream = result.getBodyStream();

    StatusLine statusLine = method.getStatusLine();
    if (statusLine != null) {
        result.setReasonPhrase(statusLine.getReasonPhrase());
    }//  ww w.j a  v  a 2  s  .c  o m
    try {
        result.setLocation(method.getURI().toString());
    } catch (URIException e) {
        throw new RuntimeException(e);
    }
    if (writeBodyAndHeaders) {
        Map<String, String> headersMap = result.getHeaders();
        Header[] headers = method.getResponseHeaders();
        for (Header header : headers) {
            headersMap.put(header.getName(), header.getValue());
        }
    }
    result.setHttpStatus(method.getStatusCode());
    Filter filter = new IdentityFilter(result);
    for (ResponseFilter responseFilter : responseFilters) {
        filter = responseFilter.applyFilter(filter, method, result);
    }
    if (writeBodyAndHeaders && bodyStream != null && method.getStatusCode() != 204) {
        try {
            InputStream responseBody = method.getResponseBodyAsStream();
            if (responseBody != null) {
                IOUtils.copy(responseBody, filter.getOutputStream());
                bodyStream.flush();
                bodyStream.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.adobe.share.api.ShareAPI.java

/**
 * Parses the file response./* w ww . j av a2  s  .co  m*/
 *
 * @param method the method
 *
 * @return the input stream
 *
 * @throws HttpException the http exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws ShareAPIException the share api exception
 */
protected final InputStream parseFileResponse(final HttpMethod method)
        throws HttpException, IOException, ShareAPIException {
    JSONObject json = null;
    String content = null;

    try {
        int status = httpClient.executeMethod(method);

        if (status >= STATUS_BAD_REQUEST) {
            if (json != null) {
                throw new ShareAPIException(method.getStatusCode(),
                        json.getJSONObject("response").getString("message"));
            } else {
                throw new ShareAPIException(method.getStatusCode(), content);
            }
        }

        return method.getResponseBodyAsStream();
    } catch (JSONException e) {
        throw new ShareAPIException(method.getStatusCode(), content);
    }
}

From source file:it.haefelinger.flaka.util.HttpUpload.java

/**
 * Evaluate whether uploading went well or failed.
 * /*from   ww w  .  j  a v  a  2  s  .c  o  m*/
 * A upload on Jdepot may fail cause a connection could not be established or
 * cause there was an application specific problem (like artifact exits
 * already or Manifest does not contain required or wrong attributes).
 * 
 * @param meth
 *          not null
 * @return true if all went well
 */
protected boolean eval(HttpMethod meth) {
    Matcher regex;
    String response = null;
    StringBuilder buf = new StringBuilder("");
    String errmsg = null;
    String errtyp = null; // no error

    buf.append("<upload");
    xmlattr(buf, "testonly", get("testonly", TESTONLY));
    xmlattr(buf, "endpoint", get("endpoint", ENDPOINT));
    xmlattr(buf, "timeout", get("timeout", TIMEOUT));
    xmlattr(buf, "user", get("user", USER));
    xmlattr(buf, "loc", get("filepath", null));
    xmlattr(buf, "size", get("filesize", null));

    /* If there was already an error, handle it now */
    if (getError() != null) {
        syslog(getError());
        /* must be a transport error at this point */
        xmlattr(buf, "error", "transport-error");
        buf.append(">");
        xmldata(buf, "error", errmsg);
        buf.append("</upload>");
        set("xmlbuf", buf.toString());
        return false;
    }

    /* Handle any HTTP error */
    if (meth.getStatusCode() / 100 != 2) {
        int stat;
        String line;

        stat = meth.getStatusCode();
        line = meth.getStatusLine().toString();

        errmsg = line + " [" + HttpStatusText.explain(stat) + "]";
        setError(errmsg);
        xmlattr(buf, "error", "http-error");
        buf.append("</upload>");
        xmldata(buf, "error", errmsg);
        set("xmlbuf", buf.toString());
        return false;
    }

    /* Fetch response text from server and run a check */
    response = getResponseFrom(meth);
    /* save response for later usage */
    this.set("resbuf", response);

    /*
     * We assume that everything went well, if respone text contains an
     * acceptance message.
     */
    regex = SUBMI_P.matcher(response);

    /* do we have a confirmation message? */
    if (regex.find() == false) {
        // scan for errors? No - this should be handled on another layer.
        errtyp = "storage-error";
        errmsg = "unknown storage error";
        this.setError(errmsg);
        xmlattr(buf, "error", errtyp);
        buf.append(">");
        xmldata(buf, "error", errmsg);
        /* wrap entire response in any case */
        xmldata(buf, "cdata", response);
        buf.append("</upload>");
        set("xmlbuf", buf.toString());
        return false;
    }

    /* Finally it's looking good ... */
    String g1 = regex.group(1);
    xmlattr(buf, "href", g1);
    buf.append(">");
    /* wrap entire response in any case */
    xmldata(buf, "cdata", response);
    /* finish */
    buf.append("</upload>");
    set("xmlbuf", buf.toString());
    return true;
}