Example usage for java.net Authenticator Authenticator

List of usage examples for java.net Authenticator Authenticator

Introduction

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

Prototype

Authenticator

Source Link

Usage

From source file:org.talend.components.salesforce.runtime.SalesforceSourceOrSink.java

private void setProxy(ConnectorConfig config) {
    final ProxyPropertiesRuntimeHelper proxyHelper = new ProxyPropertiesRuntimeHelper(
            properties.getConnectionProperties().proxy);

    if (proxyHelper.getProxyHost() != null) {
        if (proxyHelper.getSocketProxy() != null) {
            config.setProxy(proxyHelper.getSocketProxy());
        } else {/*  w  w w.j  a va 2 s . c  om*/
            config.setProxy(proxyHelper.getProxyHost(), Integer.parseInt(proxyHelper.getProxyPort()));
        }

        if (proxyHelper.getProxyUser() != null && proxyHelper.getProxyUser().length() > 0) {
            config.setProxyUsername(proxyHelper.getProxyUser());

            if (proxyHelper.getProxyPwd() != null && proxyHelper.getProxyPwd().length() > 0) {
                config.setProxyPassword(proxyHelper.getProxyPwd());

                Authenticator.setDefault(new Authenticator() {

                    @Override
                    public PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(proxyHelper.getProxyUser(),
                                proxyHelper.getProxyPwd().toCharArray());
                    }

                });
            }
        }
    }
}

From source file:com.minoritycode.Application.java

private static boolean setProxy() {

    System.out.println("Setting proxy...");

    String host = null;/*from w  w  w  . j  a va  2s.c  om*/

    host = config.getProperty("proxyHost").trim();

    if (host == null || host.isEmpty() || host.equals("")) {
        logger.logLine("error proxy host not set in config file");
        if (manualOperation) {
            String message = "Please enter your proxy Host address";
            host = Credentials.getInput(message).trim();
            Credentials.saveProperty("proxyHost", host);

            if (host.equals(null)) {
                System.exit(0);
            }
        } else {
            return false;
        }
    }

    String port = config.getProperty("proxyPort").trim();

    if (port == null || port.isEmpty()) {
        logger.logLine("error proxy port not set in config file");
        if (manualOperation) {
            String message = "Please enter your proxy port";
            port = Credentials.getInput(message).trim();
            Credentials.saveProperty("proxyPort", port);

            if (port.equals(null)) {
                System.exit(0);
            }
        } else {
            return false;
        }
    }

    String user = config.getProperty("proxyUser").trim();

    if (user == null || user.isEmpty()) {
        logger.logLine("error proxy username not set in config file");
        if (manualOperation) {
            String message = "Please enter your proxy username";
            user = Credentials.getInput(message).trim();

            if (user.equals(null)) {
                System.exit(0);
            }

            Credentials.saveProperty("proxyUser", user);
        } else {
            return false;
        }
    }

    String password = config.getProperty("proxyPassword").trim();

    if (password == null || password.isEmpty()) {
        logger.logLine("error proxy password not set in config file");
        if (manualOperation) {
            String message = "Please enter your proxy password";
            password = Credentials.getInput(message).trim();
            Credentials.saveProperty("proxyPassword", password);
            if (password.equals(null)) {
                System.exit(0);
            }
        } else {
            return false;
        }
    }

    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {

            if (getRequestorType() == RequestorType.PROXY) {
                String prot = getRequestingProtocol().toLowerCase();
                String host = System.getProperty(prot + ".proxyHost", config.getProperty("proxyHost"));
                String port = System.getProperty(prot + ".proxyPort", config.getProperty("proxyPort"));
                String user = System.getProperty(prot + ".proxyUser", config.getProperty("proxyUser"));
                String password = System.getProperty(prot + ".proxyPassword",
                        config.getProperty("proxyPassword"));

                if (getRequestingHost().equalsIgnoreCase(host)) {
                    if (Integer.parseInt(port) == getRequestingPort()) {
                        // Seems to be OK.
                        return new PasswordAuthentication(user, password.toCharArray());
                    }
                }
            }
            return null;
        }
    });

    System.setProperty("http.proxyPort", port);
    System.setProperty("http.proxyHost", host);
    System.setProperty("http.proxyUser", user);
    System.setProperty("http.proxyPassword", password);

    proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, Integer.parseInt(port)));

    //        System.out.println(host+":"+port +" "+ user+":"+password);
    System.out.println("Proxy set");
    return true;
}

From source file:org.apache.cxf.maven_plugin.AbstractCodegenMoho.java

