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.siberia.image.searcher.impl.GoogleImageSearcher.java

/** search */
public void search() {

    //        http://images.google.fr/images?imgsz=xxlarge&gbv=2&hl=fr&q=b+e&btnG=Recherche+d%27images
    //        http://images.google.fr/images?imgsz=xxlarge&hl=fr&q=b+e

    Runnable run = new Runnable() {
        public void run() {
            fireSearchHasBegan(new ImageSearcherEvent(GoogleImageSearcher.this));

            StringBuffer buffer = new StringBuffer(50);

            if (getCriterions() != null) {
                boolean oneTokenAlreadyApplied = false;

                for (int i = 0; i < getCriterions().length; i++) {
                    String current = getCriterions()[i];

                    if (current != null) {
                        if (oneTokenAlreadyApplied) {
                            buffer.append("+");
                        }//from  w w w.ja  v  a2  s  . co  m

                        buffer.append(current);

                        oneTokenAlreadyApplied = true;
                    }
                }
            }

            Locale locale = getLocale();
            if (locale == null) {
                locale = Locale.getDefault();
            }

            if (logger.isDebugEnabled()) {
                logger.debug("uri : " + buffer.toString());
            }

            HttpClient client = new HttpClient();

            HttpMethod method = new GetMethod(GOOGLE_URL);

            NameValuePair[] pairs = new NameValuePair[3];
            pairs[0] = new NameValuePair("imgsz", convertImageSizeCriterion(getImageSize()));
            pairs[1] = new NameValuePair("hl", locale.getCountry().toLowerCase());
            pairs[2] = new NameValuePair("q", buffer.toString());
            method.setQueryString(pairs);

            method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler(3, false));

            InputStream stream = null;

            try {
                // Execute the method.
                int statusCode = client.executeMethod(method);

                if (statusCode == HttpStatus.SC_OK) {
                    /** on recherche  partir des motifs suivants
                     *  la premire occurrence de http://  partir de l, on prend jusqu'au prochaine espace ou '>' :
                     *
                     *  exemple :
                     *      <img src=http://tbn0.google.com/images?q=tbn:GIJo-j_dSy4FiM:http://www.discogs.com/image/R-378796-1136999170.jpeg width=135 height=135>
                     *
                     *  on trouve le motif, puis, on prend  partir de http://www.discogs jusqu'au prochain espace...
                     *
                     *  --> http://www.discogs.com/image/R-378796-1136999170.jpeg
                     */
                    String searchMotif = "<img src=http://tbn0.google.com/images?q";
                    String urlMotif = "http://";

                    int indexInSearchMotif = -1;
                    int indexInUrlMotif = -1;
                    boolean motifFound = false;
                    boolean foundUrl = false;

                    StringBuffer urlBuffer = new StringBuffer(50);

                    // Read the response body.
                    byte[] bytes = new byte[1024 * 8];
                    stream = method.getResponseBodyAsStream();

                    if (stream != null) {
                        int read = -1;

                        int linksRetrieved = 0;

                        while ((read = stream.read(bytes)) != -1) {
                            for (int i = 0; i < read; i++) {
                                byte currentByte = bytes[i];

                                if (motifFound) {
                                    if (foundUrl) {
                                        if (currentByte == ' ' || currentByte == '>') {
                                            /* add current url to list of result */
                                            try {
                                                URL url = new URL(urlBuffer.toString());

                                                fireImageFound(new ImageFoundEvent(GoogleImageSearcher.this,
                                                        url, linksRetrieved));
                                                linksRetrieved++;

                                                if (linksRetrieved >= getMaximumLinksRetrieved()) {
                                                    break;
                                                }
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            } finally {
                                                urlBuffer.delete(0, urlBuffer.length());

                                                foundUrl = false;
                                                motifFound = false;
                                            }
                                        } else {
                                            /* add current byte to url buffer */
                                            urlBuffer.append((char) currentByte);
                                        }
                                    } else {
                                        if (indexInUrlMotif == urlMotif.length() - 1) {
                                            urlBuffer.append(urlMotif);
                                            urlBuffer.append((char) currentByte);
                                            foundUrl = true;
                                            indexInUrlMotif = -1;
                                        }

                                        /* if the current byte is the same as that attempted on the url motif let's continue */
                                        if (((char) currentByte) == urlMotif.charAt(indexInUrlMotif + 1)) {
                                            indexInUrlMotif++;
                                        } else {
                                            indexInUrlMotif = -1;
                                        }
                                    }
                                } else {
                                    if (indexInSearchMotif == searchMotif.length() - 1) {
                                        motifFound = true;
                                        indexInSearchMotif = -1;
                                    }

                                    if (((char) currentByte) == searchMotif.charAt(indexInSearchMotif + 1)) {
                                        indexInSearchMotif++;
                                    } else {
                                        indexInSearchMotif = -1;
                                    }
                                }
                            }
                            if (linksRetrieved >= getMaximumLinksRetrieved()) {
                                break;
                            }
                        }
                    }
                } else {
                    System.err.println("Method failed: " + method.getStatusLine());
                }
            } catch (HttpException e) {
                System.err.println("Fatal protocol violation: " + e.getMessage());
                e.printStackTrace();
            } catch (IOException e) {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException ex) {
                        System.err.println("Fatal transport error: " + ex.getMessage());
                    }
                }
                System.err.println("Fatal transport error: " + e.getMessage());
                e.printStackTrace();
            } finally { // Release the connection.
                method.releaseConnection();

                fireSearchFinished(new ImageSearcherEvent(GoogleImageSearcher.this));
            }
        }
    };

    this.service.submit(run);
}

