Example usage for org.apache.http.client.fluent Executor auth

List of usage examples for org.apache.http.client.fluent Executor auth

Introduction

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

Prototype

public Executor auth(final String username, final String password) 

Source Link

Usage

From source file:org.eclipse.epp.internal.logging.aeri.ui.utils.Proxies.java

public static Executor proxyAuthentication(Executor executor, URI target) throws IOException {
    IProxyData proxy = getProxyData(target).orNull();
    if (proxy != null) {
        HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort());
        if (proxy.getUserId() != null) {
            String userId = getUserName(proxy.getUserId()).orNull();
            String pass = proxy.getPassword();
            String workstation = getWorkstation().orNull();
            String domain = getUserDomain(proxy.getUserId()).orNull();
            return executor
                    .auth(new AuthScope(proxyHost, AuthScope.ANY_REALM, "ntlm"),
                            new NTCredentials(userId, pass, workstation, domain))
                    .auth(new AuthScope(proxyHost, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME),
                            new UsernamePasswordCredentials(userId, pass));
        } else {//from   w  w  w  .  j a v a  2s  .  com
            return executor;
        }
    }
    return executor;
}

From source file:org.eclipse.oomph.setup.internal.sync.SyncUtil.java

public static Executor proxyAuthentication(Executor executor, URI uri) throws IOException {
    IProxyData proxy = getProxyData(uri);
    if (proxy != null) {
        HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort());
        String proxyUserID = proxy.getUserId();
        if (proxyUserID != null) {
            String userID = getUserName(proxyUserID);
            String password = proxy.getPassword();
            String workstation = getWorkstation();
            String domain = getUserDomain(proxyUserID);
            return executor
                    .auth(new AuthScope(proxyHost, AuthScope.ANY_REALM, "ntlm"),
                            new NTCredentials(userID, password, workstation, domain))
                    .auth(new AuthScope(proxyHost, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME),
                            new UsernamePasswordCredentials(userID, password));
        }// ww w.  ja v a 2 s . c o  m
    }

    return executor;
}

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

