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

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

Introduction

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

Prototype

public static void setDefault(CredentialsProvider p) 

Source Link

Document

Set the default credentials provider.

Usage

From source file:com.google.gerrit.acceptance.git.HttpPushForReviewIT.java

License:Apache License

@Before
public void selectHttpUrl() throws Exception {
    CredentialsProvider.setDefault(new UsernamePasswordCredentialsProvider(admin.username, admin.httpPassword));
    selectProtocol(Protocol.HTTP);//from   ww  w  .j a  va 2  s .c o  m
}

From source file:org.apache.sshd.git.pack.GitPackCommandTest.java

License:Apache License

@Test
public void testGitPack() throws Exception {
    Assume.assumeFalse("On windows this activates TortoisePlink", OsUtils.isWin32());

    Path targetParent = detectTargetFolder().getParent();
    Path gitRootDir = getTempTargetRelativeFile(getClass().getSimpleName());

    try (SshServer sshd = setupTestServer()) {
        Path serverRootDir = gitRootDir.resolve("server");
        sshd.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory()));
        sshd.setCommandFactory(/*from   w w  w.j  a va2 s. c  om*/
                new GitPackCommandFactory(Utils.resolveRelativeRemotePath(targetParent, serverRootDir)));
        sshd.start();

        int port = sshd.getPort();
        try {
            Path serverDir = serverRootDir.resolve("test.git");
            Utils.deleteRecursive(serverDir);
            Git.init().setBare(true).setDirectory(serverDir.toFile()).call();

            JSch.setConfig("StrictHostKeyChecking", "no");
            CredentialsProvider.setDefault(
                    new UsernamePasswordCredentialsProvider(getCurrentTestName(), getCurrentTestName()));
            SshSessionFactory.setInstance(new GitSshdSessionFactory());

            Path localRootDir = gitRootDir.resolve("local");
            Path localDir = localRootDir.resolve(serverDir.getFileName());
            Utils.deleteRecursive(localDir);
            Git.cloneRepository().setURI("ssh://" + getCurrentTestName() + "@" + TEST_LOCALHOST + ":" + port
                    + "/" + serverDir.getFileName()).setDirectory(localDir.toFile()).call();

            Git git = Git.open(localDir.toFile());
            git.commit().setMessage("First Commit").setCommitter(getCurrentTestName(), "sshd@apache.org")
                    .call();
            git.push().call();

            Path readmeFile = Files.createFile(localDir.resolve("readme.txt"));
            git.add().addFilepattern(readmeFile.getFileName().toString()).call();
            git.commit().setMessage(getCurrentTestName()).setCommitter(getCurrentTestName(), "sshd@apache.org")
                    .call();
            git.push().call();

            git.pull().setRebase(true).call();
        } finally {
            sshd.stop();
        }
    }
}

From source file:org.eclipse.egit.ui.Activator.java

License:Open Source License

private void setupCredentialsProvider() {
    CredentialsProvider.setDefault(new EGitCredentialsProvider());
}

From source file:org.jboss.as.server.controller.git.GitRepository.java

License:Apache License