From source file:org.soasecurity.wso2.mutual.auth.oauth2.client.MutualSSLOAuthClient.java

public static void main(String[] args) throws Exception {

    File file = new File((new File(".")).getCanonicalPath() + File.separator + "src" + File.separator + "main"
            + File.separator + "resources" + File.separator + "keystore" + File.separator + keyStoreName);

    if (!file.exists()) {
        throw new Exception("Key Store file can not be found in " + file.getCanonicalPath());
    }/*from  w ww . j  a  va2s .c o  m*/

    //Set trust store, you need to import server's certificate of CA certificate chain in to this
    //key store
    System.setProperty("javax.net.ssl.trustStore", file.getCanonicalPath());
    System.setProperty("javax.net.ssl.trustStorePassword", keyStorePassword);

    //Set key store, this must contain the user private key
    //here we have use both trust store and key store as the same key store
    //But you can use a separate key store for key store an trust store.
    System.setProperty("javax.net.ssl.keyStore", file.getCanonicalPath());
    System.setProperty("javax.net.ssl.keyStorePassword", keyStorePassword);

    HttpClient client = new HttpClient();

    HttpMethod method = new PostMethod(endPoint);

    // Base64 encoded client id & secret
    method.setRequestHeader("Authorization",
            "Basic T09pN2dpUjUwdDZtUmU1ZkpmWUhVelhVa1QwYTpOOUI2dDZxQ0E2RFp2eTJPQkFIWDhjVlI1eUlh");
    method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    NameValuePair pair1 = new NameValuePair();
    pair1.setName("grant_type");
    pair1.setValue("x509");

    NameValuePair pair2 = new NameValuePair();
    pair2.setName("username");
    pair2.setValue("asela");

    NameValuePair pair3 = new NameValuePair();
    pair3.setName("password");
    pair3.setValue("asela");

    method.setQueryString(new NameValuePair[] { pair1, pair2, pair3 });

    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {

        System.out.println("Failed: " + method.getStatusLine());

    } else {

        byte[] responseBody = method.getResponseBody();

        System.out.println(new String(responseBody));
    }
}

From source file:org.tgta.tagger.AnnotationClient.java

