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:io.uploader.drive.config.Configuration.java

private void setProxy() {
    setProxySystemProperty(httpProxySettings, "http");
    setProxySystemProperty(httpsProxySettings, "https");

    Authenticator.setDefault(new Authenticator() {
        @Override//from w ww .  ja  va  2  s  . c  o  m
        protected PasswordAuthentication getPasswordAuthentication() {
            if (getRequestorType() == RequestorType.PROXY) {
                String prot = getRequestingProtocol().toLowerCase();

                String host = System.getProperty(prot + ".proxyHost", "");
                String port = System.getProperty(prot + ".proxyPort", "80");
                String user = System.getProperty(prot + ".proxyUser", "");
                String password = System.getProperty(prot + ".proxyPassword", "");

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

From source file:org.openbravo.test.datasource.TestAllowUnpagedDatasourcePreference.java

private HttpURLConnection createConnection(String wsPart, String method) throws Exception {
    Authenticator.setDefault(new Authenticator() {
        @Override/*w w w.j ava2 s  .  com*/
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(LOGIN, PWD.toCharArray());
        }
    });
    final URL url = new URL(getOpenbravoURL() + wsPart);
    final HttpURLConnection hc = (HttpURLConnection) url.openConnection();
    hc.setRequestMethod(method);
    hc.setAllowUserInteraction(false);
    hc.setDefaultUseCaches(false);
    hc.setDoOutput(true);
    hc.setDoInput(true);
    hc.setInstanceFollowRedirects(true);
    hc.setUseCaches(false);
    hc.setRequestProperty("Content-Type", "text/xml");
    return hc;
}

From source file:sce.RESTKBJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    try {/*from  w ww  . j  av a2s.  com*/
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();

        String url = jobDataMap.getString("#url");
        if (url == null) {
            throw new JobExecutionException("#url parameter must be not null");
        }

        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());
                }
            });
        }

        //set the url connection, to disconnect if interrupt() is requested
        this.urlConnection = u.openConnection();

        //set the "Accept" header
        this.urlConnection.setRequestProperty("Accept", "application/sparql-results+xml");

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document document = docBuilder.parse(this.urlConnection.getInputStream());

        parseKBResponse(document.getDocumentElement(), context);

        //set of the result is done in the method parseKBresponse, because it is built invoking it iteratively
        //set the result to the job execution context, to be able to retrieve it later (e.g., with a job listener)
        //context.setResult(result);
        //if notificationEmail is defined in the job data map, then send a notification email to it
        if (jobDataMap.containsKey("#notificationEmail")) {
            sendEmail(context, jobDataMap.getString("#notificationEmail"));
        }

        //trigger the linked jobs of the finished job, depending on the job result [true, false]
        jobChain(context);
        //System.out.println("Instance " + key + " of REST Job returns: " + truncateResult(result));
    } catch (IOException | ParserConfigurationException | SAXException e) {
        e.printStackTrace(System.out);
        throw new JobExecutionException(e);
    }
}

From source file:info.joseluismartin.gtc.mvc.CacheController.java

protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(username, password.toCharArray());
}

From source file:JAXRPublishPostal.java

