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

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

Introduction

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

Prototype

public HttpConnectionManager getHttpConnectionManager()

Source Link

Usage

From source file:com.sun.faban.harness.webclient.ResultAction.java

/**
 * This method is responsible for uploading the runs to repository.
 * @param uploadSet//w w  w . j a v a 2s.  co  m
 * @param replaceSet
 * @return HashSet
 * @throws java.io.IOException
 */
public static HashSet<String> uploadRuns(String[] runIds, HashSet<File> uploadSet, HashSet<String> replaceSet)
        throws IOException {
    // 3. Upload the run
    HashSet<String> duplicates = new HashSet<String>();

    // Prepare run id set for cross checking.
    HashSet<String> runIdSet = new HashSet<String>(runIds.length);
    for (String runId : runIds) {
        runIdSet.add(runId);
    }

    // Prepare the parts for the request.
    ArrayList<Part> params = new ArrayList<Part>();
    params.add(new StringPart("host", Config.FABAN_HOST));
    for (String replaceId : replaceSet) {
        params.add(new StringPart("replace", replaceId));
    }
    for (File jarFile : uploadSet) {
        params.add(new FilePart("jarfile", jarFile));
    }
    Part[] parts = new Part[params.size()];
    parts = params.toArray(parts);

    // Send the request for each reposotory.
    for (URL repository : Config.repositoryURLs) {
        URL repos = new URL(repository, "/controller/uploader/upload_runs");
        PostMethod post = new PostMethod(repos.toString());
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(post);

        if (status == HttpStatus.SC_FORBIDDEN)
            logger.warning("Server denied permission to upload run !");
        else if (status == HttpStatus.SC_NOT_ACCEPTABLE)
            logger.warning("Run origin error!");
        else if (status != HttpStatus.SC_CREATED)
            logger.warning(
                    "Server responded with status code " + status + ". Status code 201 (SC_CREATED) expected.");
        for (File jarFile : uploadSet) {
            jarFile.delete();
        }

        String response = post.getResponseBodyAsString();

        if (status == HttpStatus.SC_CREATED) {

            StringTokenizer t = new StringTokenizer(response.trim(), "\n");
            while (t.hasMoreTokens()) {
                String duplicateRun = t.nextToken().trim();
                if (duplicateRun.length() > 0)
                    duplicates.add(duplicateRun.trim());
            }

            for (Iterator<String> iter = duplicates.iterator(); iter.hasNext();) {
                String runId = iter.next();
                if (!runIdSet.contains(runId)) {
                    logger.warning("Unexpected archive response from " + repos + ": " + runId);
                    iter.remove();
                }
            }
        } else {
            logger.warning("Message from repository: " + response);
        }
    }
    return duplicates;
}

From source file:com.arc.embeddedcdt.gui.jtag.ConfigJTAGTab.java

