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.kawanfw.commons.client.http.HttpTransferOne.java

/**
 * Sets the proxy credentials// w ww .ja  v  a2 s. c  om
 * 
 */
private void setProxyCredentials() {

    if (proxy == null) {
        try {
            displayErrroMessageIfNoProxySet();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return;
    }

    // Sets the credential for authentication
    if (passwordAuthentication != null) {
        final String proxyAuthUsername = passwordAuthentication.getUserName();
        final char[] proxyPassword = passwordAuthentication.getPassword();

        Authenticator authenticator = new Authenticator() {

            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyAuthUsername, proxyPassword);
            }
        };

        Authenticator.setDefault(authenticator);
    }

}

From source file:hudson.remoting.Launcher.java

public void run() throws Exception {
    if (auth != null) {
        final int idx = auth.indexOf(':');
        if (idx < 0)
            throw new CmdLineException(null, "No ':' in the -auth option");
        Authenticator.setDefault(new Authenticator() {
            @Override//from w w  w .  j a  v  a  2s . c o m
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(auth.substring(0, idx),
                        auth.substring(idx + 1).toCharArray());
            }
        });
    }
    if (connectionTarget != null) {
        runAsTcpClient();
        System.exit(0);
    } else if (slaveJnlpURL != null) {
        List<String> jnlpArgs = parseJnlpArguments();
        try {
            hudson.remoting.jnlp.Main._main(jnlpArgs.toArray(new String[jnlpArgs.size()]));
        } catch (CmdLineException e) {
            System.err.println("JNLP file " + slaveJnlpURL + " has invalid arguments: " + jnlpArgs);
            System.err.println("Most likely a configuration error in the master");
            System.err.println(e.getMessage());
            System.exit(1);
        }
    } else if (tcpPortFile != null) {
        runAsTcpServer();
        System.exit(0);
    } else {
        runWithStdinStdout();
        System.exit(0);
    }
}

From source file:org.caleydo.data.importer.tcga.Settings.java

public boolean validate() {
    if (dataRuns == null)
        dataRuns = analysisRuns;//from w  w  w.ja va2s  .  co m
    if (dataRuns.size() != analysisRuns.size()) {
        System.err.println(
                "Error during parsing of program arguments. You need to provide a corresponding data run for each analysis run. Closing program.");
        return false;
    }

    if (numThreads <= 0)
        numThreads = Runtime.getRuntime().availableProcessors();

    if (username != null && password != null) {
        username = fixPrompt(username, "Enter the username: ");
        password = fixPrompt(password, "Enter the password: ");
        // set Authenticator for following urls
        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password.toCharArray());
            }
        });
    }

    if (awgGroup != null) {
        String tumor = awgGroup.toUpperCase();
        // check if not manually overridden
        if (analysisPattern.equals(ANALYSIS_PATTERN))
            analysisPattern = BASE_URL + "awg_" + awgGroup
                    + "__{0,date,yyyy_MM_dd}/data/{2}/{0,date,yyyyMMdd}/{3}";
        if (filePattern.equals(FILE_PATTERN))
            filePattern = "gdac.broadinstitute.org_{1}.{3}.Level_{4}.{0,date,yyyyMMdd}00.0.0.tar.gz";
        if (dataPattern.equals(DATA_PATTERN))
            dataPattern = BASE_URL + "/stddata__{0,date,yyyy_MM_dd}/data/" + tumor + "/{0,date,yyyyMMdd}/{3}";
        if (dataFilePattern.equals(DATAFILE_PATTERN))
            dataFilePattern = "gdac.broadinstitute.org_" + tumor
                    + ".{3}.Level_{4}.{0,date,yyyyMMdd}00.0.0.tar.gz";
        if (reportPattern.equals(REPORT_PATTERN))
            reportPattern = BASE_URL + "awg_" + awgGroup + "__{0,date,yyyy_MM_dd}/reports/cancer/{1}/";
    }

    return true;
}

From source file:JAXRDelete.java