protected void configureProxyServerSettings() throws MojoExecutionException {

    Proxy proxy = mavenSession.getSettings().getActiveProxy();

    if (proxy != null) {

        getLog().info("Using proxy server configured in maven.");

        if (proxy.getHost() == null) {
            throw new MojoExecutionException("Proxy in settings.xml has no host");
        } else {/*from  w  w w .j  av a 2 s  . c  o  m*/
            if (proxy.getHost() != null) {
                System.setProperty(HTTP_PROXY_HOST, proxy.getHost());
            }
            if (String.valueOf(proxy.getPort()) != null) {
                System.setProperty(HTTP_PROXY_PORT, String.valueOf(proxy.getPort()));
            }
            if (proxy.getNonProxyHosts() != null) {
                System.setProperty(HTTP_NON_PROXY_HOSTS, proxy.getNonProxyHosts());
            }
            if (!StringUtils.isEmpty(proxy.getUsername()) && !StringUtils.isEmpty(proxy.getPassword())) {
                final String authUser = proxy.getUsername();
                final String authPassword = proxy.getPassword();
                Authenticator.setDefault(new Authenticator() {
                    public PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(authUser, authPassword.toCharArray());
                    }
                });

                System.setProperty(HTTP_PROXY_USER, authUser);
                System.setProperty(HTTP_PROXY_PORT, authPassword);
            }
        }

    }
}

From source file:com.syncleus.maven.plugins.mongodb.StartMongoMojo.java

private void addProxySelector() {

    // Add authenticator with proxyUser and proxyPassword
    if (proxyUser != null && proxyPassword != null) {
        Authenticator.setDefault(new Authenticator() {
            @Override//  w ww .  j av  a 2 s. c  om
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
            }
        });
    }

    final ProxySelector defaultProxySelector = ProxySelector.getDefault();
    ProxySelector.setDefault(new ProxySelector() {
        @Override
        public List<Proxy> select(final URI uri) {
            if (uri.getHost().equals("fastdl.mongodb.org")) {
                return singletonList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)));
            } else {
                return defaultProxySelector.select(uri);
            }
        }

        @Override
        public void connectFailed(final URI uri, final SocketAddress sa, final IOException ioe) {
        }
    });
}

From source file:com.blackducksoftware.integration.hub.jenkins.PostBuildScanDescriptor.java

/**
 * Performs on-the-fly validation of the form field 'serverUrl'.
 *
 *//*from w  ww  .j  a  va2  s .  c  o  m*/
public FormValidation doCheckServerUrl(@QueryParameter("serverUrl") final String serverUrl)
        throws IOException, ServletException {
    if (StringUtils.isBlank(serverUrl)) {
        return FormValidation.error(Messages.HubBuildScan_getPleaseSetServerUrl());
    }
    URL url;
    try {
        url = new URL(serverUrl);
        try {
            url.toURI();
        } catch (final URISyntaxException e) {
            return FormValidation.error(e, Messages.HubBuildScan_getNotAValidUrl());
        }
    } catch (final MalformedURLException e) {
        return FormValidation.error(e, Messages.HubBuildScan_getNotAValidUrl());
    }
    try {
        Proxy proxy = null;

        final Jenkins jenkins = Jenkins.getInstance();
        if (jenkins != null) {
            final ProxyConfiguration proxyConfig = jenkins.proxy;
            if (proxyConfig != null) {
                proxy = ProxyConfiguration.createProxy(url.getHost(), proxyConfig.name, proxyConfig.port,
                        proxyConfig.noProxyHost);

                if (proxy != null && proxy != Proxy.NO_PROXY) {

                    if (StringUtils.isNotBlank(proxyConfig.getUserName())
                            && StringUtils.isNotBlank(proxyConfig.getPassword())) {
                        Authenticator.setDefault(new Authenticator() {
                            @Override
                            public PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(proxyConfig.getUserName(),
                                        proxyConfig.getPassword().toCharArray());
                            }
                        });
                    } else {
                        Authenticator.setDefault(null);
                    }
                }
            }
        }

        URLConnection connection = null;
        if (proxy != null) {
            connection = url.openConnection(proxy);
        } else {
            connection = url.openConnection();
        }

        connection.getContent();
    } catch (final IOException ioe) {
        return FormValidation.error(ioe, Messages.HubBuildScan_getCanNotReachThisServer_0_(serverUrl));
    } catch (final RuntimeException e) {
        return FormValidation.error(e, Messages.HubBuildScan_getNotAValidUrl());
    }
    return FormValidation.ok();
}

From source file:com.panet.imeta.cluster.SlaveServer.java

/**
 * Contact the server and get back the reply as a string
 * @return the requested information//from   w  w w.  j av  a2  s . c o  m
 * @throws Exception in case something goes awry 
 */
