Example usage for org.apache.commons.httpclient.params HttpClientParams HttpClientParams

List of usage examples for org.apache.commons.httpclient.params HttpClientParams HttpClientParams

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.params HttpClientParams HttpClientParams.

Prototype

public HttpClientParams() 

Source Link

Usage

From source file:com.znsx.cms.service.impl.DeviceManagerImpl.java

private List<Element> requestSubDeviceStatus(String subSn, List<String> devices) {
    String url = Configuration.getInstance().getProperties(subSn);
    // url?//  w w  w  .ja  v  a  2s .c o m
    if (StringUtils.isBlank(url)) {
        System.out.println("Sub platform[" + subSn + "] not in config.properties !");
        return new LinkedList<Element>();
    }
    // urlIP:Port?
    String[] address = url.split(":");
    if (address.length != 2) {
        System.out.println("Sub platform[" + subSn + "] config url[" + url + "] is invalid !");
        return new LinkedList<Element>();
    }
    // ?
    if (isSelfAddress(address[0])) {
        System.out.println("Sub platform[" + subSn + "] address can not be my address !");
        return new LinkedList<Element>();
    }

    StringBuffer sb = new StringBuffer();
    sb.append("<Request Method=\"List_Device_Status\" Cmd=\"1017\">");
    sb.append(System.getProperty("line.separator"));
    for (String sn : devices) {
        sb.append("  <Device StandardNumber=\"");
        sb.append(sn);
        sb.append("\" />");
        sb.append(System.getProperty("line.separator"));
    }
    sb.append("</Request>");
    String body = sb.toString();
    HttpClient client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
    client.getHttpConnectionManager().getParams().setConnectionTimeout(20000);
    PostMethod method = new PostMethod("http://" + url + "/cms/list_device_status.xml");
    System.out.println("Send request to " + url + " body is :");
    System.out.println(body);
    try {
        RequestEntity entity = new StringRequestEntity(body, "application/xml", "utf8");
        method.setRequestEntity(entity);
        client.executeMethod(method);
        // 
        SAXBuilder builder = new SAXBuilder();
        Document respDoc = builder.build(method.getResponseBodyAsStream());
        String code = respDoc.getRootElement().getAttributeValue("Code");
        if (ErrorCode.SUCCESS.equals(code)) {
            List<Element> list = respDoc.getRootElement().getChildren("Device");
            return list;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }
    return new LinkedList<Element>();
}

From source file:ome.formats.importer.util.FileUploader.java

/**
 * Upload files from error container to url
 *
 * @param url - url to send to//  ww  w . j av a  2s .  com
 * @param timeout - timeout
 * @param upload - error container with files in it
 */
public void uploadFiles(String url, int timeout, ErrorContainer upload) {
    if (client == null)
        client = new HttpClient();

    this.files = upload.getFiles();
    setSessionId(upload.getToken());

    int fileCount = 0;

    for (String f : files) {
        if (cancelUpload) {
            System.err.println(cancelUpload);
            continue;
        }

        fileCount++;
        final int count = fileCount;
        final File file = new File(f);

        try {
            HttpClientParams params = new HttpClientParams();
            params.setConnectionManagerTimeout(timeout);
            client.setParams(params);

            method = new PostMethod(url);

            String format = "";

            if (upload.getFileFormat() != null)
                format = upload.getFileFormat();
            else
                format = "unknown";

            final ErrorFilePart errorFilePart = new ErrorFilePart("Filedata", file);

            Part[] parts = { new StringPart("token", upload.getToken()), new StringPart("file_format", format),
                    errorFilePart };

            final long fileLength = file.length();

            MultipartRequestEntity mpre = new MultipartRequestEntity(parts, method.getParams());

            ProgressListener listener = new ProgressListener() {

                private long partsTotal = -1;

                /* (non-Javadoc)
                 * @see ome.formats.importer.util.FileUploadCounter.ProgressListener#update(long)
                 */
                public void update(long bytesRead) {

                    if (cancelUpload)
                        errorFilePart.cancel = true;

                    long partsDone = 0;
                    long parts = (long) Math.ceil(fileLength / 10.0f);
                    if (fileLength != 0)
                        partsDone = bytesRead / parts;

                    if (partsTotal == partsDone) {
                        return;
                    }
                    partsTotal = partsDone;

                    notifyObservers(new ImportEvent.FILE_UPLOAD_STARTED(file.getName(), count, files.length,
                            null, null, null));

                    long uploadedBytes = bytesRead / 2;
                    if (fileLength == -1) {

                        notifyObservers(new ImportEvent.FILE_UPLOAD_BYTES(file.getName(), count, files.length,
                                uploadedBytes, null, null));

                    } else {

                        notifyObservers(new ImportEvent.FILE_UPLOAD_BYTES(file.getName(), count, files.length,
                                uploadedBytes, fileLength, null));

                    }
                }
            };

            FileUploadCounter hfre = new FileUploadCounter(mpre, listener);

            method.setRequestEntity(hfre);

            int status = client.executeMethod(method);

            if (status == HttpStatus.SC_OK) {

                notifyObservers(new ImportEvent.FILE_UPLOAD_COMPLETE(file.getName(), count, files.length, null,
                        null, null));
                log.info("Uploaded file '" + file.getName() + "' to QA system");
                upload.setStatus(1);

            } else {
                notifyObservers(new ImportEvent.FILE_UPLOAD_COMPLETE(file.getName(), count, files.length, null,
                        null, null));
            }
        } catch (Exception ex) {
            notifyObservers(
                    new ImportEvent.FILE_UPLOAD_ERROR(file.getName(), count, files.length, null, null, ex));
        }
    }

    notifyObservers(new ImportEvent.FILE_UPLOAD_FINISHED(null, 0, 0, null, null, null));

}

From source file:ome.formats.importer.util.HtmlMessenger.java

/**
 * Instantiate html messenger//from w  w w.  j  a  va  2s . co m
 *
 * @param url
 * @param postList - variables list in post
 * @throws HtmlMessengerException
 */
public HtmlMessenger(String url, List<Part> postList) throws HtmlMessengerException {
    try {
        HostConfiguration cfg = new HostConfiguration();
        cfg.setHost(url);
        String proxyHost = System.getProperty(PROXY_HOST);
        String proxyPort = System.getProperty(PROXY_PORT);
        if (proxyHost != null && proxyPort != null) {
            int port = Integer.parseInt(proxyPort);
            cfg.setProxy(proxyHost, port);
        }

        client = new HttpClient();
        client.setHostConfiguration(cfg);
        HttpClientParams params = new HttpClientParams();
        params.setConnectionManagerTimeout(CONN_TIMEOUT);
        params.setSoTimeout(CONN_TIMEOUT);
        client.setParams(params);

        method = new PostMethod(url);

        Part[] parts = new Part[postList.size()];

        int i = 0;
        for (Part part : postList) {
            parts[i] = part;
            i++;
        }

        MultipartRequestEntity mpre = new MultipartRequestEntity(parts, method.getParams());

        ProgressListener listener = new ProgressListener() {
            /* (non-Javadoc)
             * @see ome.formats.importer.util.FileUploadCounter.ProgressListener#update(long)
             */
            public void update(long bytesRead) {
            }
        };

        FileUploadCounter hfre = new FileUploadCounter(mpre, listener);

        method.setRequestEntity(hfre);

    } catch (Exception e) {
        e.printStackTrace();
        throw new HtmlMessengerException("Error creating post parameters", e);
    }

}

From source file:org.anhonesteffort.flock.webdav.DavClient.java

protected void initClient() {
    HttpClientParams params = new HttpClientParams();
    List<String> authPrefs = new ArrayList<String>(2);

    authPrefs.add(AuthPolicy.DIGEST);/*  ww  w  .  j  a  v a2  s  . c o m*/
    authPrefs.add(AuthPolicy.BASIC);
    params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    params.setAuthenticationPreemptive(true);

    client = new HttpClient(params);
    hostConfiguration = client.getHostConfiguration();
    connectionManager = client.getHttpConnectionManager();

    hostConfiguration.setHost(davHost.getHost(), davHost.getPort(),
            Protocol.getProtocol(davHost.getProtocol()));

    Credentials credentials = new UsernamePasswordCredentials(davUsername, davPassword);
    client.getState().setCredentials(AuthScope.ANY, credentials);
}

From source file:org.apache.camel.component.http.HttpComponent.java

@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters)
        throws Exception {
    String addressUri = "http://" + remaining;
    if (uri.startsWith("https:")) {
        addressUri = "https://" + remaining;
    }/*from  w  w w.ja v  a2s  .  c  o m*/
    Map<String, Object> httpClientParameters = new HashMap<String, Object>(parameters);
    // must extract well known parameters before we create the endpoint
    // TODO cmueller: remove the "httpBindingRef" look up in Camel 3.0
    HttpBinding binding = resolveAndRemoveReferenceParameter(parameters, "httpBindingRef", HttpBinding.class);
    if (binding == null) {
        // try without ref
        binding = resolveAndRemoveReferenceParameter(parameters, "httpBinding", HttpBinding.class);
    }
    String proxyHost = getAndRemoveParameter(parameters, "proxyHost", String.class);
    Integer proxyPort = getAndRemoveParameter(parameters, "proxyPort", Integer.class);
    String authMethodPriority = getAndRemoveParameter(parameters, "authMethodPriority", String.class);
    HeaderFilterStrategy headerFilterStrategy = resolveAndRemoveReferenceParameter(parameters,
            "headerFilterStrategy", HeaderFilterStrategy.class);
    UrlRewrite urlRewrite = resolveAndRemoveReferenceParameter(parameters, "urlRewrite", UrlRewrite.class);
    // http client can be configured from URI options
    HttpClientParams clientParams = new HttpClientParams();
    IntrospectionSupport.setProperties(clientParams, parameters, "httpClient.");
    // validate that we could resolve all httpClient. parameters as this component is lenient
    validateParameters(uri, parameters, "httpClient.");
    // http client can be configured from URI options
    HttpConnectionManagerParams connectionManagerParams = new HttpConnectionManagerParams();
    // setup the httpConnectionManagerParams
    IntrospectionSupport.setProperties(connectionManagerParams, parameters, "httpConnectionManager.");
    validateParameters(uri, parameters, "httpConnectionManager.");
    // make sure the component httpConnectionManager is take effect
    HttpConnectionManager thisHttpConnectionManager = httpConnectionManager;
    if (thisHttpConnectionManager == null) {
        // only set the params on the new created http connection manager
        thisHttpConnectionManager = new MultiThreadedHttpConnectionManager();
        thisHttpConnectionManager.setParams(connectionManagerParams);
    }
    // create the configurer to use for this endpoint (authMethods contains the used methods created by the configurer)
    final Set<AuthMethod> authMethods = new LinkedHashSet<AuthMethod>();
    HttpClientConfigurer configurer = createHttpClientConfigurer(parameters, authMethods);
    addressUri = UnsafeUriCharactersEncoder.encodeHttpURI(addressUri);
    URI endpointUri = URISupport.createRemainingURI(new URI(addressUri), httpClientParameters);

    // create the endpoint and connectionManagerParams already be set
    HttpEndpoint endpoint = new HttpEndpoint(endpointUri.toString(), this, clientParams,
            thisHttpConnectionManager, configurer);

    if (headerFilterStrategy != null) {
        endpoint.setHeaderFilterStrategy(headerFilterStrategy);
    } else {
        setEndpointHeaderFilterStrategy(endpoint);
    }
    if (urlRewrite != null) {
        // let CamelContext deal with the lifecycle of the url rewrite
        // this ensures its being shutdown when Camel shutdown etc.
        getCamelContext().addService(urlRewrite);
        endpoint.setUrlRewrite(urlRewrite);
    }

    // prefer to use endpoint configured over component configured
    if (binding == null) {
        // fallback to component configured
        binding = getHttpBinding();
    }
    if (binding != null) {
        endpoint.setBinding(binding);
    }
    if (proxyHost != null) {
        endpoint.setProxyHost(proxyHost);
        endpoint.setProxyPort(proxyPort);
    } else if (httpConfiguration != null) {
        endpoint.setProxyHost(httpConfiguration.getProxyHost());
        endpoint.setProxyPort(httpConfiguration.getProxyPort());
    }
    if (authMethodPriority != null) {
        endpoint.setAuthMethodPriority(authMethodPriority);
    } else if (httpConfiguration != null && httpConfiguration.getAuthMethodPriority() != null) {
        endpoint.setAuthMethodPriority(httpConfiguration.getAuthMethodPriority());
    } else {
        // no explicit auth method priority configured, so use convention over configuration
        // and set priority based on auth method
        if (!authMethods.isEmpty()) {
            authMethodPriority = CollectionHelper.collectionAsCommaDelimitedString(authMethods);
            endpoint.setAuthMethodPriority(authMethodPriority);
        }
    }
    setProperties(endpoint, parameters);
    // restructure uri to be based on the parameters left as we dont want to include the Camel internal options
    URI httpUri = URISupport.createRemainingURI(new URI(addressUri), parameters);

    // validate http uri that end-user did not duplicate the http part that can be a common error
    String part = httpUri.getSchemeSpecificPart();
    if (part != null) {
        part = part.toLowerCase();
        if (part.startsWith("//http//") || part.startsWith("//https//") || part.startsWith("//http://")
                || part.startsWith("//https://")) {
            throw new ResolveEndpointFailedException(uri,
                    "The uri part is not configured correctly. You have duplicated the http(s) protocol.");
        }
    }
    endpoint.setHttpUri(httpUri);
    return endpoint;
}