public String request(HttpMethod method) throws AnnotationException {

    String response = null;//from w  w  w . jav a  2 s  . c  o m

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

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

        // Read the response body.
        //byte[] responseBody;
        InputStream in = method.getResponseBodyAsStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder out = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            out.append(line);
        }
        //System.out.println(out.toString());   //Prints the string content read from input stream
        reader.close();

        response = out.toString();

        //TODO Going to buffer response body of large or unknown size. 
        //Using getResponseBodyAsStream instead is recommended.

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        //response = new String(responseBody);

    } catch (HttpException e) {
        LOG.error("Fatal protocol violation: " + e.getMessage());
        throw new AnnotationException("Protocol error executing HTTP request.", e);
    } catch (IOException e) {
        LOG.error("Fatal transport error: " + e.getMessage());
        LOG.error(method.getQueryString());
        throw new AnnotationException("Transport error executing HTTP request.", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return response;

}

From source file:org.tuckey.web.filters.urlrewrite.RequestProxy.java

private static void setupResponseHeaders(HttpMethod httpMethod, HttpServletResponse hsResponse) {
    if (log.isInfoEnabled()) {
        log.info("setupResponseHeaders");
        log.info("status text: " + httpMethod.getStatusText());
        log.info("status line: " + httpMethod.getStatusLine());
    }// w w w .  java 2 s.co  m

    //filter the headers, which are copied from the proxy response. The http lib handles those itself.
    //Filtered out: the content encoding, the content length and cookies
    for (int i = 0; i < httpMethod.getResponseHeaders().length; i++) {
        Header h = httpMethod.getResponseHeaders()[i];
        if ("content-encoding".equalsIgnoreCase(h.getName())) {
            continue;
        } else if ("content-length".equalsIgnoreCase(h.getName())) {
            continue;
        } else if ("transfer-encoding".equalsIgnoreCase(h.getName())) {
            continue;
        } else if (h.getName().toLowerCase().startsWith("cookie")) {
            //retrieving a cookie which sets the session id will change the calling session: bad! So we skip this header.
            continue;
        } else if (h.getName().toLowerCase().startsWith("set-cookie")) {
            //retrieving a cookie which sets the session id will change the calling session: bad! So we skip this header.
            continue;
        }

        hsResponse.addHeader(h.getName(), h.getValue());
        if (log.isInfoEnabled())
            log.info("setting response parameter:" + h.getName() + ", value: " + h.getValue());
    }
    //fixme what about the response footers? (httpMethod.getResponseFooters())

    if (httpMethod.getStatusCode() != 200) {
        hsResponse.setStatus(httpMethod.getStatusCode());
    }
}

From source file:org.tuleap.mylyn.task.core.internal.client.rest.TuleapRestConnector.java

/**
 * Logs a debug message of the REST request/response.
 *
 * @param method// w  w w .  j  a  v a2 s .com
 *            The method executed
 * @param bodyReceived
 *            The response body received
 */
private void debugRestCall(HttpMethod method, String bodyReceived) {
    int responseStatus = method.getStatusCode();
    StringBuilder b = new StringBuilder();
    b.append(method.getName());
    b.append(" ").append(method.getPath()); //$NON-NLS-1$
    String qs = method.getQueryString();
    if (qs != null && !qs.isEmpty()) {
        b.append('?').append(method.getQueryString());
    }
    if (method instanceof EntityEnclosingMethod) {
        RequestEntity requestEntity = ((EntityEnclosingMethod) method).getRequestEntity();
        String body = ""; //$NON-NLS-1$
        if (requestEntity.isRepeatable()) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            try {
                requestEntity.writeRequest(os);
                body = os.toString("UTF-8"); //$NON-NLS-1$
            } catch (UnsupportedEncodingException e) {
                // Nothing to do
            } catch (IOException e) {
                // Nothing to do
            }
        }
        b.append("\nbody:\n").append(body.replaceAll(//$NON-NLS-1$
                "\"password\" *: *\".*\"", "\"password\":\"(hidden in debug)\"")); //$NON-NLS-1$ //$NON-NLS-2$
    }
    b.append("\n__________\nresponse:\n"); //$NON-NLS-1$
    b.append(method.getStatusLine()).append("\n"); //$NON-NLS-1$
    b.append("body:\n"); //$NON-NLS-1$
    b.append(bodyReceived);
    int status = IStatus.INFO;
    if (responseStatus != HttpURLConnection.HTTP_OK) {
        status = IStatus.ERROR;
    }
    this.logger.log(new Status(status, TuleapCoreActivator.PLUGIN_ID, b.toString()));
}

