类org.eclipse.jgit.transport.CredentialsProvider源码实例Demo

下面列出了怎么用org.eclipse.jgit.transport.CredentialsProvider的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: submarine   文件: GitUtils.java
/**
 * To execute clone command
 * @param remotePath
 * @param localPath
 * @param token
 * @param branch
 * @throws GitAPIException
 */
public void clone(String remotePath, String localPath, String token, String branch) {
  // Clone the code base command
  // Sets the token on the remote server
  CredentialsProvider credentialsProvider =
      new UsernamePasswordCredentialsProvider("PRIVATE-TOKEN", token);

  Git git = null;
  try {
    git = Git.cloneRepository().setURI(remotePath) // Set remote URI
        .setBranch(branch) // Set the branch down from clone
        .setDirectory(new File(localPath)) // Set the download path
        .setCredentialsProvider(credentialsProvider) // Set permission validation
        .call();
  } catch (GitAPIException e) {
    LOG.error(e.getMessage(), e);
  } finally {
    if (git != null) {
      git.close();
    }
  }
  LOG.info("git.tag(): {}", git.tag());
}
 
源代码2 项目: Jpom   文件: GitUtil.java
/**
 * 获取仓库远程的所有分支
 *
 * @param url                 远程url
 * @param file                仓库clone到本地的文件夹
 * @param credentialsProvider 凭证
 * @return list
 * @throws GitAPIException api
 * @throws IOException     IO
 */
private static List<String> branchList(String url, File file, CredentialsProvider credentialsProvider) throws GitAPIException, IOException {
    try (Git git = initGit(url, file, credentialsProvider)) {
        //
        List<Ref> list = git.branchList().setListMode(ListBranchCommand.ListMode.REMOTE).call();
        List<String> all = new ArrayList<>(list.size());
        list.forEach(ref -> {
            String name = ref.getName();
            if (name.startsWith(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME)) {
                all.add(name.substring((Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME).length() + 1));
            }
        });
        return all;
    } catch (TransportException t) {
        checkTransportException(t);
        throw t;
    }
}
 
