Example usage for org.apache.http.client.fluent Request viaProxy

List of usage examples for org.apache.http.client.fluent Request viaProxy

Introduction

In this page you can find the example usage for org.apache.http.client.fluent Request viaProxy.

Prototype

public Request viaProxy(final HttpHost proxy) 

Source Link

Usage

From source file:eu.esdihumboldt.util.http.client.fluent.FluentProxyUtil.java

/**
 * setup the given request object to go via proxy
 * /*from w w w  . j  av  a 2 s. c om*/
 * @param request A fluent request
 * @param proxy applying proxy to the fluent request
 * @return Executor, for a fluent request
 */
public static Executor setProxy(Request request, Proxy proxy) {
    ProxyUtil.init();
    Executor executor = Executor.newInstance();

    if (proxy != null && proxy.type() == Type.HTTP) {
        InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();

        // set the proxy
        HttpHost proxyHost = new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort());
        request.viaProxy(proxyHost);

        String userName = System.getProperty("http.proxyUser");
        String password = System.getProperty("http.proxyPassword");

        boolean useProxyAuth = userName != null && !userName.isEmpty();

        if (useProxyAuth) {
            Credentials cred = ClientProxyUtil.createCredentials(userName, password);

            executor.auth(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()), cred);
        }
    }
    return executor;
}

From source file:com.jaspersoft.studio.server.protocol.restv2.CASUtil.java