public GitRepository(GitRepositoryConfiguration gitConfig)
        throws IllegalArgumentException, IOException, ConfigXMLParseException, GeneralSecurityException {
    this.basePath = gitConfig.getBasePath();
    this.branch = gitConfig.getBranch();
    this.ignored = gitConfig.getIgnored();
    this.defaultRemoteRepository = gitConfig.getRepository();
    File baseDir = basePath.toFile();
    File gitDir = new File(baseDir, DOT_GIT);
    if (gitConfig.getAuthenticationConfig() != null) {
        CredentialsProvider
                .setDefault(new ElytronClientCredentialsProvider(gitConfig.getAuthenticationConfig()));
    }/*  www.j a v a 2s .  c o  m*/
    if (gitDir.exists()) {
        try {
            repository = new FileRepositoryBuilder().setWorkTree(baseDir).setGitDir(gitDir).setup().build();
        } catch (IOException ex) {
            throw ServerLogger.ROOT_LOGGER.failedToPullRepository(ex, gitConfig.getRepository());
        }
        try (Git git = Git.wrap(repository)) {
            git.clean();
            if (!isLocalGitRepository(gitConfig.getRepository())) {
                String remote = getRemoteName(gitConfig.getRepository());
                checkoutToSelectedBranch(git);
                PullResult result = git.pull().setRemote(remote).setRemoteBranchName(branch)
                        .setStrategy(MergeStrategy.RESOLVE).call();
                if (!result.isSuccessful()) {
                    throw ServerLogger.ROOT_LOGGER.failedToPullRepository(null, gitConfig.getRepository());
                }
            } else {
                if (!this.branch.equals(repository.getBranch())) {
                    CheckoutCommand checkout = git.checkout().setName(branch);
                    checkout.call();
                    if (checkout.getResult().getStatus() == CheckoutResult.Status.ERROR) {
                        throw ServerLogger.ROOT_LOGGER.failedToPullRepository(null, gitConfig.getRepository());
                    }
                }
            }
        } catch (GitAPIException ex) {
            throw ServerLogger.ROOT_LOGGER.failedToPullRepository(ex, gitConfig.getRepository());
        }
    } else {
        if (isLocalGitRepository(gitConfig.getRepository())) {
            try (Git git = Git.init().setDirectory(baseDir).call()) {
                final AddCommand addCommand = git.add();
                addCommand.addFilepattern("data/content/");
                Path configurationDir = basePath.resolve("configuration");
                try (Stream<Path> files = Files.list(configurationDir)) {
                    files.filter(configFile -> !"logging.properties".equals(configFile.getFileName().toString())
                            && Files.isRegularFile(configFile))
                            .forEach(configFile -> addCommand.addFilepattern(getPattern(configFile)));
                }
                addCommand.call();
                createGitIgnore(git, basePath);
                git.commit().setMessage(ServerLogger.ROOT_LOGGER.repositoryInitialized()).call();
            } catch (GitAPIException | IOException ex) {
                throw ServerLogger.ROOT_LOGGER.failedToInitRepository(ex, gitConfig.getRepository());
            }
        } else {
            clearExistingFiles(basePath, gitConfig.getRepository());
            try (Git git = Git.init().setDirectory(baseDir).call()) {
                String remoteName = UUID.randomUUID().toString();
                StoredConfig config = git.getRepository().getConfig();
                config.setString("remote", remoteName, "url", gitConfig.getRepository());
                config.setString("remote", remoteName, "fetch",
                        "+" + R_HEADS + "*:" + R_REMOTES + remoteName + "/*");
                config.save();
                git.clean();
                git.pull().setRemote(remoteName).setRemoteBranchName(branch).setStrategy(MergeStrategy.RESOLVE)
                        .call();
                checkoutToSelectedBranch(git);
                if (createGitIgnore(git, basePath)) {
                    git.commit().setMessage(ServerLogger.ROOT_LOGGER.addingIgnored()).call();
                }
            } catch (GitAPIException ex) {
                throw ServerLogger.ROOT_LOGGER.failedToInitRepository(ex, gitConfig.getRepository());
            }
        }
        repository = new FileRepositoryBuilder().setWorkTree(baseDir).setGitDir(gitDir).setup().build();
    }
    ServerLogger.ROOT_LOGGER.usingGit();
}

From source file:org.omegat.core.team.GITRemoteRepository.java

License:Open Source License

public GITRemoteRepository(File localDirectory) throws Exception {

    try {//from  ww  w . j  a v  a 2 s . co  m
        //workaround for: file c:\project\omegat\project_save.tmx is not contained in C:\project\.
        //The git repo uses the canonical path for some actions, and if c: != C: then an error is raised.
        //if we make it canonical already here, then we don't have that problem.
        localDirectory = localDirectory.getCanonicalFile();
    } catch (Exception e) {
    }

    this.localDirectory = localDirectory;
    CredentialsProvider prevProvider = CredentialsProvider.getDefault();
    myCredentialsProvider = new MyCredentialsProvider(this);
    if (prevProvider instanceof MyCredentialsProvider) {
        myCredentialsProvider.setCredentials(((MyCredentialsProvider) prevProvider).credentials);
    }
    CredentialsProvider.setDefault(myCredentialsProvider);
    File localRepositoryDirectory = getLocalRepositoryRoot(localDirectory);
    if (localRepositoryDirectory != null) {
        repository = Git.open(localRepositoryDirectory).getRepository();
    }
}

