Example usage for org.eclipse.jgit.transport CredentialsProvider CredentialsProvider

List of usage examples for org.eclipse.jgit.transport CredentialsProvider CredentialsProvider

Introduction

In this page you can find the example usage for org.eclipse.jgit.transport CredentialsProvider CredentialsProvider.

Prototype

CredentialsProvider

Source Link

Usage

From source file:CustomJschConfigSessionFactory.java

License:Apache License

@Override
protected void configure(OpenSshConfig.Host host, Session session) {
    CredentialsProvider provider = new CredentialsProvider() {
        @Override/*w w w  .j  av  a 2  s . co m*/
        public boolean isInteractive() {
            return false;
        }

        @Override
        public boolean supports(CredentialItem... credentialItems) {
            return true;
        }

        @Override
        public boolean get(URIish urIish, CredentialItem... credentialItems) throws UnsupportedCredentialItem {
            for (CredentialItem item : credentialItems) {
                try {
                    ((CredentialItem.StringType) item).setValue(config.getString("privateKeyPassPhrase"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return true;
        }
    };
    UserInfo userInfo = new CredentialsProviderUserInfo(session, provider);
    session.setUserInfo(userInfo);
    session.setConfig("StrictHostKeyChecking", "yes");
}

From source file:com.buildautomation.jgit.api.CloneRemoteRepositoryWithAuthentication.java

License:Apache License

public static void cloneRemoteRepositoryWithAuthentication()
        throws IOException, InvalidRemoteException, TransportException, GitAPIException {
    // this is necessary when the remote host does not have a valid certificate, ideally we would install the certificate in the JVM
    // instead of this unsecure workaround!

    // PROXY//from ww  w  . j  a  v  a  2  s  . c o m
    System.setProperty("http.proxyHost", "10.245.90.37");
    System.setProperty("http.proxyPort", "6050");

    // PROXY
    System.setProperty("https.proxyHost", "10.245.90.37");
    System.setProperty("https.proxyPort", "6050");

    CredentialsProvider allowHosts = new CredentialsProvider() {

        @Override
        public boolean supports(CredentialItem... items) {
            for (CredentialItem item : items) {
                if ((item instanceof CredentialItem.YesNoType)) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
            for (CredentialItem item : items) {
                if (item instanceof CredentialItem.YesNoType) {
                    ((CredentialItem.YesNoType) item).setValue(true);
                    return true;
                }
            }
            return false;
        }

        @Override
        public boolean isInteractive() {
            return false;
        }
    };

    // prepare a new folder for the cloned repository
    File localPath = File.createTempFile("TestGitRepository", "");
    localPath.delete();

    // then clone
    System.out.println("Cloning from " + REMOTE_URL + " to " + localPath);
    try (Git result = Git.cloneRepository().setURI(REMOTE_URL).setDirectory(localPath)
            .setCredentialsProvider(allowHosts).call()) {
        // Note: the call() returns an opened repository already which needs to be closed to avoid file handle leaks!
        System.out.println("Having repository: " + result.getRepository().getDirectory());
    }
}

From source file:com.googlesource.gerrit.plugins.github.git.GitHubRepository.java

License:Apache License

public CredentialsProvider getCredentialsProvider() {
    return new CredentialsProvider() {

        @Override/*  w w  w  .  j  a v  a 2  s  . c  o m*/
        public boolean supports(CredentialItem... items) {
            for (CredentialItem i : items) {
                if (i instanceof CredentialItem.Username) {
                    continue;
                } else if (i instanceof CredentialItem.Password) {
                    continue;
                } else {
                    return false;
                }
            }
            return true;
        }

        @Override
        public boolean isInteractive() {
            return false;
        }

        @Override
        public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
            String user = uri.getUser();
            if (user == null) {
                user = GitHubRepository.this.username;
            }
            if (user == null) {
                return false;
            }

            String passwd = GitHubRepository.this.password;
            if (passwd == null) {
                return false;
            }

            for (CredentialItem i : items) {
                if (i instanceof CredentialItem.Username) {
                    ((CredentialItem.Username) i).setValue(user);
                } else if (i instanceof CredentialItem.Password) {
                    ((CredentialItem.Password) i).setValue(passwd.toCharArray());
                } else {
                    throw new UnsupportedCredentialItem(uri, i.getPromptText());
                }
            }
            return true;
        }
    };
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

License:Apache License

void additionalAuthentication(String passPhrase) {
    final String passwordPhrase = passPhrase;
    JschConfigSessionFactory sessionFactory = new JschConfigSessionFactory() {
        @Override//  w w  w .  j av  a2s . c o m
        protected void configure(OpenSshConfig.Host hc, Session session) {
            CredentialsProvider provider = new CredentialsProvider() {
                @Override
                public boolean isInteractive() {
                    return false;
                }

                @Override
                public boolean supports(CredentialItem... items) {
                    return true;
                }

                @Override
                public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
                    for (CredentialItem item : items) {
                        if (item instanceof CredentialItem.StringType) {
                            ((CredentialItem.StringType) item).setValue(passwordPhrase);
                        }
                    }
                    return true;
                }
            };
            UserInfo userInfo = new CredentialsProviderUserInfo(session, provider);
            // Unknown host key for ssh
            java.util.Properties config = new java.util.Properties();
            config.put(STRICT_HOST_KEY_CHECKING, NO);
            session.setConfig(config);

            session.setUserInfo(userInfo);
        }
    };

    SshSessionFactory.setInstance(sessionFactory);

    /*
     * Enable clone of https url by trusting those urls
     */
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    final String https_proxy = System.getenv(HTTPS_PROXY);
    final String http_proxy = System.getenv(HTTP_PROXY);

    ProxySelector.setDefault(new ProxySelector() {
        final ProxySelector delegate = ProxySelector.getDefault();

        @Override
        public List<Proxy> select(URI uri) {
            // Filter the URIs to be proxied

            if (uri.toString().contains(HTTPS) && StringUtils.isNotEmpty(http_proxy) && http_proxy != null) {
                try {
                    URI httpsUri = new URI(https_proxy);
                    String host = httpsUri.getHost();
                    int port = httpsUri.getPort();
                    return Arrays.asList(new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(host, port)));
                } catch (URISyntaxException e) {
                    if (debugEnabled) {
                        S_LOGGER.debug("Url exception caught in https block of additionalAuthentication()");
                    }
                }
            }

            if (uri.toString().contains(HTTP) && StringUtils.isNotEmpty(http_proxy) && http_proxy != null) {
                try {
                    URI httpUri = new URI(http_proxy);
                    String host = httpUri.getHost();
                    int port = httpUri.getPort();
                    return Arrays.asList(new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(host, port)));
                } catch (URISyntaxException e) {
                    if (debugEnabled) {
                        S_LOGGER.debug("Url exception caught in http block of additionalAuthentication()");
                    }
                }
            }

            // revert to the default behaviour
            return delegate == null ? Arrays.asList(Proxy.NO_PROXY) : delegate.select(uri);
        }

        @Override
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
            if (uri == null || sa == null || ioe == null) {
                throw new IllegalArgumentException("Arguments can't be null.");
            }
        }
    });

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance(SSL);
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (GeneralSecurityException e) {
        e.getLocalizedMessage();
    }
}

From source file:edu.nju.cs.inform.jgit.porcelain.CloneRemoteRepositoryWithAuthentication.java

License:Apache License

public static void main(String[] args)
        throws IOException, InvalidRemoteException, TransportException, GitAPIException {
    // this is necessary when the remote host does not have a valid certificate, ideally we would install the certificate in the JVM
    // instead of this unsecure workaround!
    CredentialsProvider allowHosts = new CredentialsProvider() {

        @Override//from  w w w.j  a v  a 2s .  c o m
        public boolean supports(CredentialItem... items) {
            for (CredentialItem item : items) {
                if ((item instanceof CredentialItem.YesNoType)) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
            for (CredentialItem item : items) {
                if (item instanceof CredentialItem.YesNoType) {
                    ((CredentialItem.YesNoType) item).setValue(true);
                    return true;
                }
            }
            return false;
        }

        @Override
        public boolean isInteractive() {
            return false;
        }
    };

    // prepare a new folder for the cloned repository
    File localPath = File.createTempFile("TestGitRepository", "");
    localPath.delete();

    // then clone
    System.out.println("Cloning from " + REMOTE_URL + " to " + localPath);
    try (Git result = Git.cloneRepository().setURI(REMOTE_URL).setDirectory(localPath)
            .setCredentialsProvider(allowHosts).call()) {
        // Note: the call() returns an opened repository already which needs to be closed to avoid file handle leaks!
        System.out.println("Having repository: " + result.getRepository().getDirectory());
    }
}

From source file:ezbake.deployer.publishers.openShift.Rhc.java

License:Apache License

private CredentialsProvider generateGitCredentials() {
    return new CredentialsProvider() {
        @Override/*from   w  w w  .  ja  va  2 s  .  co  m*/
        public boolean isInteractive() {
            return false;
        }

        @Override
        public boolean supports(CredentialItem... items) {
            log.info("Supported credentials: " + Joiner.on(',').join(items));
            return true;
        }

        @Override
        public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
            log.info("Number of items: " + items.length);
            for (CredentialItem item : items) {
                log.info(item.getPromptText());
                if (item instanceof CredentialItem.StringType)
                    ((CredentialItem.StringType) item).setValue(openshiftKeyPassphrase);
                else if (item instanceof CredentialItem.YesNoType) {
                    //The authenticity of host 'hostname' can't be established.
                    // TODO: This isn't secured to always passed in true.
                    ((CredentialItem.YesNoType) item).setValue(true);
                }
            }
            return true;
        }
    };
}

From source file:fr.treeptik.cloudunit.utils.GitUtils.java

License:Open Source License

private static CredentialsProvider configCredentialsForGit(final String userNameGit, final String password) {
    CredentialsProvider credentialsProvider = new CredentialsProvider() {

        @Override/*from  ww w  .j ava2  s.co  m*/
        public boolean supports(CredentialItem... arg0) {
            return true;
        }

        @Override
        public boolean isInteractive() {
            return true;
        }

        @Override
        public boolean get(URIish arg0, CredentialItem... items) throws UnsupportedCredentialItem {
            for (CredentialItem item : items) {
                if (item instanceof CredentialItem.StringType) {
                    ((CredentialItem.StringType) item).setValue("YOUR_PASSPHRASE");
                    continue;
                }
                if (item instanceof CredentialItem.Username) {
                    ((CredentialItem.Username) item).setValue(userNameGit);
                    continue;
                }

                if (item instanceof CredentialItem.Password) {
                    ((CredentialItem.Password) item).setValue(password.toCharArray());
                    continue;
                }
                if (item instanceof CredentialItem.YesNoType) {
                    ((CredentialItem.YesNoType) item).setValue(true);
                    continue;
                }
            }
            return true;
        }
    };
    return credentialsProvider;

}

From source file:gitadapter.CloneRemoteRepositoryWithAuthentication.java

License:Apache License

public static void main(String[] args) throws IOException, GitAPIException {
    // this is necessary when the remote host does not have a valid certificate, ideally we would install the certificate in the JVM
    // instead of this unsecure workaround!
    CredentialsProvider allowHosts = new CredentialsProvider() {

        @Override//from   w  w  w  .  j a  v  a2 s .c o  m
        public boolean supports(CredentialItem... items) {
            for (CredentialItem item : items) {
                if ((item instanceof CredentialItem.YesNoType)) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
            for (CredentialItem item : items) {
                if (item instanceof CredentialItem.YesNoType) {
                    ((CredentialItem.YesNoType) item).setValue(true);
                    return true;
                }
            }
            return false;
        }

        @Override
        public boolean isInteractive() {
            return false;
        }
    };

    // prepare a new folder for the cloned repository
    File localPath = File.createTempFile("TestGitRepository", "");
    if (!localPath.delete()) {
        throw new IOException("Could not delete temporary file " + localPath);
    }

    // then clone
    System.out.println("Cloning from " + REMOTE_URL + " to " + localPath);
    try (Git result = Git.cloneRepository().setURI(REMOTE_URL).setDirectory(localPath)
            .setCredentialsProvider(allowHosts).call()) {
        // Note: the call() returns an opened repository already which needs to be closed to avoid file handle leaks!
        System.out.println("Having repository: " + result.getRepository().getDirectory());
    }
}

From source file:io.fabric8.openshift.agent.OpenShiftDeployAgent.java

License:Apache License

protected void onConfigurationChanged() {
    LOGGER.info(/*from w ww .j a v  a2s. co  m*/
            "Configuration has changed; so checking the Fabric managed Java cartridges on OpenShift are up to date");
    Container[] containers = fabricService.get().getContainers();
    for (Container container : containers) {
        Profile effectiveProfile = Profiles.getEffectiveProfile(fabricService.get(),
                container.getOverlayProfile());
        Map<String, String> openshiftConfiguration = effectiveProfile
                .getConfiguration(OpenShiftConstants.OPENSHIFT_PID);
        if (openshiftConfiguration != null) {
            DeploymentUpdater deployTask = null;
            try {
                deployTask = createDeployTask(container, openshiftConfiguration);
            } catch (MalformedURLException e) {
                LOGGER.error("Failed to create DeploymentUpdater. " + e, e);
            }
            if (deployTask != null && OpenShiftUtils.isFabricManaged(openshiftConfiguration)) {
                String containerId = container.getId();
                IOpenShiftConnection connection = OpenShiftUtils.createConnection(container);
                CreateOpenshiftContainerOptions options = OpenShiftUtils.getCreateOptions(container);
                if (connection == null || options == null) {
                    LOGGER.warn("Ignoring container which has no openshift connection or options. connection: "
                            + connection + " options: " + options);
                } else {
                    try {
                        IApplication application = OpenShiftUtils.getApplication(container, connection);
                        if (application != null) {
                            final String gitUrl = application.getGitUrl();
                            if (gitUrl != null) {
                                LOGGER.info("Git URL is " + gitUrl);

                                final CartridgeGitRepository repo = new CartridgeGitRepository(containerId);

                                final List<IOpenShiftSSHKey> sshkeys = application.getDomain().getUser()
                                        .getSSHKeys();

                                final CredentialsProvider credentials = new CredentialsProvider() {
                                    @Override
                                    public boolean supports(CredentialItem... items) {
                                        return true;
                                    }

                                    @Override
                                    public boolean isInteractive() {
                                        return true;
                                    }

                                    @Override
                                    public boolean get(URIish uri, CredentialItem... items)
                                            throws UnsupportedCredentialItem {

                                        LOGGER.info(
                                                "Credential request " + uri + " items " + Arrays.asList(items));
                                        int i = -1;
                                        for (CredentialItem item : items) {
                                            if (item instanceof CredentialItem.StringType) {
                                                CredentialItem.StringType stringType = (CredentialItem.StringType) item;

                                                int idx = ++i < sshkeys.size() ? i : 0;
                                                if (idx < sshkeys.size()) {
                                                    IOpenShiftSSHKey sshKey = sshkeys.get(idx);
                                                    String passphrase = sshKey.getPublicKey();
                                                    LOGGER.info("For item " + item + " index " + i
                                                            + " using passphrase: " + passphrase);
                                                    stringType.setValue(passphrase);
                                                } else {
                                                    LOGGER.warn("No ssh keys we can pass into git!");
                                                }
                                                continue;
                                            } else {
                                                LOGGER.warn("Unknown CredentialItem " + item);
                                            }
                                        }
                                        return true;
                                    }
                                };

                                final DeploymentUpdater finalDeployTask = deployTask;
                                SshSessionFactoryUtils.useOpenShiftSessionFactory(new Callable<Object>() {

                                    @Override
                                    public Object call() throws Exception {
                                        repo.cloneOrPull(gitUrl, credentials);
                                        finalDeployTask.updateDeployment(repo.getGit(), repo.getLocalRepo(),
                                                credentials);
                                        return null;
                                    }
                                });
                            }
                        }
                    } catch (Exception e) {
                        LOGGER.error("Failed to update container " + containerId + ". Reason: " + e, e);
                    } finally {
                        OpenShiftUtils.close(connection);
                    }
                }
            }
        }
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.AuthSettings.java

License:Apache License

public CredentialsProvider toCredentialsProvider() {
    return new CredentialsProvider() {
        @Override//  w  w  w. ja v  a  2 s  .  com
        public boolean isInteractive() {
            return false;
        }

        @Override
        public boolean supports(CredentialItem... items) {
            for (CredentialItem i : items) {
                if (i instanceof CredentialItem.Username && myAuthMethod != AuthenticationMethod.ANONYMOUS)
                    continue;
                if (i instanceof CredentialItem.Password && myAuthMethod == AuthenticationMethod.PASSWORD
                        && myPassword != null)
                    continue;
                return false;
            }
            return true;
        }

        @Override
        public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
            boolean allValuesSupplied = true;
            for (CredentialItem i : items) {
                if (i instanceof CredentialItem.Username) {
                    allValuesSupplied &= supplyUsername(uri, (CredentialItem.Username) i);
                } else if (i instanceof CredentialItem.Password) {
                    allValuesSupplied &= supplyPassword((CredentialItem.Password) i);
                } else if (i instanceof CredentialItem.StringType
                        && "Passphrase for ".equals(i.getPromptText())) {
                    //we provider a passphrase to the jsch, if we are asked about it
                    //then the original passphrase was incorrect
                    throw new WrongPassphraseException(uri);
                } else {
                    throw new UnsupportedCredentialItem(uri, i.getPromptText());
                }
            }
            return allValuesSupplied;
        }

        private boolean supplyUsername(URIish uri, CredentialItem.Username item) {
            if (myAuthMethod == AuthenticationMethod.ANONYMOUS)
                return false;
            String username = myUserName != null ? myUserName : uri.getUser();
            if (username == null)
                return false;
            item.setValue(username);
            return true;
        }

        private boolean supplyPassword(CredentialItem.Password item) {
            if (myAuthMethod != AuthenticationMethod.PASSWORD)
                return false;
            if (myPassword == null)
                return false;
            item.setValue(myPassword.toCharArray());
            return true;
        }
    };
}