源代码3 项目: singleton   文件: GitUtils.java
public static File cloneRepository(String remoteUri, String tempFolder, CredentialsProvider credentialsProvider) {

		logger.info("begin clone " + remoteUri + " to " + tempFolder);
		File file = new File(tempFolder);

		try {
			if (file.exists()) {
				deleteFolder(file);
			}
			file.mkdirs();
			Git git = Git.cloneRepository().setURI(remoteUri).setDirectory(file)
					.setCredentialsProvider(credentialsProvider).call();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
		logger.info("end clone " + remoteUri + " to " + tempFolder);

		return file;
	}
 
源代码4 项目: singleton   文件: GitUtils.java
public static File cloneRepository(String remoteUri, String tempFolder, String branch,
		CredentialsProvider credentialsProvider) {

	File file = new File(tempFolder);

	try {
		if (file.exists()) {
			deleteFolder(file);
		}
		file.mkdirs();
		Git.cloneRepository().setURI(remoteUri).setDirectory(file).setBranch(branch)
				.setCredentialsProvider(credentialsProvider).call();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		logger.error(e.getMessage(), e);
	}
	return file;
}
 
源代码5 项目: singleton   文件: GitUtils.java
public static File cloneRepository(String remoteUri, String tempFolder, CredentialsProvider credentialsProvider) {

		logger.info("begin clone " + remoteUri + " to " + tempFolder);
		File file = new File(tempFolder);

		try {
			if (file.exists()) {
				deleteFolder(file);
			}
			file.mkdirs();
			Git git = Git.cloneRepository().setURI(remoteUri).setDirectory(file)
					.setCredentialsProvider(credentialsProvider).call();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
		logger.info("end clone " + remoteUri + " to " + tempFolder);

		return file;
	}
 
源代码6 项目: singleton   文件: GitUtils.java
public static File cloneRepository(String remoteUri, String tempFolder, String branch,
		CredentialsProvider credentialsProvider) {

	File file = new File(tempFolder);

	try {
		if (file.exists()) {
			deleteFolder(file);
		}
		file.mkdirs();
		Git.cloneRepository().setURI(remoteUri).setDirectory(file).setBranch(branch)
				.setCredentialsProvider(credentialsProvider).call();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		logger.error(e.getMessage(), e);
	}
	return file;
}
 
源代码7 项目: fabric8-forge   文件: ProjectFileSystem.java
public static void cloneRepo(File projectFolder, String cloneUrl, CredentialsProvider credentialsProvider, final File sshPrivateKey, final File sshPublicKey, String remote, String tag) {
    StopWatch watch = new StopWatch();

    // clone the repo!
    boolean cloneAll = true;
    LOG.info("Cloning git repo " + cloneUrl + " into directory " + projectFolder.getAbsolutePath() + " cloneAllBranches: " + cloneAll);
    CloneCommand command = Git.cloneRepository();
    GitUtils.configureCommand(command, credentialsProvider, sshPrivateKey, sshPublicKey);
    command = command.setCredentialsProvider(credentialsProvider).
            setCloneAllBranches(cloneAll).setURI(cloneUrl).setDirectory(projectFolder).setRemote(remote);

    try {
        Git git = command.call();
        if (tag != null){
            git.checkout().setName(tag).call();
        }
    } catch (Throwable e) {
        LOG.error("Failed to command remote repo " + cloneUrl + " due: " + e.getMessage(), e);
        throw new RuntimeException("Failed to command remote repo " + cloneUrl + " due: " + e.getMessage());
    } finally {
        LOG.info("cloneRepo took " + watch.taken());
    }
}
 
源代码8 项目: contribution   文件: XdocPublisher.java
/**
 * Publish release notes.
 *
 * @throws IOException if problem with access to files appears.
 * @throws GitAPIException for problems with jgit.
 */
public void publish() throws IOException, GitAPIException {
    changeLocalRepoXdoc();
    final FileRepositoryBuilder builder = new FileRepositoryBuilder();
    final File localRepo = new File(localRepoPath);
    final Repository repo = builder.findGitDir(localRepo).readEnvironment().build();
    final Git git = new Git(repo);
    git.add()
        .addFilepattern(PATH_TO_XDOC_IN_REPO)
        .call();
    git.commit()
        .setMessage(String.format(Locale.ENGLISH, COMMIT_MESSAGE_TEMPLATE, releaseNumber))
        .call();
    if (doPush) {
        final CredentialsProvider credentialsProvider =
            new UsernamePasswordCredentialsProvider(authToken, "");
        git.push()
            .setCredentialsProvider(credentialsProvider)
            .call();
    }
}
 
源代码9 项目: molicode   文件: GitServiceImpl.java
private void pullGitRepoInLock(GitRepoVo gitRepoVo, CommonResult<String> result) throws IOException, GitAPIException {
    String filePath = SystemFileUtils.buildGitRepoDir(gitRepoVo.getGitUrl(), gitRepoVo.getBranchName());
    File repoDir = new File(filePath);

    CostWatch costWatch = CostWatch.createStarted();
    Git git = null;
    CredentialsProvider credentialsProvider = buildCredentialsProvider(gitRepoVo);
    if (repoDir.exists() && isGitDirectory(repoDir)) {
        git = Git.open(repoDir);
        LogHelper.DEFAULT.info("git repo already exist, fetch from url={}, branch={}", gitRepoVo.getGitUrl(), gitRepoVo.getBranchName());
        PullCommand pull = git.pull();
        if (credentialsProvider != null) {
            pull.setCredentialsProvider(credentialsProvider);
        }
        pull.setRemoteBranchName(gitRepoVo.getBranchName()).call();
        result.addDefaultModel("info", "仓库已存在,拉取最新内容到分支:" + gitRepoVo.getBranchName());
    } else {
        FileIoUtil.makeDir(repoDir);
        CloneCommand cloneCommand = Git.cloneRepository().setURI(gitRepoVo.getGitUrl()).setDirectory(repoDir).setBranch(gitRepoVo.getBranchName());
        if (credentialsProvider != null) {
            cloneCommand.setCredentialsProvider(credentialsProvider);
        }
        git = cloneCommand
                .call();
        LogHelper.DEFAULT.info("Cloning from " + gitRepoVo.getGitUrl() + " to " + git.getRepository());
        result.addDefaultModel("info", "仓库在本地还未存在,拉取最新内容到分支:" + gitRepoVo.getBranchName());
    }
    costWatch.stop();
    LogHelper.DEFAULT.info("拉取仓库模板,gitUrl={}, 耗时={}ms ", gitRepoVo.getGitUrl(), costWatch.getCost(TimeUnit.MILLISECONDS));
    result.addModel(MoliCodeConstant.ResultInfo.COST_TIME_KEY, costWatch.getCost(TimeUnit.SECONDS));
    result.succeed();
}
 
源代码10 项目: Jpom   文件: GitUtil.java
/**
 * 删除重新clone
 *
 * @param url                 url
 * @param file                文件
 * @param credentialsProvider 凭证
 * @return git
 * @throws GitAPIException api
 * @throws IOException     删除文件失败
 */
private static Git reClone(String url, File file, CredentialsProvider credentialsProvider) throws GitAPIException, IOException {
    if (!FileUtil.clean(file)) {
        throw new IOException("del error:" + file.getPath());
    }
    return Git.cloneRepository()
            .setURI(url)
            .setDirectory(file)
            .setCredentialsProvider(credentialsProvider)
            .call();
}
 
源代码11 项目: Jpom   文件: GitUtil.java
private static Git initGit(String url, File file, CredentialsProvider credentialsProvider) throws IOException, GitAPIException {
    Git git;
    if (FileUtil.file(file, Constants.DOT_GIT).exists()) {
        if (checkRemoteUrl(url, file)) {
            git = Git.open(file);
            //
            git.pull().setCredentialsProvider(credentialsProvider).call();
        } else {
            git = reClone(url, file, credentialsProvider);
        }
    } else {
        git = reClone(url, file, credentialsProvider);
    }
    return git;
}
 
源代码12 项目: Jpom   文件: GitUtil.java
/**
 * 拉取对应分支最新代码
 *
 * @param url                 远程url
 * @param file                仓库路径
 * @param branchName          分支名
 * @param credentialsProvider 凭证
 * @throws IOException     IO
 * @throws GitAPIException api
 */
public static void checkoutPull(String url, File file, String branchName, CredentialsProvider credentialsProvider) throws IOException, GitAPIException {
    try (Git git = initGit(url, file, credentialsProvider)) {
        // 判断本地是否存在对应分支
        List<Ref> list = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
        boolean createBranch = true;
        for (Ref ref : list) {
            String name = ref.getName();
            if (name.startsWith(Constants.R_HEADS + branchName)) {
                createBranch = false;
                break;
            }
        }
        // 切换分支
        if (!StrUtil.equals(git.getRepository().getBranch(), branchName)) {
            git.checkout().
                    setCreateBranch(createBranch).
                    setName(branchName).
                    setForceRefUpdate(true).
                    setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM).
                    call();
        }
        git.pull().setCredentialsProvider(credentialsProvider).call();
    } catch (TransportException t) {
        checkTransportException(t);
        throw t;
    }
}
 
源代码13 项目: netbeans   文件: JGitSshSessionFactory.java
@Override
public synchronized RemoteSession getSession (URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException {
    boolean agentUsed = false;
    String host = uri.getHost();
    CredentialItem.StringType identityFile = null;
    if (credentialsProvider != null) {
        identityFile = new JGitCredentialsProvider.IdentityFileItem("Identity file for " + host, false);
        if (credentialsProvider.isInteractive() && credentialsProvider.get(uri, identityFile) && identityFile.getValue() != null) {
            LOG.log(Level.FINE, "Identity file for {0}: {1}", new Object[] { host, identityFile.getValue() }); //NOI18N
            agentUsed = setupJSch(fs, host, identityFile, uri, true);
            LOG.log(Level.FINE, "Setting cert auth for {0}, agent={1}", new Object[] { host, agentUsed }); //NOI18N
        }
    }
    try {
        LOG.log(Level.FINE, "Trying to connect to {0}, agent={1}", new Object[] { host, agentUsed }); //NOI18N
        return super.getSession(uri, credentialsProvider, fs, tms);
    } catch (Exception ex) {
        // catch rather all exceptions. In case jsch-agent-proxy is broken again we should
        // at least fall back on key/pasphrase
        if (agentUsed) {
            LOG.log(ex instanceof TransportException ? Level.FINE : Level.INFO, null, ex);
            setupJSch(fs, host, identityFile, uri, false);
            LOG.log(Level.FINE, "Trying to connect to {0}, agent={1}", new Object[] { host, false }); //NOI18N
            return super.getSession(uri, credentialsProvider, fs, tms);
        } else {
            LOG.log(Level.FINE, "Connection failed: {0}", host); //NOI18N
            throw ex;
        }
    }
}
 
源代码14 项目: orion.server   文件: PushJob.java
public PushJob(String userRunningTask, CredentialsProvider credentials, Path path, String srcRef, boolean tags, boolean force) {
	super(userRunningTask, true, (GitCredentialsProvider) credentials);
	this.path = path;
	this.remote = path.segment(0);
	this.branch = GitUtils.decode(path.segment(1));
	this.srcRef = srcRef;
	this.tags = tags;
	this.force = force;
	setFinalMessage(NLS.bind("Pushing {0} done", path.segment(0)));
	setTaskExpirationTime(TimeUnit.DAYS.toMillis(7));
}
 
源代码15 项目: orion.server   文件: CloneJob.java
public CloneJob(Clone clone, String userRunningTask, CredentialsProvider credentials, String user, String cloneLocation, ProjectInfo project,
		String gitUserName, String gitUserMail, boolean initProject, boolean cloneSubmodules) {
	super(userRunningTask, true, (GitCredentialsProvider) credentials);
	this.clone = clone;
	this.user = user;
	this.project = project;
	this.gitUserName = gitUserName;
	this.gitUserMail = gitUserMail;
	this.cloneLocation = cloneLocation;
	this.initProject = initProject;
	this.cloneSubmodules = cloneSubmodules;
	setFinalMessage("Clone complete.");
	setTaskExpirationTime(TimeUnit.DAYS.toMillis(7));
}
 
源代码16 项目: orion.server   文件: FetchJob.java
public FetchJob(String userRunningTask, CredentialsProvider credentials, Path path, boolean force) {
	super(userRunningTask, true, (GitCredentialsProvider) credentials);
	// path: {remote}[/{branch}]/file/{...}
	this.path = path;
	this.remote = GitUtils.decode(path.segment(0));
	this.force = force;
	this.branch = path.segment(1).equals("file") ? null : GitUtils.decode(path.segment(1)); //$NON-NLS-1$
	builtMessages();
	setTaskExpirationTime(TimeUnit.DAYS.toMillis(7));
}
 
源代码17 项目: orion.server   文件: PullJob.java
public PullJob(String userRunningTask, CredentialsProvider credentials, Path path, boolean force) {
	super(userRunningTask, true, (GitCredentialsProvider) credentials);
	// path: file/{...}
	this.path = path;
	this.projectName = path.lastSegment();
	// this.force = force; // TODO: enable when JGit starts to support this option
	setName(NLS.bind("Pulling {0}", projectName));
	setFinalMessage(NLS.bind("Pulling {0} done", projectName));
	setTaskExpirationTime(TimeUnit.DAYS.toMillis(7));
}
 
源代码18 项目: fabric8-forge   文件: RepositoryResource.java
protected void doPull(Git git, GitContext context) throws GitAPIException {
    StopWatch watch = new StopWatch();

    LOG.info("Performing a pull in git repository " + this.gitFolder + " on remote URL: " + this.remoteRepository);
    CredentialsProvider cp = userDetails.createCredentialsProvider();
    PullCommand command = git.pull();
    configureCommand(command, userDetails);
    command.setCredentialsProvider(cp).setRebase(true).call();
    LOG.info("Took " + watch.taken() + " to complete pull in git repository " + this.gitFolder + " on remote URL: " + this.remoteRepository);
}
 
源代码19 项目: fabric8-forge   文件: ProjectFileSystem.java
public File cloneOrPullRepo(UserDetails userDetails, File projectFolder, String cloneUrl, File sshPrivateKey, File sshPublicKey) {
    File gitFolder = new File(projectFolder, ".git");
    CredentialsProvider credentialsProvider = userDetails.createCredentialsProvider();
    if (!Files.isDirectory(gitFolder) || !Files.isDirectory(projectFolder)) {
        // lets clone the git repository!
        cloneRepo(projectFolder, cloneUrl, credentialsProvider, sshPrivateKey, sshPublicKey, this.remote, this.jenkinsfileLibraryGitTag);
    } else {
        doPull(gitFolder, credentialsProvider, userDetails.getBranch(), userDetails.createPersonIdent(), userDetails);
    }
    return projectFolder;
}
 
源代码20 项目: fabric8-forge   文件: ProjectFileSystem.java
public File cloneRepoIfNotExist(UserDetails userDetails, File projectFolder, String cloneUrl) {
    File gitFolder = new File(projectFolder, ".git");
    CredentialsProvider credentialsProvider = userDetails.createCredentialsProvider();
    if (!Files.isDirectory(gitFolder) || !Files.isDirectory(projectFolder)) {
        // lets clone the git repository!
        cloneRepo(projectFolder, cloneUrl, credentialsProvider, userDetails.getSshPrivateKey(), userDetails.getSshPublicKey(), this.remote);

    }
    return projectFolder;
}
 
源代码21 项目: spring-data-dev-tools   文件: GitOperations.java
private void cherryPickCommitToBranch(ObjectId id, Project project, Branch branch) {

		doWithGit(project, git -> {

			try {
				checkout(project, branch);
			} catch (RuntimeException o_O) {

				logger.warn(project, "Couldn't check out branch %s. Skipping cherrypick of commit %s.", branch, id.getName());
				return;
			}

			logger.log(project, "git cp %s", id.getName());

			// Required as the CherryPick command has no setter for a CredentialsProvide *sigh*
			if (gpg.isGpgAvailable()) {
				CredentialsProvider.setDefault(new GpgPassphraseProvider(gpg));
			}

			CherryPickResult result = git.cherryPick().include(id).call();

			if (result.getStatus().equals(CherryPickStatus.OK)) {
				logger.log(project, "Successfully cherry-picked commit %s to branch %s.", id.getName(), branch);
			} else {
				logger.warn(project, "Cherry pick failed. aborting…");
				logger.log(project, "git reset --hard");
				git.reset().setMode(ResetType.HARD).call();
			}
		});
	}
 
protected CredentialsProvider getCredentialsProvider(final Log log) throws ValidationException {
    if (serverId != null) {
        Server server = settings.getServer(serverId);
        if (server == null) {
            log.warn(format("No server configuration in Maven settings found with id %s", serverId));
        }
        if (server.getUsername() != null && server.getPassword() != null) {
            return new UsernamePasswordCredentialsProvider(server.getUsername(), server.getPassword());
        }
    }
    return null;
}
 
源代码23 项目: aeron   文件: TutorialPublishTask.java
@TaskAction
public void publish() throws Exception
{
    final String wikiUri = getWikiUri();
    final File directory = new File(getProject().getBuildDir(), "tmp/tutorialPublish");
    // Use Personal Access Token or GITHUB_TOKEN for workflows
    final CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(apiKey, "");

    final Git git = Git.cloneRepository()
        .setURI(wikiUri)
        .setCredentialsProvider(credentialsProvider)
        .setDirectory(directory)
        .call();

    final File[] asciidocFiles = AsciidocUtil.filterAsciidocFiles(source);
    System.out.println("Publishing from: " + source);
    System.out.println("Found files: " + Arrays.stream(asciidocFiles).map(File::getName).collect(joining(", ")));

    for (final File asciidocFile : asciidocFiles)
    {
        Files.copy(
            asciidocFile.toPath(),
            new File(directory, asciidocFile.getName()).toPath(),
            StandardCopyOption.REPLACE_EXISTING);
    }

    git.add().addFilepattern(".").setUpdate(false).call();
    git.commit().setMessage("Update Docs").call();

    System.out.println("Publishing to: " + wikiUri);

    git.push().setCredentialsProvider(credentialsProvider).call();
}
 
源代码24 项目: incubator-gobblin   文件: GitMonitoringService.java
/**
 * Create an object to manage the git repository stored locally at repoDir with a repository URI of repoDir
 * @param repoUri URI of repository
 * @param repoDir Directory to hold the local copy of the repository
 * @param branchName Branch name
 * @param providerSessionFactoryEither Either {@link UsernamePasswordCredentialsProvider} or {@link SshSessionFactory}
 * @param shouldCheckpointHashes a boolean to determine whether to checkpoint commit hashes
 * @throws GitAPIException
 * @throws IOException
 */
GitRepository(String repoUri, String repoDir, String branchName, Either<CredentialsProvider, SshSessionFactory>
    providerSessionFactoryEither, boolean shouldCheckpointHashes) throws GitAPIException, IOException {
  this.repoUri = repoUri;
  this.repoDir = repoDir;
  this.branchName = branchName;
  this.providerSessionFactoryEither = providerSessionFactoryEither;
  this.shouldCheckpointHashes = shouldCheckpointHashes;

  initRepository();
}
 
源代码25 项目: incubator-gobblin   文件: GitMonitoringService.java
private TransportConfigCallback buildTransportConfigCallback() {
  if (this.providerSessionFactoryEither instanceof Either.Left) return null;

  SshSessionFactory sshSessionFactory = ((Either.Right<CredentialsProvider, SshSessionFactory>) this.providerSessionFactoryEither).getRight();
  return transport -> {
    SshTransport sshTransport = (SshTransport) transport;
    sshTransport.setSshSessionFactory(sshSessionFactory);
  };
}
 
private void configureCommand(TransportCommand<?, ?> command) {
	command.setTimeout(this.timeout);
	if (this.transportConfigCallback != null) {
		command.setTransportConfigCallback(this.transportConfigCallback);
	}
	CredentialsProvider credentialsProvider = getCredentialsProvider();
	if (credentialsProvider != null) {
		command.setCredentialsProvider(credentialsProvider);
	}
}
 
@Test
public void usernamePasswordShouldSetCredentials() throws Exception {
	Git mockGit = mock(Git.class);
	MockCloneCommand mockCloneCommand = new MockCloneCommand(mockGit);

	JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(
			this.environment, new JGitEnvironmentProperties());
	envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand));
	envRepository.setUri("git+ssh://[email protected]/somegitrepo");
	envRepository.setBasedir(new File("./mybasedir"));
	final String username = "someuser";
	final String password = "mypassword";
	envRepository.setUsername(username);
	envRepository.setPassword(password);
	envRepository.setCloneOnStart(true);
	envRepository.afterPropertiesSet();

	assertTrue(mockCloneCommand
			.getCredentialsProvider() instanceof UsernamePasswordCredentialsProvider);

	CredentialsProvider provider = mockCloneCommand.getCredentialsProvider();
	CredentialItem.Username usernameCredential = new CredentialItem.Username();
	CredentialItem.Password passwordCredential = new CredentialItem.Password();
	assertThat(provider.supports(usernameCredential)).isTrue();
	assertThat(provider.supports(passwordCredential)).isTrue();

	provider.get(new URIish(), usernameCredential);
	assertThat(username).isEqualTo(usernameCredential.getValue());
	provider.get(new URIish(), passwordCredential);
	assertThat(password).isEqualTo(String.valueOf(passwordCredential.getValue()));
}
 
