下面列出了怎么用org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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());
}
/**
* This method fetches data from the 'upstrem' remote.
*
* @param gitConfig
* @throws GitWorkflowException
*/
public void fetchRemote(GitConfiguration gitConfig) throws GitWorkflowException {
try (Git git = Git.open(new File(botConfig.getBotRefactoringDirectory() + gitConfig.getConfigurationId()))) {
// Fetch data
if (gitConfig.getRepoService().equals(FileHoster.github)) {
git.fetch().setRemote("upstream")
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(gitConfig.getBotToken(), ""))
.call();
} else {
git.fetch().setRemote("upstream").setCredentialsProvider(
new UsernamePasswordCredentialsProvider(gitConfig.getBotName(), gitConfig.getBotToken()))
.call();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new GitWorkflowException("Could not fetch data from 'upstream'!");
}
}
/**
* This method clones an repository with its git url.
*
* @param gitConfig
* @throws GitWorkflowException
*/
public void cloneRepository(GitConfiguration gitConfig) throws GitWorkflowException {
Git git = null;
try {
if (gitConfig.getRepoService().equals(FileHoster.github)) {
git = Git.cloneRepository().setURI(gitConfig.getForkGitLink())
.setDirectory(new File(botConfig.getBotRefactoringDirectory() + gitConfig.getConfigurationId()))
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(gitConfig.getBotToken(), ""))
.call();
} else {
git = Git.cloneRepository().setURI(gitConfig.getForkGitLink())
.setDirectory(new File(botConfig.getBotRefactoringDirectory() + gitConfig.getConfigurationId()))
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(gitConfig.getBotName(),
gitConfig.getBotToken()))
.call();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new GitWorkflowException("Faild to clone " + "'" + gitConfig.getForkGitLink() + "' successfully!");
} finally {
// Close git if possible
if (git != null) {
git.close();
}
}
}
public static boolean cloneRepository(String remoteUrl, String branch, String projectPath, String user, String pwd) throws InvalidRemoteException, TransportException, GitAPIException {
File projectDir = new File(projectPath);
UsernamePasswordCredentialsProvider provider = new UsernamePasswordCredentialsProvider(user, pwd);
try (Git git = Git.cloneRepository()
.setURI(remoteUrl)
.setBranch(branch)
.setDirectory(projectDir)
.setCredentialsProvider(provider)
.setProgressMonitor(new CloneProgressMonitor())
.call()) {
}
return true;
}
private synchronized Repository getRepository() {
try {
clear();
logger.info("Cloning {} {}", url,branch);
Git git = Git.cloneRepository()
.setURI(url)
.setBranch(branch)
.setDirectory(repositoryDir)
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password))
.call();
return (git.getRepository());
}
catch (Exception e) {
throw Throwables.propagate(e);
}
}
@Override
public Response gitInit(String botId) {
try {
deleteFileIfExists(Paths.get(tmpPath + botId));
Path gitPath = Files.createDirectories(Paths.get(tmpPath + botId));
Git git = Git.cloneRepository()
.setBranch(gitBranch)
.setURI(gitUrl)
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(gitUsername, gitPassword))
.setDirectory(gitPath.toFile())
.call();
StoredConfig config = git.getRepository().getConfig();
config.setString( CONFIG_BRANCH_SECTION, "local-branch", "remote", gitBranch);
config.setString( CONFIG_BRANCH_SECTION, "local-branch", "merge", "refs/heads/" + gitBranch );
config.save();
} catch (IOException | GitAPIException e) {
log.error(e.getLocalizedMessage(), e);
throw new InternalServerErrorException();
}
return Response.accepted().build();
}
private void pullFromRemoteStream() {
try {
LOG.debug("Pulling latest changes from remote stream");
PullCommand pullCommand = git.pull();
pullCommand.setCredentialsProvider(
new UsernamePasswordCredentialsProvider(
zeppelinConfiguration.getZeppelinNotebookGitUsername(),
zeppelinConfiguration.getZeppelinNotebookGitAccessToken()
)
);
pullCommand.call();
} catch (GitAPIException e) {
LOG.error("Error when pulling latest changes from remote repository", e);
}
}
private void pushToRemoteSteam() {
try {
LOG.debug("Pushing latest changes to remote stream");
PushCommand pushCommand = git.push();
pushCommand.setCredentialsProvider(
new UsernamePasswordCredentialsProvider(
zeppelinConfiguration.getZeppelinNotebookGitUsername(),
zeppelinConfiguration.getZeppelinNotebookGitAccessToken()
)
);
pushCommand.call();
} catch (GitAPIException e) {
LOG.error("Error when pushing latest changes to remote repository", e);
}
}
private void pullFromRemoteStream() {
try {
LOG.debug("Pulling latest changes from remote stream");
PullCommand pullCommand = git.pull();
pullCommand.setCredentialsProvider(
new UsernamePasswordCredentialsProvider(
zeppelinConfiguration.getZeppelinNotebookGitUsername(),
zeppelinConfiguration.getZeppelinNotebookGitAccessToken()
)
);
pullCommand.call();
} catch (GitAPIException e) {
LOG.error("Error when pulling latest changes from remote repository", e);
}
}
private void pushToRemoteSteam() {
try {
LOG.debug("Pushing latest changes to remote stream");
PushCommand pushCommand = git.push();
pushCommand.setCredentialsProvider(
new UsernamePasswordCredentialsProvider(
zeppelinConfiguration.getZeppelinNotebookGitUsername(),
zeppelinConfiguration.getZeppelinNotebookGitAccessToken()
)
);
pushCommand.call();
} catch (GitAPIException e) {
LOG.error("Error when pushing latest changes to remote repository", e);
}
}
/**
* Synchronizes your updates on your local repository with github.
*
* @param owner
* @param repoName
* @throws KaramelException
*/
public synchronized static void commitPush(String owner, String repoName)
throws KaramelException {
if (email == null || user == null) {
throw new KaramelException("You forgot to call registerCredentials. You must call this method first.");
}
File repoDir = getRepoDirectory(repoName);
Git git = null;
try {
git = Git.open(repoDir);
git.commit().setAuthor(user, email).setMessage("Code generated by Karamel.")
.setAll(true).call();
git.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider(user, password)).call();
} catch (IOException | GitAPIException ex) {
logger.error("error during github push", ex);
throw new KaramelException(ex.getMessage());
} finally {
if (git != null) {
git.close();
}
}
}
/**
* 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();
}
}
@Override
public void cloneRepository(CloneRepositoryCommand cloneRepositoryCommand)
throws UnableToCloneRepositoryException {
try {
// TODO: support progress monitoring
CloneCommand cloneCommand =
Git.cloneRepository()
.setURI(cloneRepositoryCommand.getRemoteUrl())
.setDirectory(new File(cloneRepositoryCommand.getLocalDir()))
.setBare(true);
if (cloneRepositoryCommand.getUsername() != null
&& cloneRepositoryCommand.getPassword() != null) {
cloneCommand.setCredentialsProvider(
new UsernamePasswordCredentialsProvider(
cloneRepositoryCommand.getUsername(), cloneRepositoryCommand.getPassword()));
}
cloneCommand.call().close();
} catch (GitAPIException e) {
throw new UnableToCloneRepositoryException(e.getMessage());
}
}
public JGitOperator(String repositoryPath, String gitUser, String gitPassword) {
try {
// need to verify repo was created successfully - this is not enough
/*if(!repositoryPath.contains("\\.git") && !repositoryPath.equals("."))
{
repositoryPath=repositoryPath.concat("\\.git");
}*/
_repo = new FileRepository(repositoryPath);
_git = new Git(_repo);
if(gitUser != null)
_cp = new UsernamePasswordCredentialsProvider(gitUser, gitPassword);
} catch (IOException e) {
throw new RuntimeException(String.format(
"Failed creating git repository for path [%s]",
repositoryPath), e);
}
}
/**
* Creates and return a UsernamePasswordCredentialsProvider instance for a tenant
*
* @param tenantId tenant Id
* @param repositoryManager RepositoryManager instance
* @return UsernamePasswordCredentialsProvider instance or null if username/password is not valid
*/
public static UsernamePasswordCredentialsProvider createCredentialsProvider (RepositoryManager repositoryManager,
int tenantId) {
RepositoryInformation repoInfo = repositoryManager.getCredentialsInformation(tenantId);
if(repoInfo == null) {
return null;
}
String userName = repoInfo.getUserName();
String password = repoInfo.getPassword();
if (userName!= null && password != null) {
return new UsernamePasswordCredentialsProvider(userName, password);
} else {
return new UsernamePasswordCredentialsProvider("", "");
}
}
/**
* Pushes the artifacts of the tenant to relevant remote repository
*
* @param gitRepoCtx TenantGitRepositoryContext instance for the tenant
*/
private void pushToRemoteRepo(TenantGitRepositoryContext gitRepoCtx) {
PushCommand pushCmd = gitRepoCtx.getGit().push();
UsernamePasswordCredentialsProvider credentialsProvider = GitUtilities.createCredentialsProvider(repositoryManager,
gitRepoCtx.getTenantId());
if (credentialsProvider == null) {
log.warn ("Remote repository credentials not available for tenant " + gitRepoCtx.getTenantId() +
", aborting push");
return;
}
pushCmd.setCredentialsProvider(credentialsProvider);
try {
pushCmd.call();
} catch (GitAPIException e) {
log.error("Pushing artifacts to remote repository failed for tenant " + gitRepoCtx.getTenantId(), e);
}
}
/**
* Pushes the artifacts of the tenant to relevant remote repository
*
* @param gitRepoCtx RepositoryContext instance for the tenant
*/
private void pushToRemoteRepo(RepositoryContext gitRepoCtx) {
PushCommand pushCmd = gitRepoCtx.getGit().push();
if (!gitRepoCtx.getKeyBasedAuthentication()) {
UsernamePasswordCredentialsProvider credentialsProvider = createCredentialsProvider(gitRepoCtx);
if (credentialsProvider != null)
pushCmd.setCredentialsProvider(credentialsProvider);
}
try {
pushCmd.call();
if (log.isDebugEnabled()) {
log.debug("Pushed artifacts for tenant : " + gitRepoCtx.getTenantId());
}
} catch (GitAPIException e) {
log.error("Pushing artifacts to remote repository failed for tenant " + gitRepoCtx.getTenantId(), e);
}
}
private <T extends TransportCommand> void configureBasicAuthentication(
ClusterMember remoteNode, T gitCommand, TextEncryptor encryptor, boolean sshProtocol) throws CryptoException {
String password = encryptor.decrypt(remoteNode.getGitPassword());
UsernamePasswordCredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(
remoteNode.getGitUsername(), password);
if (sshProtocol) {
gitCommand.setTransportConfigCallback(transport -> {
SshTransport sshTransport = (SshTransport) transport;
sshTransport.setSshSessionFactory(new StrictHostCheckingOffSshSessionFactory() {
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
super.configure(host, session);
session.setPassword(password);
}
});
});
}
gitCommand.setCredentialsProvider(credentialsProvider);
}
/**
* clones from the git URL to local workspace
* @param gitUrl remote git url from which to clone
* @param username
* @param password
* @param testDefinitionsDirectory typically matrices/test-definitions
* @param workspaceProvider where local non-bare copy will be cloned to (unless exists)
* @param pullPushTimeoutSeconds
* @param cloneTimeoutSeconds
* @param cleanInitialization
* @param branchName
*/
public GitProctorCore(final String gitUrl,
final String username,
final String password,
final String testDefinitionsDirectory,
final GitWorkspaceProvider workspaceProvider,
final int pullPushTimeoutSeconds,
final int cloneTimeoutSeconds,
final boolean cleanInitialization,
@Nullable final String branchName) {
this.gitUrl = gitUrl;
this.refName = Constants.HEAD;
this.workspaceProvider = Preconditions
.checkNotNull(workspaceProvider, "GitWorkspaceProvider should not be null");
this.username = username;
this.password = password;
user = new UsernamePasswordCredentialsProvider(username, password);
this.testDefinitionsDirectory = testDefinitionsDirectory;
gcExecutor = Executors.newSingleThreadScheduledExecutor();
this.pullPushTimeoutSeconds = pullPushTimeoutSeconds;
this.cloneTimeoutSeconds = cloneTimeoutSeconds;
this.branchName = branchName;
this.gitAPIExceptionWrapper = new GitAPIExceptionWrapper();
this.gitAPIExceptionWrapper.setGitUrl(gitUrl);
initializeRepository(cleanInitialization);
}
public static List<String> getBranchList(String url, String userName, String userPwd) throws GitAPIException, IOException {
// 生成临时路径
String tempId = SecureUtil.md5(url);
File file = ConfigBean.getInstance().getTempPath();
File gitFile = FileUtil.file(file, "gitTemp", tempId);
List<String> list = branchList(url, gitFile, new UsernamePasswordCredentialsProvider(userName, userPwd));
if (list.isEmpty()) {
throw new JpomRuntimeException("该仓库还没有任何分支");
}
return list;
}
public static<R extends TransportCommand<C, T>, C extends GitCommand<T>, T> R initWith(R cmd, GitSyncDetails sync){
if (sync.isSsh()) {
cmd.setTransportConfigCallback(new SshTransportConfigCallback(sync.getUsername(), sync.getPasswordOrToken()));
if (StringUtils.isNotBlank(sync.getPasswordOrToken())) {
cmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(sync.getUsername(), sync.getPasswordOrToken()));
}
} else {
cmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(sync.getUsername(), sync.getPasswordOrToken()));
}
return cmd;
}
/**
* clone 代码仓库
*
* @param groupName
* @param projectName
* @param branch
*/
private String cloneRepo(String groupName, String projectName, String branch, String gitURL) {
String remoteURL = gitURL;
String localPath = getLocalPath(groupName, projectName, branch);
CloneCommand cloneCommand = Git.cloneRepository().setURI(remoteURL).setBranch(branch).setDirectory(
new File(localPath)).setTimeout(30);
Git git = null;
cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(tacGitlabProperties.getUserName(),
tacGitlabProperties.getPassword()));
try {
git = cloneCommand.call();
// 取分支
String existBranch = git.getRepository().getBranch();
if (!StringUtils.equals(branch, existBranch)) {
throw new IllegalStateException(String.format("branch %s not exist", branch));
}
} catch (Exception e) {
log.error("[Git Refresh Source] clone repository error . remote:{} {}", remoteURL, e.getMessage(), e);
throw new IllegalStateException("clone repository error ." + e.getMessage());
}
return localPath;
}
public static boolean pull(String projectPath, String branch, String user, String pwd) throws IOException, WrongRepositoryStateException, InvalidConfigurationException, InvalidRemoteException, CanceledException, RefNotFoundException, RefNotAdvertisedException, NoHeadException, TransportException, GitAPIException {
try (Git git = Git.open(new File(projectPath)) ) {
UsernamePasswordCredentialsProvider provider = new UsernamePasswordCredentialsProvider(user, pwd);
git.pull().setRemoteBranchName(branch)
.setCredentialsProvider(provider)
.setProgressMonitor(new PullProgressMonitor())
.call();
}
return true;
}
protected void pushPatches(Git git, String forkedRepo,String branchName) throws IOException, GitAPIException, URISyntaxException {
RemoteAddCommand remoteAddCommand = git.remoteAdd();
remoteAddCommand.setUri(new URIish(forkedRepo));
remoteAddCommand.setName("fork-patch");
remoteAddCommand.call();
git.push().add(branchName).setRemote("fork-patch").setCredentialsProvider(new UsernamePasswordCredentialsProvider(RepairnatorConfig.getInstance().getGithubToken(), "")).call();
}
protected void commitAndPushDiffs() throws NoFilepatternException, GitAPIException {
diffsRepo.add().addFilepattern(".").call();
diffsRepo.commit().setMessage("diff files").call();
String OAUTH_TOKEN = System.getenv("OAUTH_TOKEN");
RefSpec spec = new RefSpec("master:master");
diffsRepo.push()
.setRemote("origin")
.setRefSpecs(spec)
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(OAUTH_TOKEN, ""))
.call();
}
@Autowired
public ConfigsFetcherGit(GitSettings gitSettings, DataLocationConfiguration location, List<Parser> parser) {
this.gitSettings = gitSettings;
this.parser = parser;
this.gitDirPath = new File(location.getLocation(), "git-container-configs").toPath();
this.cp = hasText(gitSettings.getPassword()) ? new UsernamePasswordCredentialsProvider(gitSettings.getUsername(), gitSettings.getPassword()) : null;
this.git = initGitRepo();
}
public GitControl(String localPath, String remotePath) throws IOException {
this.localPath = localPath;
this.remotePath = remotePath;
this.localRepo = new FileRepository(localPath + "/.git");
cp = new UsernamePasswordCredentialsProvider(this.name, this.password);
git = new Git(localRepo);
}
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;
}
public synchronized static void removeFile(String owner, String repoName, String fileName)
throws KaramelException {
File repoDir = getRepoDirectory(repoName);
Git git = null;
try {
git = Git.open(repoDir);
new File(repoDir + File.separator + fileName).delete();
git.add().addFilepattern(fileName).call();
git.commit().setAuthor(user, email).setMessage("File removed by Karamel.")
.setAll(true).call();
git.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider(user, password)).call();
RepoItem toRemove = null;
List<RepoItem> repos = cachedRepos.get(owner);
for (RepoItem r : repos) {
if (r.getName().compareToIgnoreCase(repoName) == 0) {
toRemove = r;
}
}
if (toRemove != null) {
repos.remove(toRemove);
}
} catch (IOException | GitAPIException ex) {
throw new KaramelException(ex.getMessage());
} finally {
if (git != null) {
git.close();
}
}
}
public void pushAll() throws GitAPIException {
git.push()
.setPushAll()
.setProgressMonitor(new TextProgressMonitor())
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(GH_TOKEN, ""))
.call();
}