public String getContentFromServer(String service) throws Exception {
    // Following variable hides class variable. MB 7/10/07
    // LogWriter log = LogWriter.getInstance();

    String urlToUse = constructUrl(service);
    URL server;
    StringBuffer result = new StringBuffer();

    try {
        String beforeProxyHost = System.getProperty("http.proxyHost"); //$NON-NLS-1$
        String beforeProxyPort = System.getProperty("http.proxyPort"); //$NON-NLS-1$
        String beforeNonProxyHosts = System.getProperty("http.nonProxyHosts"); //$NON-NLS-1$

        BufferedReader input = null;

        try {
            if (log.isBasic())
                log.logBasic(toString(), Messages.getString("SlaveServer.DEBUG_ConnectingTo", urlToUse)); //$NON-NLS-1$

            if (proxyHostname != null) {
                System.setProperty("http.proxyHost", environmentSubstitute(proxyHostname)); //$NON-NLS-1$
                System.setProperty("http.proxyPort", environmentSubstitute(proxyPort)); //$NON-NLS-1$
                if (nonProxyHosts != null)
                    System.setProperty("http.nonProxyHosts", environmentSubstitute(nonProxyHosts)); //$NON-NLS-1$
            }

            if (username != null && username.length() > 0) {
                Authenticator.setDefault(new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(environmentSubstitute(username),
                                password != null ? environmentSubstitute(password).toCharArray()
                                        : new char[] {});
                    }
                });
            }

            // Get a stream for the specified URL
            server = new URL(urlToUse);
            URLConnection connection = server.openConnection();

            log.logDetailed(toString(), Messages.getString("SlaveServer.StartReadingReply")); //$NON-NLS-1$

            // Read the result from the server...
            InputStream inputStream = new BufferedInputStream(connection.getInputStream(), 1000);

            input = new BufferedReader(new InputStreamReader(inputStream));

            long bytesRead = 0L;
            String line;
            while ((line = input.readLine()) != null) {
                result.append(line).append(Const.CR);
                bytesRead += line.length();
            }
            if (log.isBasic())
                log.logBasic(toString(), Messages.getString("SlaveServer.FinishedReadingResponse"), bytesRead); //$NON-NLS-1$
            if (log.isDebug())
                log.logDebug(toString(), "response from the webserver: {0}", result);
        } catch (MalformedURLException e) {
            log.logError(toString(), Messages.getString("SlaveServer.UrlIsInvalid", urlToUse, e.getMessage())); //$NON-NLS-1$
            log.logError(toString(), Const.getStackTracker(e));
        } catch (IOException e) {
            log.logError(toString(), Messages.getString("SlaveServer.CannotSaveDueToIOError", e.getMessage())); //$NON-NLS-1$
            log.logError(toString(), Const.getStackTracker(e));
        } catch (Exception e) {
            log.logError(toString(), Messages.getString("SlaveServer.ErrorReceivingFile", e.getMessage())); //$NON-NLS-1$
            log.logError(toString(), Const.getStackTracker(e));
        } finally {
            // Close it all
            try {
                if (input != null)
                    input.close();
            } catch (Exception e) {
                log.logError(toString(), Messages.getString("SlaveServer.CannotCloseStream", e.getMessage())); //$NON-NLS-1$
                log.logError(toString(), Const.getStackTracker(e));
            }

        }

        // Set the proxy settings back as they were on the system!
        System.setProperty("http.proxyHost", Const.NVL(beforeProxyHost, "")); //$NON-NLS-1$  //$NON-NLS-2$
        System.setProperty("http.proxyPort", Const.NVL(beforeProxyPort, "")); //$NON-NLS-1$  //$NON-NLS-2$
        System.setProperty("http.nonProxyHosts", Const.NVL(beforeNonProxyHosts, "")); //$NON-NLS-1$  //$NON-NLS-2$

        // Get the result back...
        return result.toString();
    } catch (Exception e) {
        throw new Exception(Messages.getString("SlaveServer.CannotContactURLForSecurityInformation", urlToUse), //$NON-NLS-1$
                e);
    }
}

From source file:org.owasp.proxy.Main.java

private static HttpRequestHandler configureAuthentication(HttpRequestHandler rh, final Configuration config) {
    if (config.authUser != null) {
        if (config.authPassword == null) {
            System.err.println("authPassword must be provided!");
            System.exit(1);//  w w  w. j  a  va  2  s .  c  o m
        }
        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.authUser, config.authPassword.toCharArray());
            }
        });
        return new AuthenticatingHttpRequestHandler(rh);
    } else {
        return rh;
    }
}