From source file:org.xwiki.xwoot.manager.internal.DefaultXWootManager.java

private String call(String service) {
    String xwootAppAddress = getXWootAppAddress();

    HttpMethod method = new GetMethod(xwootAppAddress + service);

    /* This is needed because the xwootApp servlet might send redirects to perform initializations */
    method.setFollowRedirects(true);/*from  w w  w. j  a  v a  2  s.  c o m*/

    try {
        getLogger().debug("Requesting: " + method.getURI());
        if (client.executeMethod(method) < 400) {
            String result = method.getResponseBodyAsString();
            getLogger().debug("Result: " + result);
            return result;
        }
        getLogger().info("Failed call: " + method.getStatusLine());
    } catch (CircularRedirectException e) {
        /*
         * Ignore. This could be normal. For example in the case of connecting/disconnecting the P2P network we call
         * the synchronize servlet that redirects to the boostrap that redirects to synchronize again, causing this
         * exception.
         */
    } catch (Exception ex) {
        getLogger().warn("Exception occured while calling [" + service + "] on [" + xwootAppAddress + "]", ex);
    } finally {
        // Release the connection, since HTTPClient reuses connections for improved performance
        method.releaseConnection();
    }
    return "failed";
}

From source file:org.xwiki.xwoot.manager.internal.DefaultXWootManager.java

private Map<String, Object> getStatusMap(String type) {
    String uri = String.format("%s/status?type=%s", getXWootAppAddress(), type);
    HttpMethod method = new GetMethod(uri);
    try {//  w w w .  j a v  a2  s . c  o m
        getLogger().debug("Requesting: " + method.getURI());
        if (client.executeMethod(method) < 400) {
            XStream xstream = new XStream(new DomDriver());
            Map<String, Object> result = (Map<String, Object>) xstream
                    .fromXML(method.getResponseBodyAsStream());
            getLogger().debug("Result: " + result);
            return result;
        }
        getLogger().info("Failed call: " + method.getStatusLine());
    } catch (Exception ex) {
        getLogger().warn("Exception occured while calling [" + uri + "]", ex);
    } finally {
        // Release the connection, since HTTPClient reuses connections for improved performance
        method.releaseConnection();
    }

    return new HashMap<String, Object>();
}

From source file:poisondog.demo.HttpClientDemo.java

public static void main(String[] args) {
    HttpClientDemo demo = new HttpClientDemo();
    HttpClient client = demo.create("account", "pa5sw0rd");
    HttpMethod method = new GetMethod("http://www.apache.org/");

    try {/*from  ww w. ja  v a  2 s.  c  o m*/
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }
        byte[] responseBody = method.getResponseBody();
        System.out.println(new String(responseBody));
    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }
}

From source file:pukiwikiCommunicator.connector.SaveButtonDebugFrame.java