From source file:org.apache.camel.component.http.HttpEndpoint.java

public HttpEndpoint(String endPointURI, HttpComponent component, URI httpURI,
        HttpConnectionManager httpConnectionManager) throws URISyntaxException {
    this(endPointURI, component, httpURI, new HttpClientParams(), httpConnectionManager, null);
}

From source file:org.apache.camel.component.servlet.ServletComponent.java

@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters)
        throws Exception {
    HttpClientParams params = new HttpClientParams();
    IntrospectionSupport.setProperties(params, parameters, "httpClient.");

    // create the configurer to use for this endpoint
    final Set<AuthMethod> authMethods = new LinkedHashSet<AuthMethod>();
    HttpClientConfigurer configurer = createHttpClientConfigurer(parameters, authMethods);

    // must extract well known parameters before we create the endpoint
    Boolean throwExceptionOnFailure = getAndRemoveParameter(parameters, "throwExceptionOnFailure",
            Boolean.class);
    Boolean transferException = getAndRemoveParameter(parameters, "transferException", Boolean.class);
    Boolean bridgeEndpoint = getAndRemoveParameter(parameters, "bridgeEndpoint", Boolean.class);
    HttpBinding binding = resolveAndRemoveReferenceParameter(parameters, "httpBindingRef", HttpBinding.class);
    Boolean matchOnUriPrefix = getAndRemoveParameter(parameters, "matchOnUriPrefix", Boolean.class);
    String servletName = getAndRemoveParameter(parameters, "servletName", String.class, getServletName());
    String httpMethodRestrict = getAndRemoveParameter(parameters, "httpMethodRestrict", String.class);
    HeaderFilterStrategy headerFilterStrategy = resolveAndRemoveReferenceParameter(parameters,
            "headerFilterStrategy", HeaderFilterStrategy.class);

    // restructure uri to be based on the parameters left as we dont want to include the Camel internal options
    URI httpUri = URISupport.createRemainingURI(new URI(UnsafeUriCharactersEncoder.encodeHttpURI(uri)),
            parameters);//www  .  j  ava 2  s. c o  m

    ServletEndpoint endpoint = createServletEndpoint(uri, this, httpUri, params, getHttpConnectionManager(),
            configurer);
    endpoint.setServletName(servletName);
    if (headerFilterStrategy != null) {
        endpoint.setHeaderFilterStrategy(headerFilterStrategy);
    } else {
        setEndpointHeaderFilterStrategy(endpoint);
    }

    // prefer to use endpoint configured over component configured
    if (binding == null) {
        // fallback to component configured
        binding = getHttpBinding();
    }
    if (binding != null) {
        endpoint.setBinding(binding);
    }
    // should we use an exception for failed error codes?
    if (throwExceptionOnFailure != null) {
        endpoint.setThrowExceptionOnFailure(throwExceptionOnFailure);
    }
    // should we transfer exception as serialized object
    if (transferException != null) {
        endpoint.setTransferException(transferException);
    }
    if (bridgeEndpoint != null) {
        endpoint.setBridgeEndpoint(bridgeEndpoint);
    }
    if (matchOnUriPrefix != null) {
        endpoint.setMatchOnUriPrefix(matchOnUriPrefix);
    }
    if (httpMethodRestrict != null) {
        endpoint.setHttpMethodRestrict(httpMethodRestrict);
    }

    setProperties(endpoint, parameters);
    return endpoint;
}

