Example usage for org.eclipse.jgit.api PushCommand call

List of usage examples for org.eclipse.jgit.api PushCommand call

Introduction

In this page you can find the example usage for org.eclipse.jgit.api PushCommand call.

Prototype

@Override
public Iterable<PushResult> call()
        throws GitAPIException, InvalidRemoteException, org.eclipse.jgit.api.errors.TransportException 

Source Link

Document

Execute the push command with all the options and parameters collected by the setter methods of this class.

Usage

From source file:com.verigreen.jgit.JGitOperator.java

License:Apache License

@Override
public boolean push(String sourceBranch, String destinationBranch) {

    PushCommand command = _git.push();
    boolean ret = true;
    RefSpec refSpec = new RefSpec().setSourceDestination(sourceBranch, destinationBranch);
    command.setRefSpecs(refSpec);/*from   w ww. ja  v  a 2 s .  c  o  m*/
    try {
        List<Ref> remoteBranches = _git.branchList().setListMode(ListMode.REMOTE).call();
        Iterable<PushResult> results = command.call();
        for (PushResult pushResult : results) {
            Collection<RemoteRefUpdate> resultsCollection = pushResult.getRemoteUpdates();
            Map<PushResult, RemoteRefUpdate> resultsMap = new HashMap<>();
            for (RemoteRefUpdate remoteRefUpdate : resultsCollection) {
                resultsMap.put(pushResult, remoteRefUpdate);
            }

            RemoteRefUpdate remoteUpdate = pushResult.getRemoteUpdate(destinationBranch);
            if (remoteUpdate != null) {
                org.eclipse.jgit.transport.RemoteRefUpdate.Status status = remoteUpdate.getStatus();
                ret = status.equals(org.eclipse.jgit.transport.RemoteRefUpdate.Status.OK)
                        || status.equals(org.eclipse.jgit.transport.RemoteRefUpdate.Status.UP_TO_DATE);
            }

            if (remoteUpdate == null && !remoteBranches.toString().contains(destinationBranch)) {

                for (RemoteRefUpdate resultValue : resultsMap.values()) {
                    if (resultValue.toString().contains("REJECTED_OTHER_REASON")) {
                        ret = false;
                    }
                }
            }
        }
    } catch (Throwable e) {
        throw new RuntimeException(
                String.format("Failed to push [%s] into [%s]", sourceBranch, destinationBranch), e);
    }

    return ret;
}

From source file:es.logongas.openshift.ant.impl.OpenShiftUtil.java

License:Apache License

public void gitPushApplication(String serverUrl, String userName, String password, String domainName,
        String applicationName, String privateKeyFile, String path) throws GitAPIException, IOException {

    SshSessionFactory.setInstance(new CustomConfigSessionFactory(privateKeyFile));

    Git git = Git.open(new File(path));

    PushCommand push = git.push();
    push.setProgressMonitor(new TextProgressMonitor());
    LOGGER.info("Finalizado push");
    LOGGER.info("Mostrando resultados");
    Iterable<PushResult> pushResults = push.call();
    for (PushResult pushResult : pushResults) {
        LOGGER.info(pushResult.getMessages());
    }//from  w  w w  .j  a v a 2s. c om

}

From source file:eu.atos.paas.git.Repository.java

License:Open Source License

public void push(String remote, CredentialsProvider credentials) throws GitAPIException {
    logger.debug("Start git push {} from {}", remote, this);
    try (Git git = buildGit()) {
        PushCommand cmd = git.push().setRemote(remote);

        if (remote.startsWith("git:")) {
            cmd.setTransportConfigCallback(getTransportConfigCallback());
            /*/*from   w  ww. j a va 2 s  . com*/
             * TODO: set pwd if needed
             */
        } else if (credentials != null) {
            cmd.setCredentialsProvider(credentials);
        }
        cmd.call();
    }
    logger.debug("End git push {}", remote);
}

From source file:facade.GitFacade.java

public static String pushRepo(Repository repository, String username, String password) throws GitAPIException {
    Git git = new Git(repository);
    CredentialsProvider provider = new UsernamePasswordCredentialsProvider(username, password);
    PushCommand pushCommand = git.push();
    pushCommand.setCredentialsProvider(provider).setForce(true).setPushAll();

    Iterable<PushResult> result = pushCommand.call();

    if (!result.iterator().next().getMessages().isEmpty())
        return result.iterator().next().getMessages();
    else/*from   ww w . ja  v  a  2  s  . c  o m*/
        return "OK";

}

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

License:Open Source License

/**
 * this method is associate with listGitTagsOfApplication() method
 * which list all tags with index, this is this index which must pass as parammeter of this method
 *
 * @param application/*  w ww. j  a  va2  s.com*/
 * @param indexChosen
 * @param dockerManagerAddress
 * @param containerGitAddress
 * @return
 * @throws InvalidRemoteException
 * @throws TransportException
 * @throws GitAPIException
 * @throws IOException
 */
