Example usage for org.apache.commons.httpclient HttpClient setConnectionTimeout

List of usage examples for org.apache.commons.httpclient HttpClient setConnectionTimeout

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpClient setConnectionTimeout.

Prototype

public void setConnectionTimeout(int paramInt)

Source Link

Usage

From source file:ExampleP2PHttpClient.java

public static void main(String[] args) {
    // initialize JXTA
    try {/*from w w w.  j  a v a2  s  . co  m*/
        // sign in and initialize the JXTA network; profile this peer and create it
        // if it doesn't exist
        P2PNetwork.signin("clientpeer", "clientpeerpassword", "TestNetwork", true);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    // register the P2P socket protocol factory
    Protocol jxtaHttp = new Protocol("p2phttp", new P2PProtocolSocketFactory(), 80);
    Protocol.registerProtocol("p2phttp", jxtaHttp);

    //create a singular HttpClient object
    HttpClient client = new HttpClient();

    //establish a connection within 50 seconds
    client.setConnectionTimeout(50000);

    String url = System.getProperty("url");
    if (url == null || url.equals("")) {
        System.out.println("You must provide a URL to access.  For example:");
        System.out.println("ant example-webclient-run -D--url=p2phttp://www.somedomain.foo");

        System.exit(1);
    }
    System.out.println("Connecting to " + url + "...");

    HttpMethod method = null;

    //create a method object
    method = new GetMethod(url);
    method.setFollowRedirects(true);
    method.setStrictMode(false);
    //} catch (MalformedURLException murle) {
    //    System.out.println("<url> argument '" + url
    //            + "' is not a valid URL");
    //    System.exit(-2);
    //}

    //execute the method
    String responseBody = null;
    try {
        client.executeMethod(method);
        responseBody = method.getResponseBodyAsString();
    } catch (HttpException he) {
        System.err.println("Http error connecting to '" + url + "'");
        System.err.println(he.getMessage());
        System.exit(-4);
    } catch (IOException ioe) {
        System.err.println("Unable to connect to '" + url + "'");
        System.exit(-3);
    }

    //write out the request headers
    System.out.println("*** Request ***");
    System.out.println("Request Path: " + method.getPath());
    System.out.println("Request Query: " + method.getQueryString());
    Header[] requestHeaders = method.getRequestHeaders();
    for (int i = 0; i < requestHeaders.length; i++) {
        System.out.print(requestHeaders[i]);
    }

    //write out the response headers
    System.out.println("*** Response ***");
    System.out.println("Status Line: " + method.getStatusLine());
    Header[] responseHeaders = method.getResponseHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        System.out.print(responseHeaders[i]);
    }

    //write out the response body
    System.out.println("*** Response Body ***");
    System.out.println(responseBody);

    //clean up the connection resources
    method.releaseConnection();
    method.recycle();

    System.exit(0);
}

From source file:edu.umd.cs.submit.CommandLineSubmit.java

public static void main(String[] args) {
    try {//w w  w . j a  v  a  2 s  .  c om
        Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
        File home = args.length > 0 ? new File(args[0]) : new File(".");

        Protocol.registerProtocol("easyhttps", easyhttps);
        File submitFile = new File(home, ".submit");
        File submitUserFile = new File(home, ".submitUser");
        File submitIgnoreFile = new File(home, ".submitIgnore");
        File cvsIgnoreFile = new File(home, ".cvsignore");

        if (!submitFile.canRead()) {
            System.out.println("Must perform submit from a directory containing a \".submit\" file");
            System.out.println("No such file found at " + submitFile.getCanonicalPath());
            System.exit(1);
        }

        Properties p = new Properties();
        p.load(new FileInputStream(submitFile));
        String submitURL = p.getProperty("submitURL");
        if (submitURL == null) {
            System.out.println(".submit file does not contain a submitURL");
            System.exit(1);
        }
        String courseName = p.getProperty("courseName");
        String courseKey = p.getProperty("courseKey");
        String semester = p.getProperty("semester");
        String projectNumber = p.getProperty("projectNumber");
        String authenticationType = p.getProperty("authentication.type");
        String baseURL = p.getProperty("baseURL");

        System.out.println("Submitting contents of " + home.getCanonicalPath());
        System.out.println(" as project " + projectNumber + " for course " + courseName);
        FilesToIgnore ignorePatterns = new FilesToIgnore();
        addIgnoredPatternsFromFile(cvsIgnoreFile, ignorePatterns);
        addIgnoredPatternsFromFile(submitIgnoreFile, ignorePatterns);

        FindAllFiles find = new FindAllFiles(home, ignorePatterns.getPattern());
        Collection<File> files = find.getAllFiles();

        boolean createdSubmitUser = false;
        Properties userProps = new Properties();
        if (submitUserFile.canRead()) {
            userProps.load(new FileInputStream(submitUserFile));
        }
        if (userProps.getProperty("cvsAccount") == null && userProps.getProperty("classAccount") == null
                || userProps.getProperty("oneTimePassword") == null) {
            System.out.println();
            System.out.println(
                    "We need to authenticate you and create a .submitUser file so you can submit your project");

            createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL);
            createdSubmitUser = true;
            userProps.load(new FileInputStream(submitUserFile));
        }

        MultipartPostMethod filePost = createFilePost(p, find, files, userProps);
        HttpClient client = new HttpClient();
        client.setConnectionTimeout(HTTP_TIMEOUT);
        int status = client.executeMethod(filePost);
        System.out.println(filePost.getResponseBodyAsString());
        if (status == 500 && !createdSubmitUser) {
            System.out.println("Let's try reauthenticating you");
            System.out.println();

            createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL);
            userProps.load(new FileInputStream(submitUserFile));
            filePost = createFilePost(p, find, files, userProps);
            client = new HttpClient();
            client.setConnectionTimeout(HTTP_TIMEOUT);
            status = client.executeMethod(filePost);
            System.out.println(filePost.getResponseBodyAsString());
        }
        if (status != HttpStatus.SC_OK) {
            System.out.println("Status code: " + status);
            System.exit(1);
        }
        System.out.println("Submission accepted");
    } catch (Exception e) {
        System.out.println();
        System.out.println("An Error has occured during submission!");
        System.out.println();
        System.out.println("[DETAILS]");
        System.out.println(e.getMessage());
        e.printStackTrace(System.out);
        System.out.println();
    }
}