From source file:org.apache.cxf.cwiki.SiteExporter.java

public static void main(String[] args) throws Exception {
    Authenticator.setDefault(new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password.toCharArray());
        }/*from ww  w .  j  a  v  a2s  .c  o  m*/
    });
    ListIterator<String> it = Arrays.asList(args).listIterator();
    List<String> files = new ArrayList<String>();
    boolean forceAll = false;
    int maxThreads = -1;
    while (it.hasNext()) {
        String s = it.next();
        if ("-debug".equals(s)) {
            debug = true;
        } else if ("-user".equals(s)) {
            userName = it.next();
        } else if ("-password".equals(s)) {
            password = it.next();
        } else if ("-d".equals(s)) {
            rootOutputDir = new File(it.next());
        } else if ("-force".equals(s)) {
            forceAll = true;
        } else if ("-svn".equals(s)) {
            svn = true;
        } else if ("-commit".equals(s)) {
            commit = true;
        } else if ("-maxThreads".equals(s)) {
            maxThreads = Integer.parseInt(it.next());
        } else if (s != null && s.length() > 0) {
            files.add(s);
        }
    }

    List<SiteExporter> exporters = new ArrayList<SiteExporter>();
    for (String file : files) {
        exporters.add(new SiteExporter(file, forceAll));
    }
    List<SiteExporter> modified = new ArrayList<SiteExporter>();
    for (SiteExporter exporter : exporters) {
        if (exporter.initialize()) {
            modified.add(exporter);
        }
    }

    // render stuff only if needed
    if (!modified.isEmpty()) {
        setSiteExporters(exporters);

        if (maxThreads <= 0) {
            maxThreads = modified.size();
        }

        ExecutorService executor = Executors.newFixedThreadPool(maxThreads, new ThreadFactory() {
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setDaemon(true);
                return t;
            }
        });
        List<Future<?>> futures = new ArrayList<Future<?>>(modified.size());
        for (SiteExporter exporter : modified) {
            futures.add(executor.submit(exporter));
        }
        for (Future<?> t : futures) {
            t.get();
        }
    }

    if (commit) {
        File file = FileUtils.createTempFile("svncommit", "txt");
        FileWriter writer = new FileWriter(file);
        writer.write(svnCommitMessage.toString());
        writer.close();
        callSvn(rootOutputDir, "commit", "-F", file.getAbsolutePath(), rootOutputDir.getAbsolutePath());
        svnCommitMessage.setLength(0);
    }
}

From source file:org.tupelo_schneck.electric.Options.java

private void readAndProcessPassword() throws IOException {
    System.err.print("Please enter password for username '" + username + "': ");
    password = Options.reader.readLine();
    Authenticator.setDefault(new Authenticator() {
        @Override/*from   w w w  .j  a v a 2  s  . c om*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password.toCharArray());
        }
    });
}

From source file:org.ramadda.repository.Repository.java

/**
 * _more_/*  ww w  .j av a  2  s  .c  o m*/
 */
private void initProxy() {
    //First try the local ramadda properties
    //The default value is the system property 
    String proxyHost = getProperty(PROP_PROXY_HOST, getProperty("http.proxyHost", (String) null));
    String proxyPort = getProperty(PROP_PROXY_PORT, getProperty("http.proxyPort", "8080"));
    final String proxyUser = getProperty(PROP_PROXY_USER, (String) null);
    final String proxyPass = getProperty(PROP_PROXY_PASSWORD, (String) null);
    httpClient = new HttpClient();
    if (proxyHost != null) {
        getLogManager().logInfoAndPrint("Setting proxy server to:" + proxyHost + ":" + proxyPort);
        System.setProperty("http.proxyHost", proxyHost);
        System.setProperty("http.proxyPort", proxyPort);
        System.setProperty("ftp.proxyHost", proxyHost);
        System.setProperty("ftp.proxyPort", proxyPort);
        httpClient.getHostConfiguration().setProxy(proxyHost, Integer.parseInt(proxyPort));
        // Just if proxy has authentication credentials
        if (proxyUser != null) {
            getLogManager().logInfoAndPrint("Setting proxy user to:" + proxyUser);
            httpClient.getParams().setAuthenticationPreemptive(true);
            Credentials defaultcreds = new UsernamePasswordCredentials(proxyUser, proxyPass);
            httpClient.getState().setProxyCredentials(
                    new AuthScope(proxyHost, Integer.parseInt(proxyPort), AuthScope.ANY_REALM), defaultcreds);
            Authenticator.setDefault(new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(proxyUser, proxyPass.toCharArray());
                }
            });
        }
    }

}