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:com.ericsson.eiffel.remrem.semantics.clone.PrepareLocalEiffelSchemas.java

/**
 * This method is used get the proxy instance by using user provided proxy details
 * //from w w w  .  j  a v  a2s. c  o  m
 * @param httpProxyUrl proxy url configured in property file
 * @param httpProxyPort proxy port configured in property file
 * @param httpProxyUsername proxy username to authenticate
 * @param httpProxyPassword proxy password to authenticate
 * @return proxy instance
 */
private Proxy getProxy(final String httpProxyUrl, final String httpProxyPort, final String httpProxyUsername,
        final String httpProxyPassword) {
    if (!httpProxyUrl.isEmpty() && !httpProxyPort.isEmpty()) {
        final InetSocketAddress socket = InetSocketAddress.createUnresolved(httpProxyUrl,
                Integer.parseInt(httpProxyPort));
        if (!httpProxyUsername.isEmpty() && !httpProxyPassword.isEmpty()) {
            Authenticator authenticator = new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    LOGGER.info("proxy authentication called");
                    return (new PasswordAuthentication(httpProxyUsername, httpProxyPassword.toCharArray()));
                }
            };
            Authenticator.setDefault(authenticator);
        }
        return new Proxy(Proxy.Type.HTTP, socket);
    }
    return null;
}

From source file:org.nuxeo.ecm.core.storage.sql.JCloudsBinaryManager.java

@Override
public void initialize(BinaryManagerDescriptor binaryManagerDescriptor) throws IOException {
    super.initialize(binaryManagerDescriptor);

    // Get settings from the configuration
    storeProvider = Framework.getProperty(BLOBSTORE_PROVIDER_KEY);
    if (isBlank(storeProvider)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_PROVIDER_KEY);
    }/*  w ww  .  j a  va2  s .com*/
    container = Framework.getProperty(BLOBSTORE_MAP_NAME_KEY);
    if (isBlank(container)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_MAP_NAME_KEY);
    }

    String storeLocation = Framework.getProperty(BLOBSTORE_LOCATION_KEY);
    if (isBlank(storeLocation)) {
        storeLocation = null;
    }

    String storeIdentity = Framework.getProperty(BLOBSTORE_IDENTITY_KEY);
    if (isBlank(storeIdentity)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_IDENTITY_KEY);
    }

    String storeSecret = Framework.getProperty(BLOBSTORE_SECRET_KEY);
    if (isBlank(storeSecret)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_SECRET_KEY);
    }

    String cacheSizeStr = Framework.getProperty(CACHE_SIZE_KEY);
    if (isBlank(cacheSizeStr)) {
        cacheSizeStr = DEFAULT_CACHE_SIZE;
    }

    String proxyHost = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_HOST);
    String proxyPort = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PORT);
    final String proxyLogin = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_LOGIN);
    final String proxyPassword = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PASSWORD);

    // Set up proxy
    if (isNotBlank(proxyHost)) {
        System.setProperty("https.proxyHost", proxyHost);
    }
    if (isNotBlank(proxyPort)) {
        System.setProperty("https.proxyPort", proxyPort);
    }
    if (isNotBlank(proxyLogin)) {
        System.setProperty("https.proxyUser", proxyLogin);
        System.setProperty("https.proxyPassword", proxyPassword);
        Authenticator.setDefault(new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyLogin, proxyPassword.toCharArray());
            }
        });
    }

    BlobStoreContext context = ContextBuilder.newBuilder(storeProvider).credentials(storeIdentity, storeSecret)
            .buildView(BlobStoreContext.class);

    // Try to create container if it doesn't exist
    blobStore = context.getBlobStore();
    boolean created = false;
    if (storeLocation == null) {
        created = blobStore.createContainerInLocation(null, container);
    } else {
        Location location = new LocationBuilder().scope(LocationScope.REGION).id(storeLocation)
                .description(storeLocation).build();
        created = blobStore.createContainerInLocation(location, container);
    }
    if (created) {
        log.debug("Created container " + container);
    }

    // Create file cache
    initializeCache(cacheSizeStr, new JCloudsFileStorage());
    createGarbageCollector();
}

From source file:org.nuxeo.ecm.blob.jclouds.JCloudsBinaryManager.java