private String connectToURL(String url) {
    this.println("connectButton.actionPerformed, url=" + url);
    //TODO add your code for connectButton.actionPerformed
    String pageText = null;/*  ww w.j ava 2 s. com*/
    client = new HttpClient();
    //      this.messageTextArea.append(url+"\n");
    String urlWithoutParameters = "";
    if (authDialog != null) {
        this.println("authDialog is not null");
        urlWithoutParameters = getUrlWithoutParameters(url);
        String registeredUrl = authDialog.getProperty("auth-url");
        this.println("urlWithoutParamaters=" + urlWithoutParameters);
        this.println("registeredUrl=" + registeredUrl);
        if (registeredUrl == null) {
            this.authDialog = null;
            pageText = this.connectToURL(url);
            return pageText;
        }
        if (registeredUrl.equals(urlWithoutParameters)) {
            this.println("registeredUrl == urlWithoutParameters");
            client.getParams().setAuthenticationPreemptive(true);
            // F?([UpX[h)??.
            String uname = authDialog.getID();
            char[] pwd = authDialog.getPassword();
            String pwdx = new String(pwd);
            String idPass = uname + ":" + pwdx;
            String authUrl = "basicAuth-" + urlWithoutParameters;
            this.setting.setProperty(authUrl, idPass);
            //             Credentials defaultcreds1 = new UsernamePasswordCredentials(uname, pwdx);
            Credentials defaultcreds1 = new UsernamePasswordCredentials(idPass);
            // FXR[v.
            AuthScope scope1 = new AuthScope(null, -1, null);
            // XR[vF?gZbg.
            client.getState().setCredentials(scope1, defaultcreds1);
        } else {
            this.authDialog = null;
            pageText = this.connectToURL(url);
            return pageText;
        }
    }
    try {
        this.println("new getMethiod(" + url + ")");
        HttpMethod method = new GetMethod(url);
        //          method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
        //               new DefaultHttpMethodRetryHandler(3, false));
        if (this.authDialog != null) {
            method.setDoAuthentication(true);
        }

        //          method.getParams().setContentCharset("UTF-8");
        int status = client.executeMethod(method);
        if (status != HttpStatus.SC_OK) {
            this.println("Method failed: " + method.getStatusLine());
            if ((method.getStatusLine()).toString().indexOf("401") >= 0) {
                this.authDialog = new AuthDialog(this);
                this.authInputFlag = false;
                urlWithoutParameters = getUrlWithoutParameters(url);
                this.authDialog.setProperty("auth-url", urlWithoutParameters);
                this.println("before waitUntilMessageIsReturned");
                //                   this.authDialog.start();
                this.authDialog.setVisible(true);
                if (this.setting != null) {
                    urlWithoutParameters = getUrlWithoutParameters(url);
                    String authUrl = "basicAuth-" + urlWithoutParameters;
                    String idPass = this.setting.getProperty(authUrl);
                    StringTokenizer st1 = new StringTokenizer(idPass, ":");
                    String id = "";
                    String pas = "";
                    if (st1 != null) {
                        id = st1.nextToken();
                        pas = st1.nextToken();
                        if (id != null)
                            this.authDialog.setID(id);
                        if (pas != null)
                            this.authDialog.setPassword(pas);
                    }
                }

                this.waitUntilMessageIsReturned(); //!!
                //                   this.authDialog.stop(); //!!
                this.authDialog.setVisible(false);
                this.println("after waitUntilMessageIsReturned");
                if (this.loginButtonPressed) {
                    this.println("loginButtonPressed");
                    pageText = this.connectToURL(url);
                }
                return pageText;
            }
        } else {
            pageText = this.getText(method);
            /*
            //          String txt=method.getResponseBodyAsString();
              InputStream is=method.getResponseBodyAsStream();
              InputStreamReader isr=new InputStreamReader(is,this.charset);
            //               InputStreamReader isr=new InputStreamReader(is,"UTF-8");
            //               InputStreamReader isr=new InputStreamReader(is);
              BufferedReader br=new BufferedReader(isr);
             String line="";
             pageText="";
             while(true){
               line=br.readLine();
               pageText=pageText+line+"\n";
                if(line==null) break;
                this.messageTextArea.append(line+"\n");
            //                 System.out.println(line);
             }
             */
        }
    } catch (Exception e) {
        this.println(e.toString() + "\n");
        e.printStackTrace();
        return null;
    }
    return pageText;
}