public static List<String> resetOnChosenGitTag(Application application, int indexChosen,
        String dockerManagerAddress, String containerGitAddress)
        throws InvalidRemoteException, TransportException, GitAPIException, IOException {
    User user = application.getUser();
    String sshPort = application.getServers().get(0).getSshPort();
    String password = user.getPassword();
    String userNameGit = user.getLogin();
    String dockerManagerIP = dockerManagerAddress.substring(0, dockerManagerAddress.length() - 5);
    String remoteRepository = "ssh://" + userNameGit + "@" + dockerManagerIP + ":" + sshPort
            + containerGitAddress;
    File gitworkDir = Files.createTempDirectory("clone").toFile();
    CloneCommand clone = Git.cloneRepository();
    clone.setDirectory(gitworkDir);

    CredentialsProvider credentialsProvider = configCredentialsForGit(userNameGit, password);
    clone.setCredentialsProvider(credentialsProvider);
    clone.setURI(remoteRepository);
    Git git = clone.call();

    ListTagCommand listTagCommand = git.tagList();
    List<Ref> listRefs = listTagCommand.call();

    Ref ref = listRefs.get(indexChosen);

    ResetCommand resetCommand = git.reset();
    resetCommand.setMode(ResetType.HARD);
    resetCommand.setRef(ref.getName());
    resetCommand.call();

    PushCommand pushCommand = git.push();
    pushCommand.setCredentialsProvider(credentialsProvider);
    pushCommand.setForce(true);

    List<PushResult> listPushResults = (List<PushResult>) pushCommand.call();
    List<String> listPushResultsMessages = new ArrayList<>();
    for (PushResult pushResult : listPushResults) {
        listPushResultsMessages.add(pushResult.getMessages());
    }
    FilesUtils.deleteDirectory(gitworkDir);
    return listPushResultsMessages;
}

From source file:jbyoshi.gitupdate.processor.Push.java

License:Apache License

private static void process(Repository repo, Git git, String remote, Collection<String> branches, Report report)
        throws Exception {
    // Figure out if anything needs to be pushed.
    Map<String, ObjectId> oldIds = new HashMap<>();
    boolean canPush = false;
    for (String branch : branches) {
        BranchConfig config = new BranchConfig(repo.getConfig(), branch);
        ObjectId target = repo.getRef(branch).getObjectId();

        Ref remoteRef = repo.getRef(config.getRemoteTrackingBranch());
        if (remoteRef == null || !target.equals(remoteRef.getObjectId())) {
            canPush = true;/*from w  w w. j  av  a  2s. c  o m*/
        }
        oldIds.put(branch, remoteRef == null ? ObjectId.zeroId() : remoteRef.getObjectId());
    }

    if (!canPush) {
        return;
    }

    PushCommand push = git.push().setCredentialsProvider(Prompts.INSTANCE).setTimeout(5).setRemote(remote);
    for (String branch : branches) {
        push.add(Constants.R_HEADS + branch);
    }
    for (PushResult result : push.call()) {
        for (RemoteRefUpdate update : result.getRemoteUpdates()) {
            if (update.getStatus() == RemoteRefUpdate.Status.OK) {
                String branchName = Utils.getShortBranch(update.getSrcRef());
                ObjectId oldId = oldIds.get(branchName);
                String old = oldId.equals(ObjectId.zeroId()) ? "new branch" : oldId.name();
                report.newChild(branchName + ": " + old + " -> " + update.getNewObjectId().name()).modified();
            }
        }
    }
}

From source file:org.ajoberstar.gradle.git.tasks.GitPush.java

License:Apache License

/**
 * Pushes changes to a remote repository.
 *///from   w  w  w. j ava2s. c om
@TaskAction
public void push() {
    PushCommand cmd = getGit().push();
    TransportAuthUtil.configure(cmd, this);
    cmd.setRemote(getRemote());
    if (isPushTags()) {
        cmd.setPushTags();
    }
    if (isPushAll()) {
        cmd.setPushAll();
    }
    cmd.setForce(isForce());
    try {
        cmd.call();
    } catch (Exception e) {
        throw new GradleException("Problem pushing to repository.", e);
    }
    //TODO add progress monitor to go to Gradle status bar
}

From source file:org.apache.nifi.registry.provider.flow.git.GitFlowMetaData.java

License:Apache License