@Test
public void passphraseShouldSetCredentials() throws Exception {
	final String passphrase = "mypassphrase";
	Git mockGit = mock(Git.class);
	MockCloneCommand mockCloneCommand = new MockCloneCommand(mockGit);

	JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(
			this.environment, new JGitEnvironmentProperties());
	envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand));
	envRepository.setUri("git+ssh://[email protected]/somegitrepo");
	envRepository.setBasedir(new File("./mybasedir"));
	envRepository.setPassphrase(passphrase);
	envRepository.setCloneOnStart(true);
	envRepository.afterPropertiesSet();

	assertThat(mockCloneCommand.hasPassphraseCredentialsProvider()).isTrue();

	CredentialsProvider provider = mockCloneCommand.getCredentialsProvider();
	assertThat(provider.isInteractive()).isFalse();

	CredentialItem.StringType stringCredential = new CredentialItem.StringType(
			PassphraseCredentialsProvider.PROMPT, true);

	assertThat(provider.supports(stringCredential)).isTrue();
	provider.get(new URIish(), stringCredential);
	assertThat(passphrase).isEqualTo(stringCredential.getValue());
}
 
@Test
public void gitCredentialsProviderFactoryCreatesPassphraseProvider()
		throws Exception {
	final String passphrase = "mypassphrase";
	final String gitUri = "git+ssh://[email protected]/somegitrepo";
	Git mockGit = mock(Git.class);
	MockCloneCommand mockCloneCommand = new MockCloneCommand(mockGit);

	JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(
			this.environment, new JGitEnvironmentProperties());
	envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand));
	envRepository.setUri(gitUri);
	envRepository.setBasedir(new File("./mybasedir"));
	envRepository.setPassphrase(passphrase);
	envRepository.setCloneOnStart(true);
	envRepository.afterPropertiesSet();

	assertThat(mockCloneCommand.hasPassphraseCredentialsProvider()).isTrue();

	CredentialsProvider provider = mockCloneCommand.getCredentialsProvider();
	assertThat(provider.isInteractive()).isFalse();

	CredentialItem.StringType stringCredential = new CredentialItem.StringType(
			PassphraseCredentialsProvider.PROMPT, true);

	assertThat(provider.supports(stringCredential)).isTrue();
	provider.get(new URIish(), stringCredential);
	assertThat(passphrase).isEqualTo(stringCredential.getValue());

}
 
