Example usage for java.net Authenticator setDefault

List of usage examples for java.net Authenticator setDefault

Introduction

In this page you can find the example usage for java.net Authenticator setDefault.

Prototype

public static synchronized void setDefault(Authenticator a) 

Source Link

Document

Sets the authenticator that will be used by the networking code when a proxy or an HTTP server asks for authentication.

Usage

From source file:org.eclipse.mylyn.gerrit.tests.support.GerritProject.java

public String registerAuthenticator(PrivilegeLevel privilegeLevel) throws Exception {
    // register authenticator to avoid HTTP password prompt
    AuthenticationCredentials credentials = fixture.location(privilegeLevel)
            .getCredentials(AuthenticationType.REPOSITORY);
    final PasswordAuthentication authentication = new PasswordAuthentication(credentials.getUserName(),
            credentials.getPassword().toCharArray());
    Authenticator.setDefault(new Authenticator() {
        @Override//from  w  w w.j  a v a 2  s.  c o  m
        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    });
    return credentials.getUserName();
}

From source file:cc.arduino.net.CustomProxySelector.java

private void setAuthenticator(String username, String password) {
    if (username == null || username.isEmpty()) {
        return;// www.  j a v  a  2s .  c om
    }
    String actualPassword;
    if (password == null) {
        actualPassword = "";
    } else {
        actualPassword = password;
    }
    Authenticator.setDefault(new Authenticator() {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, actualPassword.toCharArray());
        }
    });
}

From source file:fr.cls.atoll.motu.library.cas.HttpClientCAS.java

/**
 * Sets the proxy user.//ww w. j  av  a2  s  . co  m
 */
public void setProxyUser() {
    if (LOG.isDebugEnabled()) {
        LOG.debug("setProxyUser() - start");
    }

    String proxyLogin = System.getProperty("proxyLogin");
    String proxyPassword = System.getProperty("proxyPassword");

    if ((!RestUtil.isNullOrEmpty(proxyLogin)) && (!RestUtil.isNullOrEmpty(proxyPassword))) {
        Authenticator.setDefault(new SimpleAuthenticator(proxyLogin, proxyPassword));

        if (LOG.isDebugEnabled()) {
            LOG.debug("setProxy() - proxy parameters are set: proxyLogin=" + proxyLogin + " - proxyPassword="
                    + proxyPassword);
            LOG.debug("setProxyUser() - end");
        }
        return;
    }

    proxyLogin = System.getProperty("http.proxyLogin");
    proxyPassword = System.getProperty("http.proxyPassword");

    if ((!RestUtil.isNullOrEmpty(proxyLogin)) && (!RestUtil.isNullOrEmpty(proxyPassword))) {
        Authenticator.setDefault(new SimpleAuthenticator(proxyLogin, proxyPassword));
        if (LOG.isDebugEnabled()) {
            LOG.debug("setProxy() - proxy parameters are set: proxyLogin=" + proxyLogin + " - proxyPassword="
                    + proxyPassword);
            LOG.debug("setProxyUser() - end");
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("setProxyUser() - end");
    }
}

From source file:sce.ElasticJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    try {//from  ww w .j a v  a2s. co m
        // build the list of queries
        ArrayList<String> queries = new ArrayList<>();

        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String url = jobDataMap.getString("#url");
        String elasticJob = jobDataMap.getString("#elasticJobConstraints");

        int counter = 0;
        String expression = "";
        String j_tmp = "";

        JSONParser parser = new JSONParser();
        JSONObject jsonobject = (JSONObject) parser.parse(elasticJob);
        Iterator<?> keys = jsonobject.keySet().iterator();
        while (keys.hasNext()) {
            String i = (String) keys.next();
            JSONObject jsonobject2 = (JSONObject) jsonobject.get(i);
            Iterator<?> keys2 = jsonobject2.keySet().iterator();
            while (keys2.hasNext()) {
                String j = (String) keys2.next();
                JSONObject jsonobject3 = (JSONObject) jsonobject2.get(j);
                String configuration = "";
                if (jsonobject3.get("slaconfiguration") != null) {
                    configuration = (String) jsonobject3.get("slaconfiguration");
                } else if (jsonobject3.get("bcconfiguration") != null) {
                    configuration = (String) jsonobject3.get("bcconfiguration");
                } else if (jsonobject3.get("vmconfiguration") != null) {
                    configuration = (String) jsonobject3.get("vmconfiguration");
                } else if (jsonobject3.get("anyconfiguration") != null) {
                    configuration = (String) jsonobject3.get("anyconfiguration");
                }
                // add the query to the queries list
                queries.add(getQuery((String) jsonobject3.get("metric"), (String) jsonobject3.get("cfg"),
                        configuration, (String) jsonobject3.get("relation"),
                        String.valueOf(jsonobject3.get("threshold")), String.valueOf(jsonobject3.get("time")),
                        (String) jsonobject3.get("timeselect")));
                String op = jsonobject3.get("match") != null ? (String) jsonobject3.get("match") : "";
                switch (op) {
                case "":
                    break;
                case "any":
                    op = "OR(";
                    break;
                case "all":
                    op = "AND(";
                    break;
                }
                String closed_parenthesis = " ";
                int num_closed_parenthesis = !j_tmp.equals("") ? Integer.parseInt(j_tmp) - Integer.parseInt(j)
                        : 0;
                for (int parenthesis = 0; parenthesis < num_closed_parenthesis; parenthesis++) {
                    closed_parenthesis += " )";
                }
                expression += op + " " + counter + closed_parenthesis;
                j_tmp = j;
                counter++;
            }
        }
        ExpressionTree calc = new ExpressionTree(new Scanner(expression), queries);
        if (calc.evaluate()) {
            URL u = new URL(url);
            //get user credentials from URL, if present
            final String usernamePassword = u.getUserInfo();
            //set the basic authentication credentials for the connection
            if (usernamePassword != null) {
                Authenticator.setDefault(new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(usernamePassword.split(":")[0],
                                usernamePassword.split(":")[1].toCharArray());
                    }
                });
            }
            //call the callUrl
            URLConnection connection = u.openConnection();
            getUrlContents(connection);
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new JobExecutionException(e);
    }
}

