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

下面列出了怎么用org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider的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 项目: Refactoring-Bot   文件: GitService.java
/**
 * 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'!");
	}
}
 
源代码3 项目: Refactoring-Bot   文件: GitService.java
/**
 * 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();
		}
	}
}
 
源代码4 项目: mcg-helper   文件: JGitUtil.java
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;
}
 
源代码5 项目: piper   文件: JGitTemplate.java
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);
  }
}
 
源代码6 项目: EDDI   文件: RestGitBackupService.java
@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();
}
 
源代码7 项目: zeppelin   文件: OldGitHubNotebookRepo.java
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);
  }
}
 
源代码8 项目: zeppelin   文件: OldGitHubNotebookRepo.java
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);
  }
}
 
源代码9 项目: zeppelin   文件: GitHubNotebookRepo.java
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);
  }
}
 
源代码10 项目: zeppelin   文件: GitHubNotebookRepo.java
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);
  }
}
 
源代码11 项目: karamel   文件: GithubApi.java
/**
 * 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();
    }

  }
}
 
源代码12 项目: 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();
    }
}
 
源代码13 项目: coderadar   文件: CloneRepositoryAdapter.java
@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());
  }
}
 
源代码14 项目: verigreen   文件: JGitOperator.java
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);
          }
      }
 
源代码15 项目: carbon-commons   文件: GitUtilities.java
/**
 * 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);
    }
}
 
源代码17 项目: attic-stratos   文件: GitBasedArtifactRepository.java
/**
 * 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);

    }
}
 
源代码18 项目: studio   文件: StudioNodeSyncGlobalRepoTask.java
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);
}
 
源代码19 项目: proctor   文件: GitProctorCore.java
/**
 * 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);
}
 
源代码20 项目: Jpom   文件: GitUtil.java
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;
}
 
源代码21 项目: milkman   文件: JGitUtil.java
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;
}
 
源代码22 项目: tac   文件: GitRepoService.java
/**
 * 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;
}
 
源代码23 项目: mcg-helper   文件: JGitUtil.java
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;
	}
 
源代码24 项目: repairnator   文件: AbstractRepairStep.java
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();
}
 
源代码25 项目: repairnator   文件: SequencerCollector.java
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();
}
 
源代码26 项目: haven-platform   文件: ConfigsFetcherGit.java
@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();
}
 
源代码27 项目: juneau   文件: GitControl.java
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;
}
 
源代码29 项目: karamel   文件: GithubApi.java
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();
    }
  }
}
 
源代码30 项目: github-integration-plugin   文件: GHRule.java
public void pushAll() throws GitAPIException {
    git.push()
            .setPushAll()
            .setProgressMonitor(new TextProgressMonitor())
            .setCredentialsProvider(new UsernamePasswordCredentialsProvider(GH_TOKEN, ""))
            .call();
}