From source file:com.thoughtworks.go.agent.launcher.ServerCall.java

public static ServerResponseWrapper invoke(HttpMethod method) throws Exception {
    HashMap<String, String> headers = new HashMap<String, String>();
    HttpClient httpClient = new HttpClient();
    httpClient.setConnectionTimeout(HTTP_TIMEOUT_IN_MILLISECONDS);
    try {//from w ww .  ja  v  a  2 s . co m
        final int status = httpClient.executeMethod(method);
        if (status == HttpStatus.SC_NOT_FOUND) {
            StringWriter sw = new StringWriter();
            PrintWriter out = new PrintWriter(sw);
            out.println("Return Code: " + status);
            out.println("Few Possible Causes: ");
            out.println("1. Your Go Server is down or not accessible.");
            out.println(
                    "2. This agent might be incompatible with your Go Server.Please fix the version mismatch between Go Server and Go Agent.");
            out.close();
            throw new Exception(sw.toString());
        }
        if (status != HttpStatus.SC_OK) {
            throw new Exception("Got status " + status + " " + method.getStatusText() + " from server");
        }
        for (Header header : method.getResponseHeaders()) {
            headers.put(header.getName(), header.getValue());
        }
        return new ServerResponseWrapper(headers, method.getResponseBodyAsStream());
    } catch (Exception e) {
        String message = "Couldn't access Go Server with base url: " + method.getURI() + ": " + e.toString();
        LOG.error(message);
        throw new Exception(message, e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.intellij.openapi.paths.WebReferencesAnnotatorBase.java

private static MyFetchResult doCheckUrl(String url) {
    final HttpClient client = new HttpClient();
    client.setTimeout(3000);//  w  ww .  j  av  a  2 s  .  c  o m
    client.setConnectionTimeout(3000);
    // see http://hc.apache.org/httpclient-3.x/cookies.html
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    try {
        final GetMethod method = new GetMethod(url);
        final int code = client.executeMethod(method);

        return code == HttpStatus.SC_OK || code == HttpStatus.SC_REQUEST_TIMEOUT ? MyFetchResult.OK
                : MyFetchResult.NONEXISTENCE;
    } catch (UnknownHostException e) {
        LOG.info(e);
        return MyFetchResult.UNKNOWN_HOST;
    } catch (IOException e) {
        LOG.info(e);
        return MyFetchResult.OK;
    } catch (IllegalArgumentException e) {
        LOG.debug(e);
        return MyFetchResult.OK;
    }
}

From source file:au.org.ala.spatial.util.UploadSpatialResource.java

public static String loadResource(String url, String extra, String username, String password,
        String resourcepath) {//from   www  .  j a v  a2 s . com
    String output = "";

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(10000);
    client.setTimeout(60000);

    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    File input = new File(resourcepath);

    PutMethod put = new PutMethod(url);
    put.setDoAuthentication(true);

    //put.addRequestHeader("Content-type", "application/zip");

    // Request content will be retrieved directly 
    // from the input stream 
    RequestEntity entity = new FileRequestEntity(input, "application/zip");
    put.setRequestEntity(entity);

    // Execute the request 
    try {
        int result = client.executeMethod(put);

        output = result + ": " + put.getResponseBodyAsString();

    } catch (Exception e) {
        e.printStackTrace(System.out);
        output = "0: " + e.getMessage();
    } finally {
        // Release current connection to the connection pool once you are done 
        put.releaseConnection();
    }

    return output;

}

From source file:au.org.ala.spatial.util.UploadSpatialResource.java

public static String loadSld(String url, String extra, String username, String password, String resourcepath) {
    System.out.println("loadSld url:" + url);
    System.out.println("path:" + resourcepath);

    String output = "";

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(10000);
    client.setTimeout(60000);//from  www . jav  a  2  s.co m

    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    client.getParams().setAuthenticationPreemptive(true);

    File input = new File(resourcepath);

    PutMethod put = new PutMethod(url);
    put.setDoAuthentication(true);

    // Request content will be retrieved directly
    // from the input stream
    RequestEntity entity = new FileRequestEntity(input, "application/vnd.ogc.sld+xml");
    put.setRequestEntity(entity);

    // Execute the request
    try {
        int result = client.executeMethod(put);

        output = result + ": " + put.getResponseBodyAsString();

    } catch (Exception e) {
        e.printStackTrace(System.out);
        output = "0: " + e.getMessage();
    } finally {
        // Release current connection to the connection pool once you are done
        put.releaseConnection();
    }

    return output;
}

From source file:au.org.ala.spatial.util.UploadSpatialResource.java

public static String loadCreateStyle(String url, String extra, String username, String password, String name) {
    System.out.println("loadCreateStyle url:" + url);
    System.out.println("name:" + name);

    String output = "";

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(10000);
    client.setTimeout(60000);//from  ww  w  .j  ava  2 s.  co m

    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    PostMethod post = new PostMethod(url);
    post.setDoAuthentication(true);

    // Execute the request
    try {
        // Request content will be retrieved directly
        // from the input stream
        File file = File.createTempFile("sld", "xml");
        FileWriter fw = new FileWriter(file);
        fw.append("<style><name>" + name + "</name><filename>" + name + ".sld</filename></style>");
        fw.close();
        RequestEntity entity = new FileRequestEntity(file, "text/xml");
        post.setRequestEntity(entity);

        int result = client.executeMethod(post);

        output = result + ": " + post.getResponseBodyAsString();

    } catch (Exception e) {
        e.printStackTrace(System.out);
        output = "0: " + e.getMessage();
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }

    return output;
}

From source file:au.org.ala.spatial.util.UploadSpatialResource.java

public static String assignSld(String url, String extra, String username, String password, String data) {
    System.out.println("assignSld url:" + url);
    System.out.println("data:" + data);

    String output = "";

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(10000);
    client.setTimeout(60000);/*from   ww  w  . java2s .c  om*/

    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    PutMethod put = new PutMethod(url);
    put.setDoAuthentication(true);

    // Execute the request
    try {
        // Request content will be retrieved directly
        // from the input stream
        File file = File.createTempFile("sld", "xml");
        System.out.println("file:" + file.getPath());
        FileWriter fw = new FileWriter(file);
        fw.append(data);
        fw.close();
        RequestEntity entity = new FileRequestEntity(file, "text/xml");
        put.setRequestEntity(entity);

        int result = client.executeMethod(put);

        output = result + ": " + put.getResponseBodyAsString();

    } catch (Exception e) {
        output = "0: " + e.getMessage();
        e.printStackTrace(System.out);
    } finally {
        // Release current connection to the connection pool once you are done
        put.releaseConnection();
    }

    return output;
}

From source file:au.org.ala.spatial.util.UploadSpatialResource.java

/**
 * sends a PUT or POST call to a URL using authentication and including a
 * file upload/*w  w w.j av a2  s.com*/
 *
 * @param type         one of UploadSpatialResource.PUT for a PUT call or
 *                     UploadSpatialResource.POST for a POST call
 * @param url          URL for PUT/POST call
 * @param username     account username for authentication
 * @param password     account password for authentication
 * @param resourcepath local path to file to upload, null for no file to
 *                     upload
 * @param contenttype  file MIME content type
 * @return server response status code as String or empty String if
 * unsuccessful
 */
public static String httpCall(int type, String url, String username, String password, String resourcepath,
        String contenttype) {
    String output = "";

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(10000);
    client.setTimeout(60000);
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    RequestEntity entity = null;
    if (resourcepath != null) {
        File input = new File(resourcepath);
        entity = new FileRequestEntity(input, contenttype);
    }

    HttpMethod call = null;
    ;
    if (type == PUT) {
        PutMethod put = new PutMethod(url);
        put.setDoAuthentication(true);
        if (entity != null) {
            put.setRequestEntity(entity);
        }
        call = put;
    } else if (type == POST) {
        PostMethod post = new PostMethod(url);
        if (entity != null) {
            post.setRequestEntity(entity);
        }
        call = post;
    } else {
        //SpatialLogger.log("UploadSpatialResource", "invalid type: " + type);
        return output;
    }

    // Execute the request 
    try {
        int result = client.executeMethod(call);

        output = result + ": " + call.getResponseBodyAsString();
    } catch (Exception e) {
        //SpatialLogger.log("UploadSpatialResource", "failed upload to: " + url);
        output = "0: " + e.getMessage();
        e.printStackTrace(System.out);
    } finally {
        // Release current connection to the connection pool once you are done 
        call.releaseConnection();
    }

    return output;
}

From source file:lucee.commons.net.http.httpclient3.HTTPEngine3Impl.java

private static void setTimeout(HttpClient client, long timeout) {
    if (timeout > 0) {
        client.setConnectionTimeout((int) timeout);
        client.setTimeout((int) timeout);
    }/*from   w ww  . j av a2s  . co m*/
}