static private String executeCommandTcl(String ip, String command, File f) {
    PostMethod filePost = new PostMethod("http://" + ip + "/ram/cgi/execute.tcl");

    try {//from   w w  w.j  av  a2s  . co  m
        //         filePost.getParams().setBooleanParameter(
        //               HttpMethodParams.USE_EXPECT_CONTINUE, true);

        Part[] parts;
        if (f != null) {
            parts = new Part[] { new StringPart("form_command", command),
                    new FilePart("form_filecontent", "file", f) };
        } else {
            parts = new Part[] { new StringPart("form_command", command) };
        }
        MultipartRequestEntity re = new MultipartRequestEntity(parts, filePost.getParams());
        filePost.setRequestEntity(re);
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(filePost);
        if (status == HttpStatus.SC_OK) {
            String result = filePost.getResponseBodyAsString();

            Pattern p = Pattern.compile("(?s)Error: ([0-9]+)\n.*");
            Matcher m = p.matcher(result);
            if (!m.matches()) {
                throw new RuntimeException("Unknown result from execute.tcl: " + result);
            }
            Integer errorCode = Integer.parseInt(m.group(1));
            if (errorCode != 0) {
                throw new RuntimeException("Command \"" + command + "\" failed with error code " + errorCode);
            }
            p = Pattern.compile("(?s)Error: [0-9]+\n(.*)");
            m = p.matcher(result);
            if (!m.matches()) {
                throw new RuntimeException("Unknown result from execute.tcl: " + result);
            }
            return m.group(1);

        } else {
            throw new RuntimeException("Upload failed");
        }
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (HttpException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        filePost.releaseConnection();
    }
}

From source file:com.kodokux.github.api.GithubApiUtil.java

@NotNull
private static HttpClient getHttpClient(@Nullable GithubAuthData.BasicAuth basicAuth, boolean useProxy) {
    final HttpClient client = new HttpClient();
    HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
    params.setConnectionTimeout(CONNECTION_TIMEOUT); //set connection timeout (how long it takes to connect to remote host)
    params.setSoTimeout(CONNECTION_TIMEOUT); //set socket timeout (how long it takes to retrieve data from remote host)

    client.getParams().setContentCharset("UTF-8");
    // Configure proxySettings if it is required
    final HttpConfigurable proxySettings = HttpConfigurable.getInstance();
    if (useProxy && proxySettings.USE_HTTP_PROXY && !StringUtil.isEmptyOrSpaces(proxySettings.PROXY_HOST)) {
        client.getHostConfiguration().setProxy(proxySettings.PROXY_HOST, proxySettings.PROXY_PORT);
        if (proxySettings.PROXY_AUTHENTICATION) {
            client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                    proxySettings.PROXY_LOGIN, proxySettings.getPlainProxyPassword()));
        }//from  w  w  w  .  jav a2  s .  c om
    }
    if (basicAuth != null) {
        client.getParams().setCredentialCharset("UTF-8");
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(basicAuth.getLogin(), basicAuth.getPassword()));
    }
    return client;
}

From source file:com.piaoyou.util.ImageUtil.java

@SuppressWarnings("finally")
public static boolean compressImg(String imageUrl1, String path, int width, int height) {
    HttpClient client = null;
    GetMethod getMethod = null;/*w ww . j a v  a2 s .  com*/
    boolean b = true;

    try {
        URI Url = new URI(imageUrl1, false, "UTF-8");
        String imageUrl = Url.toString();
        client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager());
        //         
        client.getHttpConnectionManager().getParams().setConnectionTimeout(2000);
        //         ?
        client.getHttpConnectionManager().getParams().setSoTimeout(2000);
        String temStr = "";
        if (imageUrl.contains(".jpg")) {
            imageUrl = imageUrl.replace(" ", "BLANK");
            temStr = imageUrl.substring(imageUrl.lastIndexOf("/") + 1, imageUrl.lastIndexOf("."));
            imageUrl = imageUrl.replace(temStr, URLEncoder.encode(temStr, "UTF-8"));
            if (imageUrl.contains("eachnet"))
                imageUrl = URLEncoder.encode(imageUrl, "UTF-8");
            imageUrl = imageUrl.replaceAll("BLANK", "%20").replaceAll("%3A", ":").replaceAll("%2F", "/");
        }
        getMethod = new GetMethod(imageUrl);
        client.executeMethod(getMethod);
        ImageUtil.createThumbnail(getMethod.getResponseBodyAsStream(), path, width, height);
    } catch (Exception e) {
        b = false;
        delFile(path);
        e.printStackTrace();
    } finally {
        if (getMethod != null) {
            getMethod.releaseConnection();
        }
        return b;
    }
}

From source file:com.ibm.watson.apis.conversation_enhanced.filters.LookUp.java

private HttpClient getHttpClient() {
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    return client;
}

From source file:com.jaspersoft.ireport.jasperserver.ws.http.HCManager.java

public void cancel(HttpMethod method) {
    HttpClient client = null;
    HttpConnectionManager cmanager = client.getHttpConnectionManager();

    for (IProgressMonitor m : cmap.keySet()) {
        if (m.isCanceled()) {
            method.abort();/* w w  w . ja  va  2s.co  m*/
            cmap.remove(m);
        }
    }

}