/**
     * Creates an organization, its classification, and its
     * services, and saves it to the registry.  The primary
     * contact has a postal address.//from   w w  w  .j  av a2  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("postal.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("postal.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("postal.email.address"));
            Collection<EmailAddress> emailAddresses = new ArrayList<EmailAddress>();
            emailAddresses.add(emailAddress);
            primaryContact.setEmailAddresses(emailAddresses);

            // create postal address for primary contact
            String streetNumber = bundle.getString("postal.streetNumber");
            String street = bundle.getString("postal.street");
            String city = bundle.getString("postal.city");
            String state = bundle.getString("postal.state");
            String country = bundle.getString("postal.country");
            String postalCode = bundle.getString("postal.postalCode");
            String type = bundle.getString("postal.type");
            PostalAddress postAddr = blcm.createPostalAddress(streetNumber, street, city, state, country,
                    postalCode, type);
            Collection<PostalAddress> postalAddresses = new ArrayList<PostalAddress>();
            postalAddresses.add(postAddr);
            primaryContact.setPostalAddresses(postalAddresses);

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

            // Create and add classification
            if (cScheme != null) {
                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; don't validate this fake URL
            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.intellij.util.net.HttpConfigurable.java

public PasswordAuthentication getGenericPromptedAuthentication(final String prefix, final String host,
        final String prompt, final int port, final boolean remember) {
    if (ApplicationManager.getApplication().isUnitTestMode()) {
        return myTestGenericAuthRunnable.get();
    }//from w w w  .ja  v  a2s .  co m
    final PasswordAuthentication[] value = new PasswordAuthentication[1];
    final Runnable runnable = new Runnable() {
        public void run() {
            if (isGenericPasswordCanceled(host, port))
                return;
            final PasswordAuthentication password = getGenericPassword(host, port);
            if (password != null) {
                value[0] = password;
                return;
            }
            final AuthenticationDialog dlg = new AuthenticationDialog(PopupUtil.getActiveComponent(),
                    prefix + host, "Please enter credentials for: " + prompt, "", "", remember);
            dlg.show();
            if (dlg.getExitCode() == DialogWrapper.OK_EXIT_CODE) {
                final AuthenticationPanel panel = dlg.getPanel();
                final boolean remember1 = remember && panel.isRememberPassword();
                value[0] = new PasswordAuthentication(panel.getLogin(), panel.getPassword());
                putGenericPassword(host, port, value[0], remember1);
            } else {
                setGenericPasswordCanceled(host, port);
            }
        }
    };
    runAboveAll(runnable);
    return value[0];
}

From source file:org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin.java

private void configureProxy() {
    // It seems there is no way to set a proxy provider type (manual, native or
    // direct) without the Eclipse UI.
    // The org.eclipse.core.net plugin removes the http., https. system properties
    // when setting its preferences and a proxy provider isn't manual.
    // We save these parameters and set them after starting the
    // org.eclipse.core.net plugin.
    String httpHost = System.getProperty(HTTP_PROXY_HOST);
    String httpPort = System.getProperty(HTTP_PROXY_PORT);
    String httpUser = System.getProperty(HTTP_PROXY_USER);
    String httpPassword = System.getProperty(HTTP_PROXY_PASSWORD);
    String httpsHost = System.getProperty(HTTPS_PROXY_HOST);
    String httpsPort = System.getProperty(HTTPS_PROXY_PORT);
    String httpsUser = System.getProperty(HTTPS_PROXY_USER);
    String httpsPassword = System.getProperty(HTTPS_PROXY_PASSWORD);
    String httpsNonProxyHosts = System.getProperty(HTTPS_NON_PROXY_HOSTS);
    String httpNonProxyHosts = System.getProperty(HTTP_NON_PROXY_HOSTS);
    if (StringUtils.isNotBlank(httpUser) || StringUtils.isNotBlank(httpsUser)) {
        try {// w ww  . j  ava  2s .c o m
            Platform.getBundle("org.eclipse.core.net").start(Bundle.START_TRANSIENT);
        } catch (BundleException e) {
            logException(e.getMessage(), e);
        }
        if (StringUtils.isNotBlank(httpUser) && StringUtils.isNotBlank(httpPassword)) {
            Authenticator.setDefault(new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(httpUser, httpPassword.toCharArray());
                }
            });
        }
        IProxyService proxyService = getProxyService();
        if (proxyService != null) {
            ProxySelector.setActiveProvider(MANUAL);
            IProxyData[] proxies = proxyService.getProxyData();
            for (IProxyData proxy : proxies) {
                if ("HTTP".equals(proxy.getType())) {
                    proxy.setHost(httpHost);
                    proxy.setPort(httpPort == null ? -1 : Integer.valueOf(httpPort));
                    proxy.setPassword(httpPassword);
                    proxy.setUserid(httpUser);
                }
                if ("HTTPS".equals(proxy.getType())) {
                    proxy.setHost(httpsHost);
                    proxy.setPort(httpsPort == null ? -1 : Integer.valueOf(httpsPort));
                    proxy.setPassword(httpsPassword);
                    proxy.setUserid(httpsUser);
                }
            }
            try {
                proxyService.setProxyData(proxies);
                if (httpHost != null) {
                    System.setProperty(HTTP_PROXY_HOST, httpHost);
                }
                if (httpPort != null) {
                    System.setProperty(HTTP_PROXY_PORT, httpPort);
                }
                if (httpUser != null) {
                    System.setProperty(HTTP_PROXY_USER, httpUser);
                }
                if (httpPassword != null) {
                    System.setProperty(HTTP_PROXY_PASSWORD, httpPassword);
                }
                if (httpsHost != null) {
                    System.setProperty(HTTPS_PROXY_HOST, httpsHost);
                }
                if (httpsPort != null) {
                    System.setProperty(HTTPS_PROXY_PORT, httpsPort);
                }
                if (httpsUser != null) {
                    System.setProperty(HTTPS_PROXY_USER, httpsUser);
                }
                if (httpsPassword != null) {
                    System.setProperty(HTTPS_PROXY_PASSWORD, httpsPassword);
                }
                if (httpsNonProxyHosts != null) {
                    System.setProperty(HTTPS_NON_PROXY_HOSTS, httpsNonProxyHosts);
                }
                if (httpNonProxyHosts != null) {
                    System.setProperty(HTTP_NON_PROXY_HOSTS, httpNonProxyHosts);
                }
            } catch (CoreException e) {
                logException(e.getMessage(), e);
            }
        }
    }
}

From source file:com.hortonworks.registries.storage.tool.sql.DatabaseUserInitializer.java

private static Authenticator getBasicAuthenticator(String host, int port, String username, String password) {
    return new Authenticator() {
        @Override/* w w  w.  j a  v a  2  s . com*/
        protected PasswordAuthentication getPasswordAuthentication() {
            if (getRequestorType() == RequestorType.PROXY) {
                if (getRequestingHost().equalsIgnoreCase(host)) {
                    if (getRequestingPort() == port) {
                        return new PasswordAuthentication(username, password.toCharArray());
                    }
                }
            }
            return null;
        }
    };
}