From source file:org.omegat.core.team.GITRemoteRepository.java

License:Open Source License

/**
 * Determines whether or not the supplied URL represents a valid Git repository.
 * /*from   w w  w .  j  a va  2 s  . com*/
 * <p>Does the equivalent of <code>git ls-remote <i>url</i></code>.
 * 
 * @param url URL of supposed remote repository
 * @return true if repository appears to be valid, false otherwise
 */
public static boolean isGitRepository(String url, Credentials credentials) throws AuthenticationException {
    // Heuristics to save some waiting time
    if (url.startsWith("svn://") || url.startsWith("svn+")) {
        return false;
    }
    try {
        if (credentials != null) {
            MyCredentialsProvider provider = new MyCredentialsProvider(null);
            provider.setCredentials(credentials);
            CredentialsProvider.setDefault(provider);
        }
        Collection<Ref> result = new LsRemoteCommand(null).setRemote(url).call();
        return !result.isEmpty();
    } catch (TransportException ex) {
        String message = ex.getMessage();
        if (message.endsWith("not authorized") || message.endsWith("Auth fail")
                || message.contains("Too many authentication failures")
                || message.contains("Authentication is required")) {
            throw new AuthenticationException(ex);
        }
        return false;
    } catch (GitAPIException ex) {
        throw new AuthenticationException(ex);
    } catch (JGitInternalException ex) {
        // Happens if the URL is a Subversion URL like svn://...
        return false;
    }
}

From source file:org.uberfire.java.nio.fs.jgit.JGitFileSystemImplProviderSSHTest.java

License:Apache License

@Test
public void testSSHPostReceiveHook() throws IOException {
    FileSystemHooks.FileSystemHook hook = spy(new FileSystemHooks.FileSystemHook() {
        @Override//from  www  .j  a va 2 s  .  c  o  m
        public void execute(FileSystemHookExecutionContext context) {
            assertEquals("repo", context.getFsName());
        }
    });

    Assume.assumeFalse("UF-511", System.getProperty("java.vendor").equals("IBM Corporation"));
    //Setup Authorization/Authentication
    provider.setJAASAuthenticator(new AuthenticationService() {
        private User user;

        @Override
        public User login(String s, String s1) {
            user = new UserImpl(s);
            return user;
        }

        @Override
        public boolean isLoggedIn() {
            return user != null;
        }

        @Override
        public void logout() {
            user = null;
        }

        @Override
        public User getUser() {
            return user;
        }
    });
    provider.setAuthorizer((fs, fileSystemUser) -> true);

    CredentialsProvider.setDefault(new UsernamePasswordCredentialsProvider("admin", ""));
    assertEquals("10001", provider.getGitSSHService().getProperties().get(SshServer.IDLE_TIMEOUT));

    //Setup origin
    final URI originRepo = URI.create("git://repo");
    final JGitFileSystem origin = (JGitFileSystem) provider.newFileSystem(originRepo,
            new HashMap<String, Object>() {
                {
                    put(FileSystemHooks.ExternalUpdate.name(), hook);
                }
            });

    //Write a file to origin that we won't amend in the clone
    new Commit(origin.getGit(), "master", "user1", "user1@example.com", "commitx", null, null, false,
            new HashMap<String, File>() {
                {
                    put("file-name.txt", tempFile("temp1"));
                }
            }).execute();

    //Setup clone
    JGitFileSystem clone;
    clone = (JGitFileSystem) provider.newFileSystem(URI.create("git://repo-clone"),
            new HashMap<String, Object>() {
                {
                    put("init", "true");
                    put("origin", "ssh://admin@localhost:" + gitSSHPort + "/repo");
                }
            });

    assertNotNull(clone);

    //Push clone back to origin
    provider.getFileSystem(URI.create("git://repo-clone?push=ssh://admin@localhost:" + gitSSHPort + "/repo"));

    ArgumentCaptor<FileSystemHookExecutionContext> captor = ArgumentCaptor
            .forClass(FileSystemHookExecutionContext.class);

    verify(hook).execute(captor.capture());

    Assertions.assertThat(captor.getValue()).isNotNull().hasFieldOrPropertyWithValue("fsName", "repo");
}