From source file:de.innovationgate.wgpublisher.DefaultHttpClientFactory.java

public HttpClient createHttpClient() {
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(10 * 1000);
    client.getHttpConnectionManager().getParams().setSoTimeout(60 * 1000);

    if (_config != null && _config.getProxyConfiguration() != null
            && _config.getProxyConfiguration().isEnabled()) {
        if (_config.getProxyConfiguration().getHttpProxy() != null) {
            client.getHostConfiguration().setProxy(_config.getProxyConfiguration().getHttpProxy(),
                    _config.getProxyConfiguration().getHttpProxyPort());

            if (_config.getProxyConfiguration().getUser() != null) {
                client.getState().setProxyCredentials(AuthScope.ANY,
                        new UsernamePasswordCredentials(_config.getProxyConfiguration().getUser(),
                                _config.getProxyConfiguration().getPassword()));
            }/*from   ww  w  . ja v a 2 s.co  m*/
        }

    }

    return client;
}

From source file:example.nz.org.take.compiler.userv.main.DUIConvictionInfoSource.java

@Override
public ResourceIterator<hasBeenConvictedOfaDUI> fetch(Driver driver) {

    HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
    client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
    GetMethod get = new GetMethod(URL);
    get.setFollowRedirects(true);/*from w w  w.j a  v a2 s  . c  o m*/
    get.setQueryString(new NameValuePair[] { new NameValuePair("id", driver.getId()) });
    try {
        logger.info("DUI conviction lookup " + get.getURI());
        client.executeMethod(get);
        String response = get.getResponseBodyAsString();
        logger.info("DUI conviction lookup result: " + response);
        if (response != null && "true".equals(response.trim())) {
            hasBeenConvictedOfaDUI record = new hasBeenConvictedOfaDUI();
            record.slot1 = driver;
            get.releaseConnection();
            return new SingletonIterator<hasBeenConvictedOfaDUI>(record);
        }
    } catch (Exception e) {
        logger.error("Error connecting to web service " + URL);
    }
    return EmptyIterator.DEFAULT;

}

From source file:com.simplifide.core.net.LicenseConnection.java

public void connect() {
    HttpClientParams params = new HttpClientParams();
    params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
    params.setIntParameter(HttpClientParams.MAX_REDIRECTS, 4);

    HttpClient client = new HttpClient(params);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);

    GetMethod post = new GetMethod("http://simplifide.com/drupal/free_trial2");
    post.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    /* NameValuePair[] data = {
        new NameValuePair("user_name", "joe"),
        new NameValuePair("password", "aaa"),
        new NameValuePair("name", "joker"),
        new NameValuePair("email", "beta"),
      };//  w  ww  .  j  a va  2s . c  om
      post.setRequestBody(data);
      */
    try {
        int rettype = client.executeMethod(post);

        byte[] responseBody = post.getResponseBody();

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

    } catch (HttpException e) {

        HardwareLog.logError(e);
    } catch (IOException e) {

        HardwareLog.logError(e);
    } finally {
        post.releaseConnection();
    }

}

From source file:com.knowledgebooks.rdf.SparqlClient.java

public SparqlClient(String endpoint_URL, String sparql) throws Exception {
    //System.out.println("SparqlClient("+endpoint_URL+", "+sparql+")");
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);

    String req = URLEncoder.encode(sparql, "utf-8");
    HttpMethod method = new GetMethod(endpoint_URL + "?query=" + req);
    method.setFollowRedirects(false);/*from  www.  ja  va 2  s.c o m*/
    try {
        client.executeMethod(method);
        //System.out.println(method.getResponseBodyAsString());
        //if (true) return;
        InputStream ins = method.getResponseBodyAsStream();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser sax = factory.newSAXParser();
        sax.parse(ins, this);
    } catch (HttpException he) {
        System.err.println("Http error connecting to '" + endpoint_URL + "'");
    } catch (IOException ioe) {
        System.err.println("Unable to connect to '" + endpoint_URL + "'");
    }
    method.releaseConnection();
}