Example usage for java.net PasswordAuthentication PasswordAuthentication

List of usage examples for java.net PasswordAuthentication PasswordAuthentication

Introduction

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

Prototype

public PasswordAuthentication(String userName, char[] password) 

Source Link

Document

Creates a new PasswordAuthentication object from the given user name and password.

Usage

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

public Proxy getHttpProxy() {
    try {/*  ww  w  . ja  v a2s .  c om*/
        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.intellij.util.net.HttpConfigurable.java

public PasswordAuthentication getGenericPassword(final String host, final int port) {
    final ProxyInfo proxyInfo;
    synchronized (myLock) {
        proxyInfo = myGenericPasswords.get(new CommonProxy.HostInfo("", host, port));
    }//w w  w  .  j a v  a2 s  . c  om
    if (proxyInfo == null)
        return null;
    return new PasswordAuthentication(proxyInfo.getUsername(),
            decode(String.valueOf(proxyInfo.getPasswordCrypt())).toCharArray());
}

From source file:JAXRPublishConcept.java

/**
     * Creates a concept and saves it to the registry.
     */*from   ww w.  ja  v  a 2 s . c  o m*/
     * @param username  the username for the registry
     * @param password  the password for the registry
     */
    public void executePublish(String username, String password) {
        RegistryService rs = null;
        BusinessLifeCycleManager blcm = null;
        BusinessQueryManager bqm = null;
        ResourceBundle bundle = ResourceBundle.getBundle("JAXRExamples");

        try {
            rs = connection.getRegistryService();
            blcm = rs.getBusinessLifeCycleManager();
            bqm = rs.getBusinessQueryManager();
            System.out.println("Got registry service, query " + "manager, and life cycle manager");

            // Get authorization from the registry
            PasswordAuthentication passwdAuth = new PasswordAuthentication(username, password.toCharArray());

            HashSet<PasswordAuthentication> creds = new HashSet<PasswordAuthentication>();
            creds.add(passwdAuth);
            connection.setCredentials(creds);
            System.out.println("Established security credentials");

            InternationalString s = blcm.createInternationalString(bundle.getString("concept.name"));
            Concept specConcept = blcm.createConcept(null, s, "");
            s = blcm.createInternationalString(bundle.getString("concept.description"));
            specConcept.setDescription(s);

            s = blcm.createInternationalString(bundle.getString("link.description"));

            ExternalLink wsdlLink = blcm.createExternalLink(bundle.getString("link.uri"), s);
            specConcept.addExternalLink(wsdlLink);

            /*
             * Find the uddi-org:types classification scheme defined
             * by the UDDI specification, using well-known key id.
             */
            String uuid_types = "uuid:C1ACF26D-9672-4404-9D70-39B756E62AB4";
            ClassificationScheme uddiOrgTypes = (ClassificationScheme) bqm.getRegistryObject(uuid_types,
                    LifeCycleManager.CLASSIFICATION_SCHEME);

            /*
             * Create a classification, specifying the scheme
             *  and the taxonomy name and value defined for WSDL
             *  documents by the UDDI specification. Add to
             *  concept.
             */
            Classification wsdlSpecClassification = blcm.createClassification(uddiOrgTypes,
                    blcm.createInternationalString("wsdlSpec"), "wsdlSpec");
            specConcept.addClassification(wsdlSpecClassification);

            // Save the concept and retrieve the key.
            Collection<Concept> concepts = new ArrayList<Concept>();
            concepts.add(specConcept);

            BulkResponse response = blcm.saveConcepts(concepts);
            Collection exceptions = response.getExceptions();

            if (exceptions == null) {
                System.out.println("WSDL Specification Concept saved");

                Collection keys = response.getCollection();

                for (Object k : keys) {
                    Key concKey = (Key) k;

                    String id = concKey.getId();
                    System.out.println("Concept key is " + id);
                    System.out.println("Use this key as the argument " + "to JAXRPublishHelloOrg");
                }
            } else {
                for (Object e : exceptions) {
                    Exception exception = (Exception) e;
                    System.err.println("Exception on save: " + exception.toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // At end, close connection to registry
            if (connection != null) {
                try {
                    connection.close();
                } catch (JAXRException je) {
                }
            }
        }
    }

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();
    }/*from  w ww .  j a  va  2s. c  om*/

    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: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
 */// w w w . j av  a  2  s.co  m
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();
}

From source file:JAXRSaveClassificationScheme.java

/**
     * Creates a classification scheme and saves it to the
     * registry./* www .ja va  2  s.  c  o m*/
     *
     * @param username  the username for the registry
     * @param password  the password for the registry
     */
    public void executePublish(String username, String password) {
        RegistryService rs = null;
        BusinessLifeCycleManager blcm = null;
        BusinessQueryManager bqm = null;

        try {
            rs = connection.getRegistryService();
            blcm = rs.getBusinessLifeCycleManager();
            bqm = rs.getBusinessQueryManager();
            System.out.println("Got registry service, query " + "manager, and life cycle manager");

            // Get authorization from the registry
            PasswordAuthentication passwdAuth = new PasswordAuthentication(username, password.toCharArray());

            HashSet<PasswordAuthentication> creds = new HashSet<PasswordAuthentication>();
            creds.add(passwdAuth);
            connection.setCredentials(creds);
            System.out.println("Established security credentials");

            ResourceBundle bundle = ResourceBundle.getBundle("JAXRExamples");

            // Create classification scheme
            InternationalString sn = blcm.createInternationalString(bundle.getString("postal.scheme.name"));
            InternationalString sd = blcm.createInternationalString(bundle.getString("postal.scheme.description"));
            ClassificationScheme postalScheme = blcm.createClassificationScheme(sn, sd);

            /*
             * Find the uddi-org:types classification scheme defined
             * by the UDDI specification, using well-known key id.
             */
            String uuid_types = "uuid:C1ACF26D-9672-4404-9D70-39B756E62AB4";
            ClassificationScheme uddiOrgTypes = (ClassificationScheme) bqm.getRegistryObject(uuid_types,
                    LifeCycleManager.CLASSIFICATION_SCHEME);

            if (uddiOrgTypes != null) {
                InternationalString cn = blcm
                        .createInternationalString(bundle.getString("postal.classification.name"));
                Classification classification = blcm.createClassification(uddiOrgTypes, cn,
                        bundle.getString("postal.classification.value"));

                postalScheme.addClassification(classification);

                /*
                 * Set link to location of postal scheme (fictitious)
                 * so others can look it up. If the URI were valid, we
                 * could use the createExternalLink method.
                 */
                ExternalLink externalLink = (ExternalLink) blcm.createObject(LifeCycleManager.EXTERNAL_LINK);
                externalLink.setValidateURI(false);
                externalLink.setExternalURI(bundle.getString("postal.scheme.link"));

                InternationalString is = blcm.createInternationalString(bundle.getString("postal.scheme.linkdesc"));
                externalLink.setDescription(is);
                postalScheme.addExternalLink(externalLink);

                // Add scheme and save it to registry
                // Retrieve key if successful
                Collection<ClassificationScheme> schemes = new ArrayList<ClassificationScheme>();
                schemes.add(postalScheme);

                BulkResponse br = blcm.saveClassificationSchemes(schemes);

                if (br.getStatus() == JAXRResponse.STATUS_SUCCESS) {
                    System.out.println("Saved PostalAddress " + "ClassificationScheme");

                    Collection schemeKeys = br.getCollection();

                    for (Object k : schemeKeys) {
                        Key key = (Key) k;
                        System.out.println("The postalScheme key is " + key.getId());
                        System.out.println(
                                "Use this key as the scheme uuid " + "in the postalconcepts.xml file\n  and as the "
                                        + "argument to JAXRPublishPostal and " + "JAXRQueryPostal");
                    }
                } else {
                    Collection exceptions = br.getExceptions();

                    for (Object e : exceptions) {
                        Exception exception = (Exception) e;
                        System.err.println("Exception on save: " + exception.toString());
                    }
                }
            } else {
                System.out.println("uddi-org:types not found. Unable to " + "save PostalAddress scheme.");
            }
        } catch (JAXRException jaxe) {
            jaxe.printStackTrace();
        } finally {
            // At end, close connection to registry
            if (connection != null) {
                try {
                    connection.close();
                } catch (JAXRException je) {
                }
            }
        }
    }

From source file:com.intellij.util.net.HttpConfigurable.java

public void putGenericPassword(final String host, final int port, final PasswordAuthentication authentication,
        final boolean remember) {
    final PasswordAuthentication coded = new PasswordAuthentication(authentication.getUserName(),
            encode(String.valueOf(authentication.getPassword())).toCharArray());
    synchronized (myLock) {
        myGenericPasswords.put(new CommonProxy.HostInfo("", host, port),
                new ProxyInfo(remember, coded.getUserName(), String.valueOf(coded.getPassword())));
    }/*from www . ja va  2  s.  c o  m*/
}

From source file:hudson.ProxyConfiguration.java

/**
 * This method should be used wherever {@link URL#openConnection()} to internet URLs is invoked directly.
 *//*from  w  w w. j  a v  a 2  s .  co 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:JAXRPublish.java

/**
     * Creates an organization, its classification, and its
     * services, and saves it to the registry.
     */*www  .  j  ava 2  s.  c o  m*/
     * @param username  the username for the registry
     * @param password  the password for the registry
     */
    public void executePublish(String username, String password) {
        RegistryService rs = null;
        BusinessLifeCycleManager blcm = null;
        BusinessQueryManager bqm = null;

        try {
            rs = connection.getRegistryService();
            blcm = rs.getBusinessLifeCycleManager();
            bqm = rs.getBusinessQueryManager();
            System.out.println("Got registry service, query " + "manager, and life cycle manager");

            // Get authorization from the registry
            PasswordAuthentication passwdAuth = new PasswordAuthentication(username, password.toCharArray());

            HashSet<PasswordAuthentication> creds = new HashSet<PasswordAuthentication>();
            creds.add(passwdAuth);
            connection.setCredentials(creds);
            System.out.println("Established security credentials");

            ResourceBundle bundle = ResourceBundle.getBundle("JAXRExamples");

            // Create organization name and description
            InternationalString s = blcm.createInternationalString(bundle.getString("org.name"));
            Organization org = blcm.createOrganization(s);
            s = blcm.createInternationalString(bundle.getString("org.description"));
            org.setDescription(s);

            // Create primary contact, set name
            User primaryContact = blcm.createUser();
            PersonName pName = blcm.createPersonName(bundle.getString("person.name"));
            primaryContact.setPersonName(pName);

            // Set primary contact phone number
            TelephoneNumber tNum = blcm.createTelephoneNumber();
            tNum.setNumber(bundle.getString("phone.number"));

            Collection<TelephoneNumber> phoneNums = new ArrayList<TelephoneNumber>();
            phoneNums.add(tNum);
            primaryContact.setTelephoneNumbers(phoneNums);

            // Set primary contact email address
            EmailAddress emailAddress = blcm.createEmailAddress(bundle.getString("email.address"));
            Collection<EmailAddress> emailAddresses = new ArrayList<EmailAddress>();
            emailAddresses.add(emailAddress);
            primaryContact.setEmailAddresses(emailAddresses);

            // Set primary contact for organization
            org.setPrimaryContact(primaryContact);

            // Set classification scheme to NAICS, using
            // well-known UUID of ntis-gov:naics:1997
            String uuid_naics = "uuid:C0B9FE13-179F-413D-8A5B-5004DB8E5BB2";
            ClassificationScheme cScheme = (ClassificationScheme) bqm.getRegistryObject(uuid_naics,
                    LifeCycleManager.CLASSIFICATION_SCHEME);

            if (cScheme != null) {
                // Create and add classification
                InternationalString sn = blcm.createInternationalString(bundle.getString("classification.name"));
                Classification classification = blcm.createClassification(cScheme, sn,
                        bundle.getString("classification.value"));
                Collection<Classification> classifications = new ArrayList<Classification>();
                classifications.add(classification);
                org.addClassifications(classifications);
            } else {
                System.out.println("Classification scheme not found, " + "not classifying organization");
            }

            // Create services and service
            Collection<Service> services = new ArrayList<Service>();
            s = blcm.createInternationalString(bundle.getString("service.name"));

            Service service = blcm.createService(s);
            s = blcm.createInternationalString(bundle.getString("service.description"));
            service.setDescription(s);

            // Create service bindings
            Collection<ServiceBinding> serviceBindings = new ArrayList<ServiceBinding>();
            ServiceBinding binding = blcm.createServiceBinding();
            s = blcm.createInternationalString(bundle.getString("svcbinding.description"));
            binding.setDescription(s);

            // Allow us to publish a fictitious URI without an error
            binding.setValidateURI(false);
            binding.setAccessURI(bundle.getString("svcbinding.accessURI"));
            serviceBindings.add(binding);

            // Add service bindings to service
            service.addServiceBindings(serviceBindings);

            // Add service to services, then add services to organization
            services.add(service);
            org.addServices(services);

            // Add organization and submit to registry
            // Retrieve key if successful
            Collection<Organization> orgs = new ArrayList<Organization>();
            orgs.add(org);

            BulkResponse response = blcm.saveOrganizations(orgs);
            Collection exceptions = response.getExceptions();

            if (exceptions == null) {
                System.out.println("Organization saved");

                Collection keys = response.getCollection();

                for (Object k : keys) {
                    Key orgKey = (Key) k;
                    String id = orgKey.getId();
                    System.out.println("Organization key is " + id);
                }
            } else {
                for (Object e : exceptions) {
                    Exception exception = (Exception) e;
                    System.err.println("Exception on save: " + exception.toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // At end, close connection to registry
            if (connection != null) {
                try {
                    connection.close();
                } catch (JAXRException je) {
                }
            }
        }
    }

From source file:com.freedomotic.plugins.devices.ipx800.Ipx800.java

private Document getXMLStatusFile(Board board) {
    final Board b = board;
    //get the xml file from the socket connection
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = null;
    try {//from   w  w w  . j av  a 2 s .co m
        dBuilder = dbFactory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        LOG.error(ex.getMessage());
    }
    Document doc = null;
    String statusFileURL = null;
    try {
        if (board.getAuthentication().equalsIgnoreCase("true")) {
            Authenticator.setDefault(new Authenticator() {

                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(b.getUsername(), b.getPassword().toCharArray());
                }
            });
            statusFileURL = "http://" + b.getIpAddress() + ":" + Integer.toString(b.getPort())
                    + b.getPathAuthentication() + "/" + GET_STATUS_URL;
        } else {
            statusFileURL = "http://" + board.getIpAddress() + ":" + Integer.toString(board.getPort()) + "/"
                    + GET_STATUS_URL;
        }
        LOG.info("Ipx800 gets relay status from file {0}", statusFileURL);
        doc = dBuilder.parse(new URL(statusFileURL).openStream());
        doc.getDocumentElement().normalize();
    } catch (ConnectException connEx) {
        LOG.error(Freedomotic.getStackTraceInfo(connEx));
        //disconnect();
        this.stop();
        this.setDescription("Connection timed out, no reply from the board at " + statusFileURL);
    } catch (SAXException ex) {
        //this.stop();
        LOG.error(Freedomotic.getStackTraceInfo(ex));
    } catch (Exception ex) {
        //this.stop();
        setDescription("Unable to connect to " + statusFileURL);
        LOG.error(Freedomotic.getStackTraceInfo(ex));
    }
    return doc;
}