/**
     * Removes the organization with the specified key value.
     *//from  ww w  . j  a v a  2 s .  com
     * @param key        the Key of the organization
     * @param username  the username for the registry
     * @param password  the password for the registry
     */
    public void executeRemove(Key key, String username, String password) {
        BusinessLifeCycleManager blcm = null;

        try {
            blcm = rs.getBusinessLifeCycleManager();

            // 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");

            String id = key.getId();
            System.out.println("Deleting organization with id " + id);

            Collection<Key> keys = new ArrayList<Key>();
            keys.add(key);

            BulkResponse response = blcm.deleteOrganizations(keys);
            Collection exceptions = response.getExceptions();

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

                Collection retKeys = response.getCollection();

                for (Object k : retKeys) {
                    Key orgKey = (Key) k;
                    id = orgKey.getId();
                    System.out.println("Organization key was " + id);
                }
            } else {
                for (Object e : exceptions) {
                    Exception exception = (Exception) e;
                    System.err.println("Exception on delete: " + 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:JAXRDeleteConcept.java

/**
     * Removes the organization with the specified key value.
     */* ww w.  j ava 2 s.co  m*/
     * @param key        the Key of the organization
     * @param username  the username for the registry
     * @param password  the password for the registry
     */
    public void executeRemove(Key key, String username, String password) {
        BusinessLifeCycleManager blcm = null;

        try {
            blcm = rs.getBusinessLifeCycleManager();

            // 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");

            String id = key.getId();
            System.out.println("Deleting concept with id " + id);

            Collection<Key> keys = new ArrayList<Key>();
            keys.add(key);

            BulkResponse response = blcm.deleteConcepts(keys);
            Collection exceptions = response.getExceptions();

            if (exceptions == null) {
                System.out.println("Concept deleted");

                Collection retKeys = response.getCollection();

                for (Object k : retKeys) {
                    Key concKey = (Key) k;
                    id = concKey.getId();
                    System.out.println("Concept key was " + id);
                }
            } else {
                for (Object e : exceptions) {
                    Exception exception = (Exception) e;
                    System.err.println("Exception on delete: " + 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:JAXRPublishHelloOrg.java

/**
     * Creates an organization, its classification, and its
     * services, and saves it to the registry.
     */*from   www  . 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 uuidString, String username, String password) {
        RegistryService rs = null;
        BusinessLifeCycleManager blcm = null;
        BusinessQueryManager bqm = null;

        try {
            // Get registry service and managers
            rs = connection.getRegistryService();
            bqm = rs.getBusinessQueryManager();
            blcm = rs.getBusinessLifeCycleManager();
            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("wsdlorg.name"));
            Organization org = blcm.createOrganization(s);
            s = blcm.createInternationalString(bundle.getString("wsdlorg.description"));
            org.setDescription(s);

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

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

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

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

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

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

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

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

            /*
             * 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.
             */
            Classification wsdlSpecClassification = blcm.createClassification(uddiOrgTypes,
                    blcm.createInternationalString("wsdlSpec"), "wsdlSpec");

            // Define classifications
            Collection<Classification> classifications = new ArrayList<Classification>();
            classifications.add(wsdlSpecClassification);

            // Find the concept by its UUID
            Concept specConcept = (Concept) bqm.getRegistryObject(uuidString, LifeCycleManager.CONCEPT);

            // If we found the concept, we can save the organization
            if (specConcept != null) {
                String name = getName(specConcept);

                Collection links = specConcept.getExternalLinks();

                System.out.println("\nSpecification Concept:\n\tName: " + name + "\n\tKey: " + getKey(specConcept));

                if (links.size() > 0) {
                    ExternalLink link = (ExternalLink) links.iterator().next();
                    System.out.println("\tURL of WSDL document: '" + link.getExternalURI() + "'");
                }

                // Now set the specification link for the service binding
                SpecificationLink specLink = blcm.createSpecificationLink();
                specLink.setSpecificationObject(specConcept);

                binding.addSpecificationLink(specLink);
                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());
                    }
                }
            } else {
                System.out.println("Specified concept not found, " + "organization not saved");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // At end, close connection to registry
            if (connection != null) {
                try {
                    connection.close();
                } catch (JAXRException je) {
                }
            }
        }
    }

From source file:nl.b3p.viewer.stripes.CycloramaActionBean.java

public Resolution directRequest() throws UnsupportedEncodingException, URISyntaxException, URIException,
        IOException, SAXException, ParserConfigurationException {
    Double x1 = x - offset;//from   w w  w . ja v  a 2 s  .c o m
    Double y1 = y - offset;
    Double x2 = x + offset;
    Double y2 = y + offset;
    final String username = "B3_develop";
    final String password = "8ndj39";
    GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();

    Coordinate coord = new Coordinate(x, y);
    Point point = geometryFactory.createPoint(coord);

    URL url2 = new URL(
            "https://atlas.cyclomedia.com/recordings/wfs?service=WFS&VERSION=1.1.0&maxFeatures=100&request=GetFeature&SRSNAME=EPSG:28992&typename=atlas:Recording"
                    + "&filter=<Filter><And><BBOX><gml:Envelope%20srsName=%27EPSG:28992%27>"
                    + "<gml:lowerCorner>" + x1.intValue() + "%20" + y1.intValue() + "</gml:lowerCorner>"
                    + "<gml:upperCorner>" + x2.intValue() + "%20" + y2.intValue()
                    + "</gml:upperCorner></gml:Envelope></BBOX><ogc:PropertyIsNull><ogc:PropertyName>expiredAt</ogc:PropertyName></ogc:PropertyIsNull></And></Filter>");

    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password.toCharArray());
        }
    });
    InputStream is = url2.openStream();

    // wrap the urlconnection in a bufferedreader
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));

    String line;

    StringBuilder content = new StringBuilder();
    // read from the urlconnection via the bufferedreader
    while ((line = bufferedReader.readLine()) != null) {
        content.append(line + "\n");
    }
    bufferedReader.close();

    String s = content.toString();
    String tsString = "timeStamp=";
    int indexOfTimestamp = s.indexOf(tsString);
    int indexOfLastQuote = s.indexOf("\"", indexOfTimestamp + 2 + tsString.length());
    String contentString = s.substring(0, indexOfTimestamp - 2);
    contentString += s.substring(indexOfLastQuote);

    contentString = removeDates(contentString, "<atlas:recordedAt>", "</atlas:recordedAt>");

    Configuration configuration = new org.geotools.gml3.GMLConfiguration();
    configuration.getContext().registerComponentInstance(new GeometryFactory(new PrecisionModel(), 28992));

    Parser parser = new Parser(configuration);
    parser.setValidating(false);
    parser.setStrict(false);
    parser.setFailOnValidationError(false);

    ByteArrayInputStream bais = new ByteArrayInputStream(contentString.getBytes());
    Object obj = parser.parse(bais);

    SimpleFeatureCollection fc = (SimpleFeatureCollection) obj;

    SimpleFeatureIterator it = fc.features();
    SimpleFeature sf = null;
    List<SimpleFeature> fs = new ArrayList<SimpleFeature>();
    while (it.hasNext()) {
        sf = it.next();
        sf.getUserData().put(DISTANCE_KEY, point.distance((Geometry) sf.getDefaultGeometry()));
        fs.add(sf);
    }
    Collections.sort(fs, new Comparator<SimpleFeature>() {
        @Override
        public int compare(SimpleFeature o1, SimpleFeature o2) {
            Double d1 = (Double) o1.getUserData().get(DISTANCE_KEY);
            Double d2 = (Double) o2.getUserData().get(DISTANCE_KEY);
            return d1.compareTo(d2);
        }
    });
    SimpleFeature f = fs.get(0);
    imageId = (String) f.getAttribute("imageId");
    sign();
    return new ForwardResolution("/WEB-INF/jsp/app/globespotter.jsp");
}