From source file:org.uberfire.java.nio.fs.jgit.JGitFileSystemProvider.java

License:Apache License

public JGitFileSystemProvider() {
    loadConfig();/*from  w  ww. j av  a2  s. com*/
    CredentialsProvider.setDefault(new UsernamePasswordCredentialsProvider("guest", ""));

    if (DAEMON_ENABLED) {
        fullHostNames.put("git", DAEMON_HOST_NAME + ":" + DAEMON_PORT);
    }
    if (SSH_ENABLED) {
        fullHostNames.put("ssh", SSH_HOST_NAME + ":" + SSH_PORT);
    }

    final String[] repos = FILE_REPOSITORIES_ROOT.list(new FilenameFilter() {
        @Override
        public boolean accept(final File dir, String name) {
            return name.endsWith(DOT_GIT_EXT);
        }
    });
    if (repos != null) {
        for (final String repo : repos) {
            final File repoDir = new File(FILE_REPOSITORIES_ROOT, repo);
            if (repoDir.isDirectory()) {
                final String name = repoDir.getName().substring(0, repoDir.getName().indexOf(DOT_GIT_EXT));
                final JGitFileSystem fs = new JGitFileSystem(this, fullHostNames, newRepository(repoDir, true),
                        name, ALL, buildCredential(null));
                fileSystems.put(name, fs);
                repoIndex.put(fs.gitRepo().getRepository(), fs);
            }
        }
    }
    if (DAEMON_ENABLED) {
        buildAndStartDaemon();
    } else {
        daemonService = null;
    }

    if (SSH_ENABLED) {
        buildAndStartSSH();
    } else {
        gitSSHService = null;
    }
}

From source file:org.uberfire.java.nio.fs.jgit.JGitFileSystemProviderSSHTest.java

License:Apache License

@Test
public void testSSHPostReceiveHook() throws IOException {
    //Setup Authorization/Authentication
    provider.setAuthenticator(new FileSystemAuthenticator() {
        @Override/*  ww w  . ja v a 2 s .c  o  m*/
        public FileSystemUser authenticate(final String username, final String password) {
            return new FileSystemUser() {
                @Override
                public String getName() {
                    return "admin";
                }
            };
        }
    });
    provider.setAuthorizer(new FileSystemAuthorizer() {
        @Override
        public boolean authorize(final FileSystem fs, final FileSystemUser fileSystemUser) {
            return true;
        }
    });

    CredentialsProvider.setDefault(new UsernamePasswordCredentialsProvider("admin", ""));
    assertEquals("10001", provider.getGitSSHService().getProperties().get(SshServer.IDLE_TIMEOUT));

    //Setup origin
    final URI originRepo = URI.create("git://repo");
    final JGitFileSystem origin = (JGitFileSystem) provider.newFileSystem(originRepo,
            new HashMap<String, Object>() {
                {
                    put("listMode", "ALL");
                }
            });

    //Write a file to origin that we won't amend in the clone
    commit(origin.gitRepo(), "master", "user1", "user1@example.com", "commitx", null, null, false,
            new HashMap<String, File>() {
                {
                    put("file-name.txt", tempFile("temp1"));
                }
            });

    //Setup clone
    JGitFileSystem clone;
    clone = (JGitFileSystem) provider.newFileSystem(URI.create("git://repo-clone"),
            new HashMap<String, Object>() {
                {
                    put("init", "true");
                    put("origin", "ssh://admin@localhost:" + gitSSHPort + "/repo");
                }
            });

    assertNotNull(clone);

    //Push clone back to origin
    provider.getFileSystem(URI.create("git://repo-clone?push=ssh://admin@localhost:" + gitSSHPort + "/repo"));
}