/**
 * setup the given request object to go via proxy
 * /*from   w  ww .j a  va  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:de.elomagic.maven.http.HTTPMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    try {//from  w  ww .  j av  a  2 s .  co m
        Executor executor;

        if (httpsInsecure) {
            getLog().info("Accepting unsecure HTTPS connections.");
            try {
                SSLContextBuilder builder = new SSLContextBuilder();
                builder.loadTrustMaterial(null, new TrustAllStrategy());
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

                final Registry<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", sslsf).build();

                PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
                        sfr);
                connectionManager.setDefaultMaxPerRoute(100);
                connectionManager.setMaxTotal(200);
                connectionManager.setValidateAfterInactivity(1000);

                HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager)
                        .build();

                executor = Executor.newInstance(httpClient);
            } catch (Exception ex) {
                throw new Exception("Unable to setup HTTP client for unstrusted connections.", ex);
            }
        } else {
            executor = Executor.newInstance();
        }

        Settings settings = session.getSettings();
        if (StringUtils.isNotBlank(serverId)) {
            Server server = settings.getServer(serverId);
            if (server == null) {
                throw new Exception("Server ID \"" + serverId + "\" not found in your Maven settings.xml");
            }
            getLog().debug("ServerId: " + serverId);
            executor.auth(server.getUsername(), server.getPassword());
        }

        Request request = createRequestMethod();

        request.setHeader("Accept", accept);

        if (httpHeaders != null) {
            for (Entry<String, String> entry : httpHeaders.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }

        if (formParams != null) {
            Form form = Form.form();
            for (Entry<String, String> entry : formParams.entrySet()) {
                form.add(entry.getKey(), entry.getValue());
            }
        }

        if (fromFile != null) {
            if (!fromFile.exists()) {
                throw new MojoExecutionException("From file \"" + fromFile + "\" doesn't exist.");
            }

            if (StringUtils.isBlank(contentType)) {
                contentType = Files.probeContentType(fromFile.toPath());
            }

            getLog().debug("From file: " + fromFile);
            getLog().debug("Upload file size: "
                    + FileUtils.byteCountToDisplaySize(new Long(fromFile.length()).intValue()));
            getLog().debug("Content type: " + contentType);

            if (StringUtils.isBlank(contentType)) {
                request.body(new FileEntity(fromFile));
            } else {
                request.body(new FileEntity(fromFile, ContentType.create(contentType)));
            }
        }

        getLog().info(method + " " + url);

        Response response = executor.execute(request);
        handleResponse(response);
    } catch (Exception ex) {
        getLog().error(ex);
        if (failOnError) {
            throw new MojoExecutionException(ex.getMessage(), ex);
        } else {
            getLog().info("Fail on error is disabled. Continue execution.");
        }
    }

}

From source file:me.vertretungsplan.parser.LoginHandler.java

private String handleLogin(Executor executor, CookieStore cookieStore, boolean needsResponse)
        throws JSONException, IOException, CredentialInvalidException {
    if (auth == null)
        return null;
    if (!(auth instanceof UserPasswordCredential || auth instanceof PasswordCredential)) {
        throw new IllegalArgumentException("Wrong authentication type");
    }/*from   w ww  .  j ava  2  s . c  o  m*/

    String login;
    String password;
    if (auth instanceof UserPasswordCredential) {
        login = ((UserPasswordCredential) auth).getUsername();
        password = ((UserPasswordCredential) auth).getPassword();
    } else {
        login = null;
        password = ((PasswordCredential) auth).getPassword();
    }

    JSONObject data = scheduleData.getData();
    JSONObject loginConfig = data.getJSONObject(LOGIN_CONFIG);
    String type = loginConfig.optString(PARAM_TYPE, "post");
    switch (type) {
    case "post":
        List<Cookie> cookieList = cookieProvider != null ? cookieProvider.getCookies(auth) : null;
        if (cookieList != null && !needsResponse) {
            for (Cookie cookie : cookieList)
                cookieStore.addCookie(cookie);

            String checkUrl = loginConfig.optString(PARAM_CHECK_URL, null);
            String checkText = loginConfig.optString(PARAM_CHECK_TEXT, null);
            if (checkUrl != null && checkText != null) {
                String response = executor.execute(Request.Get(checkUrl)).returnContent().asString();
                if (!response.contains(checkText)) {
                    return null;
                }
            } else {
                return null;
            }
        }
        executor.clearCookies();
        Document preDoc = null;
        if (loginConfig.has(PARAM_PRE_URL)) {
            String preUrl = loginConfig.getString(PARAM_PRE_URL);
            String preHtml = executor.execute(Request.Get(preUrl)).returnContent().asString();
            preDoc = Jsoup.parse(preHtml);
        }

        String postUrl = loginConfig.getString(PARAM_URL);
        JSONObject loginData = loginConfig.getJSONObject(PARAM_DATA);
        List<NameValuePair> nvps = new ArrayList<>();

        String typo3Challenge = null;

        if (loginData.has("_hiddeninputs") && preDoc != null) {
            for (Element hidden : preDoc.select(loginData.getString("_hiddeninputs") + " input[type=hidden]")) {
                nvps.add(new BasicNameValuePair(hidden.attr("name"), hidden.attr("value")));
                if (hidden.attr("name").equals("challenge")) {
                    typo3Challenge = hidden.attr("value");
                }
            }
        }

        for (String name : JSONObject.getNames(loginData)) {
            String value = loginData.getString(name);

            if (name.equals("_hiddeninputs"))
                continue;

            switch (value) {
            case "_login":
                value = login;
                break;
            case "_password":
                value = password;
                break;
            case "_password_md5":
                value = DigestUtils.md5Hex(password);
                break;
            case "_password_md5_typo3":
                value = DigestUtils.md5Hex(login + ":" + DigestUtils.md5Hex(password) + ":" + typo3Challenge);
                break;
            }

            nvps.add(new BasicNameValuePair(name, value));
        }
        Request request = Request.Post(postUrl);
        if (loginConfig.optBoolean("form-data", false)) {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            for (NameValuePair nvp : nvps) {
                builder.addTextBody(nvp.getName(), nvp.getValue());
            }
            request.body(builder.build());
        } else {
            request.bodyForm(nvps, Charset.forName("UTF-8"));
        }
        String html = executor.execute(request).returnContent().asString();
        if (cookieProvider != null)
            cookieProvider.saveCookies(auth, cookieStore.getCookies());

        String checkUrl = loginConfig.optString(PARAM_CHECK_URL, null);
        String checkText = loginConfig.optString(PARAM_CHECK_TEXT, null);
        if (checkUrl != null && checkText != null) {
            String response = executor.execute(Request.Get(checkUrl)).returnContent().asString();
            if (response.contains(checkText))
                throw new CredentialInvalidException();
        } else if (checkText != null) {
            if (html.contains(checkText))
                throw new CredentialInvalidException();
        }
        return html;
    case "basic":
        if (login == null)
            throw new IOException("wrong auth type");
        executor.auth(login, password);
        if (loginConfig.has(PARAM_URL)) {
            String url = loginConfig.getString(PARAM_URL);
            if (executor.execute(Request.Get(url)).returnResponse().getStatusLine().getStatusCode() != 200) {
                throw new CredentialInvalidException();
            }
        }
        break;
    case "ntlm":
        if (login == null)
            throw new IOException("wrong auth type");
        executor.auth(login, password, null, null);
        if (loginConfig.has(PARAM_URL)) {
            String url = loginConfig.getString(PARAM_URL);
            if (executor.execute(Request.Get(url)).returnResponse().getStatusLine().getStatusCode() != 200) {
                throw new CredentialInvalidException();
            }
        }
        break;
    case "fixed":
        String loginFixed = loginConfig.optString(PARAM_LOGIN, null);
        String passwordFixed = loginConfig.getString(PARAM_PASSWORD);
        if (!Objects.equals(loginFixed, login) || !Objects.equals(passwordFixed, password)) {
            throw new CredentialInvalidException();
        }
        break;
    }
    return null;
}