From source file:org.drools.guvnor.server.files.PackageDeploymentServletChangeSetIntegrationTest.java

@Test
@RunAsClient/*from ww  w . j  a  va  2 s.c  o m*/
public void downloadPackageWithHttpClientImpl(@ArquillianResource URL baseURL)
        throws IOException, ClassNotFoundException {
    URL url = new URL(baseURL, "org.drools.guvnor.Guvnor/package/downloadPackageWithHttpClientImpl/snapshotC1");
    Resource resource = ResourceFactory.newUrlResource(url);
    KnowledgeAgentConfiguration conf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration();
    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("admin", "admin".toCharArray());
        }
    });
    InputStream in = null;
    Collection<KnowledgePackage> kpkgs = null;
    try {
        in = resource.getInputStream();
        Object object = DroolsStreamUtils.streamIn(in);
        if (object instanceof Collection) {
            kpkgs = (Collection<KnowledgePackage>) object;
        } else if (object instanceof KnowledgePackageImp) {
            kpkgs = Collections.singletonList((KnowledgePackage) object);
        } else if (object instanceof Package) {
            kpkgs = Collections.singletonList((KnowledgePackage) new KnowledgePackageImp((Package) object));
        } else if (object instanceof Package[]) {
            kpkgs = new ArrayList<KnowledgePackage>();
            for (Package pkg : (Package[]) object) {
                kpkgs.add(new KnowledgePackageImp(pkg));
            }
        } else {
            throw new RuntimeException("Unknown binary format trying to load resource " + resource.toString());
        }
    } finally {
        IOUtils.closeQuietly(in);
    }

    assertNotNull(kpkgs);
    assertFalse(kpkgs.isEmpty());
    assertNotNull(kpkgs.iterator().next());
}

From source file:com.freedomotic.plugins.devices.phwswethv2.ProgettiHwSwEthv2.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 {/*www  .j  av  a 2  s.c  om*/
        dBuilder = dbFactory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(ProgettiHwSwEthv2.class.getName()).log(Level.SEVERE, null, ex);
    }
    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()) + "/protect/"
                    + GET_STATUS_URL;
        } else {
            statusFileURL = "http://" + b.getIpAddress() + ":" + Integer.toString(b.getPort()) + "/"
                    + GET_STATUS_URL;
        }

        LOG.info("ProgettiHwSwEth gets relay status from file " + statusFileURL);
        doc = dBuilder.parse(new URL(statusFileURL).openStream());
        doc.getDocumentElement().normalize();
    } catch (ConnectException connEx) {
        disconnect();
        this.stop();
        this.setDescription("Connection timed out, no reply from the board at " + statusFileURL);
    } catch (SAXException ex) {
        disconnect();
        this.stop();
        LOG.severe(Freedomotic.getStackTraceInfo(ex));
    } catch (Exception ex) {
        disconnect();
        this.stop();
        setDescription("Unable to connect to " + statusFileURL);
        LOG.severe(Freedomotic.getStackTraceInfo(ex));
    }
    return doc;

}