From source file:com.adaptris.core.http.client.net.StandardHttpProducer.java

public StandardHttpProducer() {
    super();/*from   ww w. j a va 2s .  c  o m*/
    setResponseHeaderHandler(new DiscardResponseHeaders());
    setRequestHeaderProvider(new NoRequestHeaders());
    Authenticator.setDefault(AdapterResourceAuthenticator.getInstance());
}

From source file:org.sonar.plugins.github.GitHubPluginConfiguration.java

public Proxy getHttpProxy() {
    try {/*from  ww  w. ja v  a  2  s.com*/
        if (system2.property(HTTP_PROXY_HOSTNAME) != null && system2.property(HTTPS_PROXY_HOSTNAME) == null) {
            System.setProperty(HTTPS_PROXY_HOSTNAME, system2.property(HTTP_PROXY_HOSTNAME));
            System.setProperty(HTTPS_PROXY_PORT, system2.property(HTTP_PROXY_PORT));
        }

        String proxyUser = system2.property(HTTP_PROXY_USER);
        String proxyPass = system2.property(HTTP_PROXY_PASS);

        if (proxyUser != null && proxyPass != null) {
            Authenticator.setDefault(new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(proxyUser, proxyPass.toCharArray());
                }
            });
        }

        Proxy selectedProxy = ProxySelector.getDefault().select(new URI(endpoint())).get(0);

        if (selectedProxy.type() == Proxy.Type.DIRECT) {
            LOG.debug("There was no suitable proxy found to connect to GitHub - direct connection is used ");
        }

        LOG.info("A proxy has been configured - {}", selectedProxy.toString());
        return selectedProxy;
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(
                "Unable to perform GitHub WS operation - endpoint in wrong format: " + endpoint(), e);
    }
}

From source file:com.epam.catgenome.manager.externaldb.HttpDataManager.java

private HttpURLConnection createConnection(final String location) throws IOException {

    URL url = new URL(location);
    HttpURLConnection conn;//  w w w  .  j a v  a 2  s  . c  o  m

    if (proxyHost != null && proxyPort != null) {
        if (proxyUser != null && proxyPassword != null) {
            Authenticator authenticator = new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
                }
            };
            Authenticator.setDefault(authenticator);
        }
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        conn = (HttpURLConnection) url.openConnection(proxy);
    } else {
        conn = (HttpURLConnection) url.openConnection();
    }
    return conn;
}

From source file:com.redhat.rcm.version.config.DefaultSessionConfigurator.java