@Override
public void initialize(String blobProviderId, Map<String, String> properties) throws IOException {
    super.initialize(blobProviderId, properties);

    // Get settings from the configuration
    storeProvider = getConfigurationProperty(BLOBSTORE_PROVIDER_KEY, properties);
    if (isBlank(storeProvider)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_PROVIDER_KEY);
    }//from  w ww . ja  va2s.  c  o  m

    container = getConfigurationProperty(BLOBSTORE_MAP_NAME_KEY, properties);
    if (isBlank(container)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_MAP_NAME_KEY);
    }

    endpoint = getConfigurationProperty(BLOBSTORE_ENDPOINT_KEY, properties);

    String storeLocation = getConfigurationProperty(BLOBSTORE_LOCATION_KEY, properties);
    if (isBlank(storeLocation)) {
        storeLocation = null;
    }

    String storeIdentity = getConfigurationProperty(BLOBSTORE_IDENTITY_KEY, properties);
    if (isBlank(storeIdentity)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_IDENTITY_KEY);
    }

    String storeSecret = getConfigurationProperty(BLOBSTORE_SECRET_KEY, properties);
    if (isBlank(storeSecret)) {
        throw new RuntimeException("Missing conf: " + BLOBSTORE_SECRET_KEY);
    }

    String cacheSizeStr = getConfigurationProperty(CACHE_SIZE_KEY, properties);
    if (isBlank(cacheSizeStr)) {
        cacheSizeStr = DEFAULT_CACHE_SIZE;
    }

    String proxyHost = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_HOST);
    String proxyPort = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PORT);
    final String proxyLogin = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_LOGIN);
    final String proxyPassword = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PASSWORD);

    // Set up proxy
    if (isNotBlank(proxyHost)) {
        System.setProperty("https.proxyHost", proxyHost);
    }
    if (isNotBlank(proxyPort)) {
        System.setProperty("https.proxyPort", proxyPort);
    }
    if (isNotBlank(proxyLogin)) {
        System.setProperty("https.proxyUser", proxyLogin);
        System.setProperty("https.proxyPassword", proxyPassword);
        Authenticator.setDefault(new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyLogin, proxyPassword.toCharArray());
            }
        });
    }

    ContextBuilder builder = ContextBuilder.newBuilder(storeProvider).credentials(storeIdentity, storeSecret);

    if (isNotBlank(endpoint)) {
        builder.endpoint(endpoint);
    }

    BlobStoreContext context = builder.buildView(BlobStoreContext.class);

    // Try to create container if it doesn't exist
    blobStore = context.getBlobStore();
    boolean created = false;
    if (storeLocation == null) {
        created = blobStore.createContainerInLocation(null, container);
    } else {
        Location location = new LocationBuilder().scope(LocationScope.REGION).id(storeLocation)
                .description(storeLocation).build();
        created = blobStore.createContainerInLocation(location, container);
    }
    if (created) {
        log.debug("Created container " + container);
    }

    // Create file cache
    initializeCache(cacheSizeStr, new JCloudsFileStorage());
    createGarbageCollector();
}

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

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

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

@Test
@RunAsClient/*from   www .j  a va2s  .c o m*/
public void scanForChangeInRepository(@ArquillianResource URL baseURL) throws Exception {
    URL url = new URL(baseURL,
            "org.drools.guvnor.Guvnor/package/scanForChangeInRepository/LATEST/ChangeSet.xml");
    Resource res = ResourceFactory.newUrlResource(url);
    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("admin", "admin".toCharArray());
        }
    });

    // system event listener
    SystemEventListenerFactory.setSystemEventListener(new PrintStreamSystemEventListener(System.out));

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    KnowledgeAgentConfiguration conf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration();
    // needs to be newInstance=true, bugzilla 733008 works fine with newInstance=false
    conf.setProperty("drools.agent.newInstance", "true");
    KnowledgeAgent kagent = KnowledgeAgentFactory.newKnowledgeAgent("agent", kbase, conf);

    try {
        ResourceFactory.getResourceChangeNotifierService().start();
        ResourceFactory.getResourceChangeScannerService().start();

        ResourceChangeScannerConfiguration sconf = ResourceFactory.getResourceChangeScannerService()
                .newResourceChangeScannerConfiguration();
        sconf.setProperty("drools.resource.scanner.interval", "5");
        ResourceFactory.getResourceChangeScannerService().configure(sconf);

        kagent.applyChangeSet(res);
        kbase = kagent.getKnowledgeBase();
        Thread.sleep(1000);
        assertEquals(2, kbase.getKnowledgePackages().iterator().next().getRules().size());
        System.out.println("BUGZILLA 733008 total rules: "
                + kbase.getKnowledgePackages().iterator().next().getRules().size());
        for (Rule r : kbase.getKnowledgePackages().iterator().next().getRules()) {
            System.out.println(r.getName());
        }

        // Change Guvnor's repo with REST api by deleting asset rule2
        Abdera abdera = new Abdera();
        AbderaClient client = new AbderaClient(abdera);
        client.addCredentials(baseURL.toExternalForm(), null, null,
                new org.apache.commons.httpclient.UsernamePasswordCredentials("admin", "admin"));
        ClientResponse deleteResponse = client.delete(
                new URL(baseURL, "rest/packages/scanForChangeInRepository/assets/ruleB2").toExternalForm());
        assertEquals(204, deleteResponse.getStatus());
        ClientResponse binaryResponse = client
                .get(new URL(baseURL, "rest/packages/scanForChangeInRepository/binary").toExternalForm());
        assertEquals(200, binaryResponse.getStatus());

        // detect the change
        Thread.sleep(6000);
        kbase = kagent.getKnowledgeBase();
        assertEquals(1, kbase.getKnowledgePackages().iterator().next().getRules().size());

    } finally {
        kagent.dispose();
        ResourceFactory.getResourceChangeNotifierService().stop();
        ResourceFactory.getResourceChangeScannerService().stop();
    }
}