From source file:org.apache.hadoop.yarn.server.webproxy.WebAppProxyServlet.java

/**
 * Download link and have it be the response.
 * @param req the http request//from ww  w .j av a  2s.  c  o  m
 * @param resp the http response
 * @param link the link to download
 * @param c the cookie to set if any
 * @throws IOException on any error.
 */
private static void proxyLink(HttpServletRequest req, HttpServletResponse resp, URI link, Cookie c,
        String proxyHost) throws IOException {
    org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(link.toString(), false);
    HttpClientParams params = new HttpClientParams();
    params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
    HttpClient client = new HttpClient(params);
    // Make sure we send the request from the proxy address in the config
    // since that is what the AM filter checks against. IP aliasing or
    // similar could cause issues otherwise.
    HostConfiguration config = new HostConfiguration();
    InetAddress localAddress = InetAddress.getByName(proxyHost);
    if (LOG.isDebugEnabled()) {
        LOG.debug("local InetAddress for proxy host: " + localAddress.toString());
    }
    config.setLocalAddress(localAddress);
    HttpMethod method = new GetMethod(uri.getEscapedURI());
    @SuppressWarnings("unchecked")
    Enumeration<String> names = req.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        if (passThroughHeaders.contains(name)) {
            String value = req.getHeader(name);
            LOG.debug("REQ HEADER: " + name + " : " + value);
            method.setRequestHeader(name, value);
        }
    }

    String user = req.getRemoteUser();
    if (user != null && !user.isEmpty()) {
        method.setRequestHeader("Cookie", PROXY_USER_COOKIE_NAME + "=" + URLEncoder.encode(user, "ASCII"));
    }
    OutputStream out = resp.getOutputStream();
    try {
        resp.setStatus(client.executeMethod(config, method));
        for (Header header : method.getResponseHeaders()) {
            resp.setHeader(header.getName(), header.getValue());
        }
        if (c != null) {
            resp.addCookie(c);
        }
        InputStream in = method.getResponseBodyAsStream();
        if (in != null) {
            IOUtils.copyBytes(in, out, 4096, true);
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:org.archive.wayback.liveweb.ArcRemoteLiveWebCache.java

/**
 * //  w  ww  . ja  v a  2s  .c  om
 */
public ArcRemoteLiveWebCache() {
    connectionManager = new MultiThreadedHttpConnectionManager();
    hostConfiguration = new HostConfiguration();
    HttpClientParams params = new HttpClientParams();
    params.setParameter(HttpClientParams.RETRY_HANDLER, new NoRetryHandler());
    http = new HttpClient(params, connectionManager);
    http.setHostConfiguration(hostConfiguration);
}

From source file:org.archive.wayback.liveweb.RemoteLiveWebCache.java

/**
 * /*from   ww  w  .j  ava  2 s. c  om*/
 */
public RemoteLiveWebCache() {
    connectionManager = new MultiThreadedHttpConnectionManager();
    hostConfiguration = new HostConfiguration();
    HttpClientParams params = new HttpClientParams();
    params.setParameter(HttpClientParams.RETRY_HANDLER, new NoRetryHandler());
    http = new HttpClient(params, connectionManager);
    http.setHostConfiguration(hostConfiguration);
}