public static String doGetTocken(ServerProfile sp, SSOServer srv, IProgressMonitor monitor) throws Exception {
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            // System.out.println("getAcceptedIssuers =============");
            return null;
        }//w  w  w.  java  2 s.  com

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("checkClientTrusted =============");
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("checkServerTrusted =============");
        }
    } }, new SecureRandom());

    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
            .setRedirectStrategy(new DefaultRedirectStrategy() {
                @Override
                protected boolean isRedirectable(String arg0) {
                    // TODO Auto-generated method stub
                    return super.isRedirectable(arg0);
                }

                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    // TODO Auto-generated method stub
                    return super.isRedirected(request, response, context);
                }
            }).setDefaultCookieStore(new BasicCookieStore())
            .setUserAgent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0")
            .build();

    Executor exec = Executor.newInstance(httpclient);

    URIBuilder ub = new URIBuilder(sp.getUrl() + "index.html");

    String fullURL = ub.build().toASCIIString();
    Request req = HttpUtils.get(fullURL, sp);
    HttpHost proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    String tgtID = readData(exec, req, monitor);
    String action = getFormAction(tgtID);
    if (action != null) {
        action = action.replaceFirst("/", "");
        int indx = action.indexOf(";jsession");
        if (indx >= 0)
            action = action.substring(0, indx);
    } else
        action = "cas/login";
    String url = srv.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub = new URIBuilder(url + action);
    //
    fullURL = ub.build().toASCIIString();
    req = HttpUtils.get(fullURL, sp);
    proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    tgtID = readData(exec, req, monitor);
    action = getFormAction(tgtID);
    action = action.replaceFirst("/", "");

    ub = new URIBuilder(url + action);
    Map<String, String> map = getInputs(tgtID);
    Form form = Form.form();
    for (String key : map.keySet()) {
        if (key.equals("btn-reset"))
            continue;
        else if (key.equals("username")) {
            form.add(key, srv.getUser());
            continue;
        } else if (key.equals("password")) {
            form.add(key, Pass.getPass(srv.getPassword()));
            continue;
        }
        form.add(key, map.get(key));
    }
    //
    req = HttpUtils.post(ub.build().toASCIIString(), form, sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // Header header = null;
    readData(exec, req, monitor);
    // for (Header h : headers) {
    // for (HeaderElement he : h.getElements()) {
    // if (he.getName().equals("CASTGC")) {
    // header = new BasicHeader("Cookie", h.getValue());
    // break;
    // }
    // }
    // }
    ub = new URIBuilder(url + action);
    url = sp.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub.addParameter("service", url + "j_spring_security_check");

    req = HttpUtils.get(ub.build().toASCIIString(), sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // req.addHeader("Accept",
    // "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8, value");
    req.addHeader("Referrer", sp.getUrl());
    // req.addHeader(header);
    String html = readData(exec, req, monitor);
    Matcher matcher = ahrefPattern.matcher(html);
    while (matcher.find()) {
        Map<String, String> attributes = parseAttributes(matcher.group(1));
        String v = attributes.get("href");
        int ind = v.indexOf("ticket=");
        if (ind > 0) {
            return v.substring(ind + "ticket=".length());
        }
    }
    return null;
}

From source file:com.github.woki.payments.adyen.action.Endpoint.java

private static Request createPost(APService service, ClientConfig config, Object request) {
    Request retval = Post(config.getEndpointPort(service));
    // configure conn timeout
    retval.connectTimeout(config.getConnectionTimeout());
    // configure socket timeout
    retval.socketTimeout(config.getSocketTimeout());
    // add json//from  w  w w .j  av a2 s  .c o m
    retval.addHeader("Content-Type", "application/json");
    retval.addHeader("Accept", "application/json");
    for (Map.Entry<String, String> entry : config.getExtraParameters().entrySet()) {
        retval.addHeader(entry.getKey(), entry.getValue());
    }
    // add content
    String bodyString;
    try {
        bodyString = MAPPER.writeValueAsString(encrypt(config, request));
    } catch (Exception e) {
        throw new RuntimeException("CSE/JSON serialization error", e);
    }
    retval.bodyString(bodyString, ContentType.APPLICATION_JSON);
    if (config.hasProxy()) {
        retval.viaProxy(config.getProxyHost());
    }
    return retval;
}

From source file:com.helger.peppol.httpclient.AbstractGenericSMPClient.java

/**
 * The main execution routine. Overwrite this method to add additional
 * properties to the call.//  ww  w .  j a v  a 2  s.  c o m
 *
 * @param aRequest
 *        The request to be executed. Never <code>null</code>.
 * @return The HTTP execution response. Never <code>null</code>.
 * @throws IOException
 *         On HTTP error
 * @see #setProxy(HttpHost)
 * @see #setConnectionTimeoutMS(int)
 * @see #setRequestTimeoutMS(int)
 */
@Nonnull
@OverrideOnDemand
protected Response executeRequest(@Nonnull final Request aRequest) throws IOException {
    if (m_aProxy != null)
        aRequest.viaProxy(m_aProxy);
    if (m_nConnectionTimeoutMS > 0)
        aRequest.connectTimeout(m_nConnectionTimeoutMS);
    if (m_nRequestTimeoutMS > 0)
        aRequest.socketTimeout(m_nRequestTimeoutMS);

    return aRequest.execute();
}

From source file:com.helger.peppol.bdxrclient.BDXRClientReadOnly.java

/**
 * The main execution routine. Overwrite this method to add additional
 * properties to the call.//  w  ww  .ja  v a 2s. com
 *
 * @param aRequest
 *        The request to be executed. Never <code>null</code>.
 * @return The HTTP execution response. Never <code>null</code>.
 * @throws IOException
 *         On HTTP error
 */
@Nonnull
@OverrideOnDemand
protected Response executeRequest(@Nonnull final Request aRequest) throws IOException {
    if (m_aProxy != null)
        aRequest.viaProxy(m_aProxy);
    return aRequest.connectTimeout(5000).socketTimeout(10000).execute();
}

From source file:be.fedict.dcat.datagovbe.Drupal.java

/**
 * Check if dataset with ID already exists on drupal site.
 * // w  w  w .j  a  va 2  s . c  o  m
 * @param id
 * @param lang
 * @return 
 */
private String checkExists(String id, String lang) {
    String node = "";

    String u = this.url.toString() + "/" + lang + "/" + Drupal.TYPE_DATA + "/" + id;

    Request r = Request.Head(u);
    if (proxy != null) {
        r.viaProxy(proxy);
    }

    try {
        HttpResponse resp = exec.execute(r).returnResponse();
        Header header = resp.getFirstHeader("Link");
        if (header != null) {
            Matcher m = SHORTLINK.matcher(header.getValue());
            if (m.find()) {
                node = m.group(1);
                logger.info("Dataset {} exists, node {}", id, node);
            }
        }
    } catch (IOException ex) {
        logger.error("Exception getting dataset {}", id);
    }

    return node;
}

From source file:com.qwazr.crawler.web.driver.BrowserDriver.java

void httpClientDownload(String url, String userAgent, File file) throws NoSuchAlgorithmException,
        KeyStoreException, KeyManagementException, IOException, URISyntaxException {
    URI uri = new URI(url);
    final CloseableHttpClient httpClient = HttpUtils.createHttpClient_AcceptsUntrustedCerts();
    try {/* w w w  . ja  va2 s . c o  m*/
        final Executor executor = Executor.newInstance(httpClient);
        Request request = Request.Get(uri.toString()).addHeader("Connection", "close").connectTimeout(60000)
                .socketTimeout(60000);
        if (userAgent != null)
            request = request.addHeader("User-Agent", userAgent);
        if (currentProxy != null) {
            if (currentProxy.http_proxy != null && !currentProxy.http_proxy.isEmpty())
                request = request.viaProxy(currentProxy.http_proxy);
            if ("https".equals(uri.getScheme()) && currentProxy.ssl_proxy != null
                    && !currentProxy.ssl_proxy.isEmpty())
                request = request.viaProxy(currentProxy.ssl_proxy);
        }
        executor.execute(request).saveContent(file);
    } finally {
        IOUtils.close(httpClient);
    }
}

From source file:be.fedict.dcat.datagovbe.Drupal.java

/**
 * Get CSRF Token/*from   w  ww  .ja va  2  s. com*/
 * 
 * @throws IOException
 */
private void getCSRFToken() throws IOException {
    Request r = Request.Get(this.url.toString() + Drupal.TOKEN).setHeader(HttpHeaders.CACHE_CONTROL,
            "no-cache");

    if (proxy != null) {
        r.viaProxy(proxy);
    }
    token = exec.authPreemptive(host).execute(r).returnContent().asString();
    logger.debug("CSRF Token is {}", token);
}

From source file:com.jaspersoft.studio.statistics.UsageManager.java

/**
 * Check on the server if there is a newer version of Jaspersoft Studio
 * //from   w  w  w  . j a  v a 2s . c o  m
 * @return a not null VersionCheckResult that contains information on the new version and if there is a new version
 */
public VersionCheckResult checkVersion() {
    String uuid = getAppDataFolder().getName();
    String versionKnownByTheStats = getInstallationInfoContainer().getProperty(VERSION_INFO);
    int newInstallation = 0;
    // Read if there is an UUID in the preferences used to track the older versions
    PropertiesHelper ph = PropertiesHelper.getInstance();
    String backward_uuid = ph.getString(BACKWARD_UUID_PROPERTY, null);
    if (backward_uuid == null) {
        // If the backward value is null then i'm already using the new system, check if it
        // is a new installation or an update
        if (versionKnownByTheStats == null) {
            // Since the last version was not yet initialized it is a new installation
            newInstallation = 1;
        } else if (!versionKnownByTheStats.equals(getVersion())) {
            // There is a version stored in the file, that is the last version known by the server, if it is
            // different from the real version then there were an update
            newInstallation = 2;
        }
    } else {
        // If the backward value is != null then it isn't for sure a new installation, maybe there were
        // but since i'm inside the new code then it should be an update.
        newInstallation = 2;
        setInstallationInfo(VERSION_INFO, getVersion());
    }

    StringBuilder urlBuilder = new StringBuilder();
    urlBuilder.append(HEARTBEAT_SERVER_URL);
    urlBuilder.append("?version=");//$NON-NLS-1$
    urlBuilder.append(getVersion());
    urlBuilder.append("&uuid=");//$NON-NLS-1$
    urlBuilder.append(uuid);
    urlBuilder.append("&new=");//$NON-NLS-1$
    urlBuilder.append(newInstallation);
    urlBuilder.append("&isRCP=");//$NON-NLS-1$
    urlBuilder.append(String.valueOf(isRCP()));

    String urlstr = urlBuilder.toString();
    System.out.println("Invoking URL: " + urlstr); //$NON-NLS-1$ 
    VersionCheckResult result = new VersionCheckResult();
    try {
        Executor exec = Executor.newInstance();
        URI fullURI = new URI(urlstr);
        HttpUtils.setupProxy(exec, fullURI);
        HttpHost proxy = HttpUtils.getUnauthProxy(exec, fullURI);
        Request req = Request.Get(urlstr);
        if (proxy != null)
            req.viaProxy(proxy);
        String response = exec.execute(req).returnContent().asString();

        String serverVersion = null;
        String optmsg = ""; //$NON-NLS-1$ 
        for (String inputLine : IOUtils.readLines(new StringReader(response))) {
            if (serverVersion == null) {
                serverVersion = inputLine.trim();
            } else {
                optmsg += inputLine;
            }
        }
        // Update the installation info only if the informations was given correctly to the server
        setInstallationInfo(VERSION_INFO, getVersion());
        // Remove the old backward compatibility value if present to switch to the new system
        if (backward_uuid != null) {
            ph.removeString(BACKWARD_UUID_PROPERTY, InstanceScope.SCOPE);
        }
        result = new VersionCheckResult(serverVersion, optmsg, getVersion());
    } catch (Exception ex) {
        ex.printStackTrace();
        JaspersoftStudioPlugin.getInstance().logError(Messages.UsageManager_errorUpdateCheck, ex);
    }
    return result;
}

From source file:be.fedict.dcat.datagovbe.Drupal.java

/**
 * Prepare a POST or PUT action./*from ww w. j  av  a  2 s  .  c  o  m*/
 * 
 * @param method POST or PUT
 * @param relpath relative path
 * @return 
 */
private Request prepare(String method, String relpath) {
    String u = this.url.toString() + relpath;

    Request r = method.equals(Drupal.POST) ? Request.Post(u) : Request.Put(u);

    r.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()).setHeader(Drupal.X_TOKEN,
            token);

    if (proxy != null) {
        r.viaProxy(proxy);
    }
    return r;
}