From source file:com.maestrodev.plugins.collabnet.FrsCopyWorker.java

private String copyArtifact(FrsSession frsSession, String releaseId)
        throws MalformedURLException, RemoteException {
    Artifact artifact = new DefaultArtifact(artifactGroupId, artifactId,
            VersionRange.createFromVersion(artifactVersion), null, artifactType, artifactClassifier,
            new DefaultArtifactHandler(artifactType));
    String path = new DefaultRepositoryLayout().pathOf(artifact);
    String url = repositoryUrl + "/" + path;

    String filename = this.filename;
    if (StringUtils.isBlank(filename)) {
        filename = path.substring(path.lastIndexOf('/') + 1);
    }/*from   www  .j  a v a2s . c  om*/

    String msg = "Uploading '" + url + "' to release '" + releaseId + "' as '" + filename + "'";
    logger.debug(msg);
    writeOutput(msg + "\n");

    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(repositoryUsername, repositoryPassword.toCharArray());
        }
    });

    return frsSession.uploadFileFromUrl(releaseId, new URL(url), filename, overwrite);
}

From source file:JAXRGetMyObjects.java

/**
     * Searches for objects owned by the user and
     * displays data about them./*from w  ww  . j ava  2s. com*/
     *
     * @param username  the username for the registry
     * @param password  the password for the registry
     */
    public void executeQuery(String username, String password) {
        RegistryService rs = null;
        BusinessQueryManager bqm = null;

        try {
            // Get registry service and query manager
            rs = connection.getRegistryService();
            bqm = rs.getBusinessQueryManager();
            System.out.println("Got registry service and " + "query 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");

            // Get all objects owned by me
            BulkResponse response = bqm.getRegistryObjects();
            Collection objects = response.getCollection();

            // Display information on the objects found
            if (objects.isEmpty()) {
                System.out.println("No objects found");
            } else {
                for (Object o : objects) {
                    RegistryObject obj = (RegistryObject) o;
                    System.out.println("Object key id: " + getKey(obj));
                    System.out.println("Object name is: " + getName(obj));
                    System.out.println("Object description is: " + getDescription(obj));

                    // Print spacer between objects
                    System.out.println(" --- ");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // At end, close connection to registry
            if (connection != null) {
                try {
                    connection.close();
                } catch (JAXRException je) {
                }
            }
        }
    }

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

private void setAuthenticator(String username, String password) {
    if (username == null || username.isEmpty()) {
        return;//ww  w. jav a2s  .c o m
    }
    String actualPassword;
    if (password == null) {
        actualPassword = "";
    } else {
        actualPassword = password;
    }
    Authenticator.setDefault(new Authenticator() {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, actualPassword.toCharArray());
        }
    });
}

From source file:sce.ElasticJob.java

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

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

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

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

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

private HttpURLConnection createConnection(final String location) throws IOException {

    URL url = new URL(location);
    HttpURLConnection conn;/*from w  w  w .  ja  v a 2s  .  c  om*/

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