From source file:JAXRDeleteScheme.java

/**
     * Removes the classification scheme with the specified key value.
     *//w ww  .j a  va 2 s. c  om
     * @param key        the Key of the organization
     * @param username  the username for the registry
     * @param password  the password for the registry
     */
    public void executeRemove(Key key, String username, String password) {
        BusinessLifeCycleManager blcm = null;

        try {
            blcm = rs.getBusinessLifeCycleManager();

            // 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");

            String id = key.getId();
            System.out.println("Deleting classification scheme with id " + id);

            Collection<Key> keys = new ArrayList<Key>();
            keys.add(key);

            BulkResponse response = blcm.deleteClassificationSchemes(keys);
            Collection exceptions = response.getExceptions();

            if (exceptions == null) {
                System.out.println("Classification scheme deleted");

                Collection retKeys = response.getCollection();

                for (Object k : retKeys) {
                    Key schemeKey = (Key) k;
                    id = schemeKey.getId();
                    System.out.println("Classification scheme key was " + id);
                }
            } else {
                for (Object e : exceptions) {
                    Exception exception = (Exception) e;
                    System.err.println("Exception on delete: " + 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:hudson.ProxyConfiguration.java

public static InputStream getInputStream(URL url) throws IOException {
    Jenkins h = Jenkins.getInstance(); // this code might run on slaves
    final ProxyConfiguration p = (h != null) ? h.proxy : null;
    if (p == null)
        return new RetryableHttpStream(url);

    InputStream is = new RetryableHttpStream(url, p.createProxy(url.getHost()));
    if (p.getUserName() != null) {
        // Add an authenticator which provides the credentials for proxy authentication
        Authenticator.setDefault(new Authenticator() {

            @Override//from  ww w.j a  v  a  2s  .  c om
            public PasswordAuthentication getPasswordAuthentication() {
                if (getRequestorType() != RequestorType.PROXY) {
                    return null;
                }
                return new PasswordAuthentication(p.getUserName(), p.getPassword().toCharArray());
            }
        });
    }

    return is;
}