private void loadSettings(final VersionManagerSession session) {
    MavenExecutionRequest executionRequest = session.getExecutionRequest();
    if (executionRequest == null) {
        executionRequest = new DefaultMavenExecutionRequest();
    }/*  ww w.  ja va 2 s  . co m*/

    File settingsXml;
    try {
        settingsXml = getFile(session.getSettingsXml(), session.getDownloads());
    } catch (final VManException e) {
        session.addError(e);
        return;
    }

    final DefaultSettingsBuildingRequest req = new DefaultSettingsBuildingRequest();
    req.setUserSettingsFile(settingsXml);
    req.setSystemProperties(System.getProperties());

    try {
        final SettingsBuildingResult result = settingsBuilder.build(req);
        final Settings settings = result.getEffectiveSettings();

        final String proxyHost = System.getProperty("http.proxyHost");
        final String proxyPort = System.getProperty("http.proxyPort", "8080");
        final String nonProxyHosts = System.getProperty("http.nonProxyHosts", "localhost");

        final String proxyUser = System.getProperty("http.proxyUser");
        final String proxyPassword = System.getProperty("http.proxyPassword");
        if (proxyHost != null) {
            final Proxy proxy = new Proxy();
            proxy.setActive(true);
            proxy.setHost(proxyHost);
            proxy.setId("cli");
            proxy.setNonProxyHosts(nonProxyHosts);
            proxy.setPort(Integer.parseInt(proxyPort));

            if (proxyUser != null && proxyPassword != null) {
                proxy.setUsername(proxyUser);
                proxy.setPassword(proxyPassword);

                Authenticator.setDefault(new Authenticator() {
                    @Override
                    public PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
                    }
                });
            }

            settings.setProxies(Collections.singletonList(proxy));
        }

        executionRequest = requestPopulator.populateFromSettings(executionRequest, settings);
        session.setExecutionRequest(executionRequest);
    } catch (final SettingsBuildingException e) {
        session.addError(new VManException("Failed to build settings from: %s. Reason: %s", e, settingsXml,
                e.getMessage()));
    } catch (final MavenExecutionRequestPopulationException e) {
        session.addError(new VManException("Failed to initialize system using settings from: %s. Reason: %s", e,
                settingsXml, e.getMessage()));
    }
}

From source file:hudson.ProxyConfiguration.java

/**
 * This method should be used wherever {@link URL#openConnection()} to internet URLs is invoked directly.
 *///from ww w.  j av  a2 s  .  c o  m
public static URLConnection open(URL url) throws IOException {
    Jenkins h = Jenkins.getInstance(); // this code might run on slaves
    ProxyConfiguration p = h != null ? h.proxy : null;
    if (p == null)
        return url.openConnection();

    URLConnection con = url.openConnection(p.createProxy(url.getHost()));
    if (p.getUserName() != null) {
        // Add an authenticator which provides the credentials for proxy authentication
        Authenticator.setDefault(new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                if (getRequestorType() != RequestorType.PROXY)
                    return null;
                ProxyConfiguration p = Jenkins.getInstance().proxy;
                return new PasswordAuthentication(p.getUserName(), p.getPassword().toCharArray());
            }
        });
    }

    for (URLConnectionDecorator d : URLConnectionDecorator.all())
        d.decorate(con);

    return con;
}

From source file:net.myrrix.client.ClientRecommender.java

/**
 * Instantiates a new recommender client with the given configuration
 *
 * @param config configuration to use with this client
 * @throws IOException if the HTTP client encounters an error during configuration
 *///from   ww  w.j  a v a 2 s . c  om
public ClientRecommender(MyrrixClientConfiguration config) throws IOException {
    Preconditions.checkNotNull(config);
    this.config = config;

    final String userName = config.getUserName();
    final String password = config.getPassword();
    needAuthentication = userName != null && password != null;
    if (needAuthentication) {
        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password.toCharArray());
            }
        });
    }

    if (config.getKeystoreFile() != null) {
        log.warn("A keystore file has been specified. "
                + "This should only be done to accept self-signed certificates in development.");
        HttpsURLConnection.setDefaultSSLSocketFactory(buildSSLSocketFactory());
    }

    closeConnection = Boolean.valueOf(System.getProperty(CONNECTION_CLOSE_KEY));
    ignoreHTTPSHost = Boolean.valueOf(System.getProperty(IGNORE_HOSTNAME_KEY));

    partitions = config.getPartitions();
}