@Test
public void gitCredentialsProviderFactoryCreatesUsernamePasswordProvider()
		throws Exception {
	Git mockGit = mock(Git.class);
	MockCloneCommand mockCloneCommand = new MockCloneCommand(mockGit);
	final String username = "someuser";
	final String password = "mypassword";

	JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(
			this.environment, new JGitEnvironmentProperties());
	envRepository.setGitFactory(new MockGitFactory(mockGit, mockCloneCommand));
	envRepository.setUri("git+ssh://[email protected]/somegitrepo");
	envRepository.setBasedir(new File("./mybasedir"));
	envRepository.setUsername(username);
	envRepository.setPassword(password);
	envRepository.setCloneOnStart(true);
	envRepository.afterPropertiesSet();

	assertTrue(mockCloneCommand
			.getCredentialsProvider() instanceof UsernamePasswordCredentialsProvider);

	CredentialsProvider provider = mockCloneCommand.getCredentialsProvider();
	CredentialItem.Username usernameCredential = new CredentialItem.Username();
	CredentialItem.Password passwordCredential = new CredentialItem.Password();
	assertThat(provider.supports(usernameCredential)).isTrue();
	assertThat(provider.supports(passwordCredential)).isTrue();

	provider.get(new URIish(), usernameCredential);
	assertThat(username).isEqualTo(usernameCredential.getValue());
	provider.get(new URIish(), passwordCredential);
	assertThat(password).isEqualTo(String.valueOf(passwordCredential.getValue()));
}