void startPushThread() {
    // If successfully loaded, start pushing thread if necessary.
    if (isEmpty(remoteToPush)) {
        return;/*from  w ww  .jav a 2  s  . c om*/
    }

    final ThreadFactory threadFactory = new BasicThreadFactory.Builder().daemon(true)
            .namingPattern(getClass().getSimpleName() + " Push thread").build();

    // Use scheduled fixed delay to control the minimum interval between push activities.
    // The necessity of executing push is controlled by offering messages to the pushQueue.
    // If multiple commits are made within this time window, those are pushed by a single push execution.
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(threadFactory);
    executorService.scheduleWithFixedDelay(() -> {

        final Long offeredTimestamp;
        try {
            offeredTimestamp = pushQueue.take();
        } catch (InterruptedException e) {
            logger.warn("Waiting for push request has been interrupted due to {}", e.getMessage(), e);
            return;
        }

        logger.debug("Took a push request sent at {} to {}...", offeredTimestamp, remoteToPush);
        final PushCommand pushCommand = new Git(gitRepo).push().setRemote(remoteToPush);
        if (credentialsProvider != null) {
            pushCommand.setCredentialsProvider(credentialsProvider);
        }

        try {
            final Iterable<PushResult> pushResults = pushCommand.call();
            for (PushResult pushResult : pushResults) {
                logger.debug(pushResult.getMessages());
            }
        } catch (GitAPIException e) {
            logger.error(format("Failed to push commits to %s due to %s", remoteToPush, e), e);
        }

    }, 10, 10, TimeUnit.SECONDS);
}

From source file:org.apache.stratos.cartridge.agent.artifact.deployment.synchronizer.git.impl.GitBasedArtifactRepository.java

License:Apache License

/**
 * Pushes the artifacts of the tenant to relevant remote repository
 *
 * @param gitRepoCtx RepositoryContext instance for the tenant
 *//* w  w  w .ja v  a 2s  . c  o  m*/
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);

    }
}

From source file:org.apache.stratos.manager.utils.RepositoryCreator.java

License:Apache License

private void createGitFolderStructure(String tenantDomain, String cartridgeName, String[] dirArray)
        throws Exception {

    if (log.isDebugEnabled()) {
        log.debug("Creating git repo folder structure  ");
    }/*from w ww.  j  a  v  a  2 s. c o m*/

    String parentDirName = "/tmp/" + UUID.randomUUID().toString();
    CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(
            System.getProperty(CartridgeConstants.INTERNAL_GIT_USERNAME),
            System.getProperty(CartridgeConstants.INTERNAL_GIT_PASSWORD).toCharArray());
    // Clone
    // --------------------------
    FileRepository localRepo = null;
    try {
        localRepo = new FileRepository(new File(parentDirName + "/.git"));
    } catch (IOException e) {
        log.error("Exception occurred in creating a new file repository. Reason: " + e.getMessage());
        throw e;
    }

    Git git = new Git(localRepo);

    CloneCommand cloneCmd = git.cloneRepository().setURI(System.getProperty(CartridgeConstants.INTERNAL_GIT_URL)
            + "/git/" + tenantDomain + "/" + cartridgeName + ".git").setDirectory(new File(parentDirName));

    cloneCmd.setCredentialsProvider(credentialsProvider);
    try {
        log.debug("Clonning git repo");
        cloneCmd.call();
    } catch (Exception e1) {
        log.error("Exception occurred in cloning Repo. Reason: " + e1.getMessage());
        throw e1;
    }
    // ------------------------------------

    // --- Adding directory structure --------

    File parentDir = new File(parentDirName);
    parentDir.mkdir();

    for (String string : dirArray) {
        String[] arr = string.split("=");
        if (log.isDebugEnabled()) {
            log.debug("Creating dir: " + arr[0]);
        }
        File parentFile = new File(parentDirName + "/" + arr[0]);
        parentFile.mkdirs();

        File filess = new File(parentFile, "README");
        String content = "Content goes here";

        filess.createNewFile();
        FileWriter fw = new FileWriter(filess.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();
    }
    // ----------------------------------------------------------

    // ---- Git status ---------------
    StatusCommand s = git.status();
    Status status = null;
    try {
        log.debug("Getting git repo status");
        status = s.call();
    } catch (Exception e) {
        log.error("Exception occurred in git status check. Reason: " + e.getMessage());
        throw e;
    }
    // --------------------------------

    // ---------- Git add ---------------
    AddCommand addCmd = git.add();
    Iterator<String> it = status.getUntracked().iterator();

    while (it.hasNext()) {
        addCmd.addFilepattern(it.next());
    }

    try {
        log.debug("Adding files to git repo");
        addCmd.call();
    } catch (Exception e) {
        log.error("Exception occurred in adding files. Reason: " + e.getMessage());
        throw e;
    }
    // -----------------------------------------

    // ------- Git commit -----------------------

    CommitCommand commitCmd = git.commit();
    commitCmd.setMessage("Adding directories");

    try {
        log.debug("Committing git repo");
        commitCmd.call();
    } catch (Exception e) {
        log.error("Exception occurred in committing . Reason: " + e.getMessage());
        throw e;
    }
    // --------------------------------------------

    // --------- Git push -----------------------
    PushCommand pushCmd = git.push();
    pushCmd.setCredentialsProvider(credentialsProvider);
    try {
        log.debug("Git repo push");
        pushCmd.call();
    } catch (Exception e) {
        log.error("Exception occurred in Git push . Reason: " + e.getMessage());
        throw e;
    }

    try {
        deleteDirectory(new File(parentDirName));
    } catch (Exception e) {
        log.error("Exception occurred in deleting temp files. Reason: " + e.getMessage());
        throw e;
    }

    log.info(" Folder structure  is created ..... ");

}