com.docmd.behavior.GitManager.java Source code

Java tutorial

Introduction

Here is the source code for com.docmd.behavior.GitManager.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.docmd.behavior;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.JTextArea;
import org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.ListBranchCommand.ListMode;
import org.eclipse.jgit.api.Status;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.FetchResult;
import org.eclipse.jgit.transport.RemoteSession;
import org.eclipse.jgit.transport.SshSessionFactory;
import org.eclipse.jgit.transport.URIish;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.eclipse.jgit.util.FS;

/**
 *
 * @author gabri
 */
public class GitManager {
    private final static String INFO_REFS_PATH = "info/refs";
    public static final String SYSTEM = System.getProperty("os.name");
    private Repository repository;
    private Git git;
    private String username, password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isValidRemoteRepository(URIish repoUri) {
        boolean result;

        if (repoUri.getScheme().toLowerCase().startsWith("http")) {
            String path = repoUri.getPath();
            String newPath = path.endsWith("/") ? path + INFO_REFS_PATH : path + "/" + INFO_REFS_PATH;
            URIish checkUri = repoUri.setPath(newPath);
            InputStream ins = null;
            try {
                URLConnection conn = new URL(checkUri.toString()).openConnection();
                //conn.setReadTimeout(5000);
                ins = conn.getInputStream();
                result = true;
            } catch (Exception e) {
                if (e.getMessage().contains("403"))
                    result = true;
                else
                    result = false;
            } finally {
                try {
                    ins.close();
                } catch (Exception e) {
                    /* ignore */ }
            }
        } else {
            if (repoUri.getScheme().toLowerCase().startsWith("ssh")) {
                RemoteSession ssh = null;
                Process exec = null;
                try {
                    ssh = SshSessionFactory.getInstance().getSession(repoUri, null, FS.detect(), 5000);
                    exec = ssh.exec("cd " + repoUri.getPath() + "; git rev-parse --git-dir", 5000);
                    Integer exitValue = null;
                    do {
                        try {
                            exitValue = exec.exitValue();
                        } catch (Exception e) {
                            try {
                                Thread.sleep(1000);
                            } catch (Exception ee) {
                            }
                        }
                    } while (exitValue == null);
                    result = exitValue == 0;
                } catch (Exception e) {
                    result = false;
                } finally {
                    try {
                        exec.destroy();
                    } catch (Exception e) {
                        /* ignore */ }
                    try {
                        ssh.disconnect();
                    } catch (Exception e) {
                        /* ignore */ }
                }
            } else {
                result = true;
            }
        }
        return result;
    }

    public boolean gitClone(String path, String remoteURL, JTextArea console)
            throws IOException, GitAPIException, URISyntaxException {
        //validate remoteURL
        URIish repositoryAdress = new URIish(remoteURL);
        if (!isValidRemoteRepository(repositoryAdress))
            return false;

        //prepare a new folder for the cloned repository
        File localPath = new File("");
        String repositoryName = "";

        StringTokenizer st = new StringTokenizer(remoteURL, "/");
        while (st.hasMoreTokens()) {
            repositoryName = st.nextToken();
        }
        repositoryName = repositoryName.substring(0, repositoryName.length() - 4);
        if (SYSTEM.contains("Windows"))
            localPath = new File(path + "\\" + repositoryName);
        else
            localPath = new File(path + "/" + repositoryName);

        //if the directory does not exist, create it
        if (!localPath.exists()) {
            console.setText("");
            console.append("creating directory: " + localPath.getName());
            boolean result = false;
            try {
                localPath.mkdir();
                result = true;
            } catch (SecurityException se) {
                se.printStackTrace();
            }
            if (result) {
                console.append("\nDIR created");
            }
        }

        // then clone
        console.append("\n$git clone " + remoteURL);
        console.append("\nCloning from " + remoteURL + " to " + localPath);
        try (Git result = Git.cloneRepository().setURI(remoteURL).setDirectory(localPath)
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(this.username, this.password))
                .call()) {
            console.append("\nHaving repository: " + result.getRepository().getDirectory() + " on branch master");
            this.repository = result.getRepository();
            this.git = result;
        }

        return true;
    }

    public String[] gitBranchR(JTextArea console) throws IOException, GitAPIException {
        String[] branches = new String[0];
        int i = 0;
        console.append("\n\n$git branch -r");
        try {
            List<Ref> call = this.git.branchList().call();
            call = this.git.branchList().setListMode(ListMode.ALL).call();
            branches = new String[call.size() - 1];
            for (Ref ref : call) {
                console.append("\n" + ref.getName());
                if (ref.getName().contains("origin")) {
                    StringTokenizer st = new StringTokenizer(ref.getName(), "/");
                    while (st.hasMoreTokens()) {
                        branches[i] = st.nextToken();
                    }
                    i++;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return branches;
    }

    public void gitFetch(JTextArea console) throws GitAPIException {
        console.append("\n\n$git fetch");
        FetchResult result = git.fetch().setCheckFetchedObjects(true).call();
    }

    public void gitCheckoutBranch(String branch, JTextArea console) throws GitAPIException {
        boolean branchExists = false;
        String branchCheck = "";

        console.append("\n\n$git checkout " + branch);

        List<Ref> call = git.branchList().call();
        for (Ref ref : call) {
            StringTokenizer st = new StringTokenizer(ref.getName(), "/");
            while (st.hasMoreTokens()) {
                branchCheck = st.nextToken();
            }
            if (branchCheck.equals(branch)) {
                branchExists = true;
                break;
            }
        }

        if (branchExists)
            git.checkout().setName(branch).call();
        else {
            git.checkout().setCreateBranch(true).setName(branch).setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM)
                    .setStartPoint("origin/" + branch).call();
        }
    }

    public void gitPull(JTextArea console) throws GitAPIException {
        console.append("\n\n$git pull");
        console.append("\nSynchronized with remote repository.");
        git.pull().call();
    }

    public void gitPush(JTextArea console) throws GitAPIException {
        console.append("\n\n$git push");
        console.append("\nSynchronized with remote repository.");
        git.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider(this.username, this.password))
                .call();

        /* 
        To do: se der exception org.eclipse.jgit.api.errors.TransportException: not authorized
        significa que as credenciais do usurio esto incorretas, tratar no catch.
        */
    }

    public void gitAdd(String[] files, JTextArea console) throws GitAPIException {
        for (String file : files) {
            if (file.startsWith("[RMV]")) {
                console.append("\n\n$git add " + file.substring(5));
                git.rm().addFilepattern(file.substring(5)).call();
            } else {
                console.append("\n\n$git add " + file);
                git.add().addFilepattern(file).call();
            }
        }
    }

    public void gitCommit(String message, JTextArea console) throws GitAPIException {
        console.append("\n\n$git commit -m \"" + message + "\"");
        git.commit().setMessage(message).call();
    }

    public void gitReset(String[] files, JTextArea console) throws GitAPIException {
        for (String file : files) {
            console.append("\n\n$git reset HEAD " + file);
            git.reset().addPath(file).call();
        }
    }

    public void gitStatus(JTextArea console) throws GitAPIException {
        Status status = git.status().call();
        console.append("\n\n$git status");
        boolean flag = false;
        if ((!(status.getAdded().isEmpty())) || (!(status.getChanged().isEmpty()))
                || (!(status.getRemoved().isEmpty()))) {
            console.append("\n\n>>> STAGED CHANGES:");
            if (!(status.getAdded().isEmpty())) {
                console.append("\n\n> Added:");
                for (String s : status.getAdded()) {
                    console.append("\n" + s);
                    flag = true;
                }
            }
            if (!(status.getChanged().isEmpty())) {
                console.append("\n\n> Changed:");
                for (String s : status.getChanged()) {
                    console.append("\n" + s);
                    flag = true;
                }
            }
            if (!(status.getRemoved().isEmpty())) {
                console.append("\n\n> Removed:");
                for (String s : status.getRemoved()) {
                    console.append("\n" + s);
                    flag = true;
                }
            }
        }
        if (!(status.getConflicting().isEmpty())) {
            console.append("\n\n> Conflicting:");
            for (String s : status.getConflicting()) {
                console.append("\n" + s);
                flag = true;
            }
        }
        if (!(status.getIgnoredNotInIndex().isEmpty())) {
            console.append("\n\n> IgnoredNotInIndex:");
            for (String s : status.getIgnoredNotInIndex()) {
                console.append("\n" + s);
                flag = true;
            }
        }
        if ((!(status.getModified().isEmpty())) || (!(status.getMissing().isEmpty()))
                || (!(status.getUntracked().isEmpty())) || (!(status.getUntrackedFolders().isEmpty()))) {
            console.append("\n\n>>> UNSTAGED CHANGES:");
            if (!(status.getModified().isEmpty())) {
                console.append("\n\n> Modified:");
                for (String s : status.getModified()) {
                    console.append("\n" + s);
                    flag = true;
                }
            }
            if (!(status.getMissing().isEmpty())) {
                console.append("\n\n> Deleted:");
                for (String s : status.getMissing()) {
                    console.append("\n" + s);
                    flag = true;
                }
            }
            if (!(status.getUntracked().isEmpty())) {
                console.append("\n\n> Untracked:");
                for (String s : status.getUntracked()) {
                    console.append("\n" + s);
                    flag = true;
                }
            }
            if (!(status.getUntrackedFolders().isEmpty())) {
                console.append("\n\n> UntrackedFolders:");
                for (String s : status.getUntrackedFolders()) {
                    console.append("\n" + s);
                    flag = true;
                }
            }
        }
        if (!flag) {
            console.append("\nNo changes.");
        }
    }

    public String[] getChanges() throws GitAPIException {
        ArrayList<String> al = new ArrayList<String>();
        Status status = git.status().call();
        if (!(status.getModified().isEmpty())) {
            for (String s : status.getModified()) {
                al.add(s);
            }
        }
        if (!(status.getMissing().isEmpty())) {
            for (String s : status.getMissing()) {
                al.add("[RMV]" + s);
            }
        }
        if (!(status.getUntracked().isEmpty())) {
            for (String s : status.getUntracked()) {
                al.add(s);
            }
        }
        if (!(status.getUntrackedFolders().isEmpty())) {
            for (String s : status.getUntrackedFolders()) {
                al.add(s);
            }
        }
        String changes[] = new String[al.size()];
        for (int i = 0; i < changes.length; i++)
            changes[i] = al.get(i);
        return changes;
    }

    public String[] getStaged() throws GitAPIException {
        ArrayList<String> al = new ArrayList<String>();
        Status status = git.status().call();
        if (!(status.getAdded().isEmpty())) {
            for (String s : status.getAdded()) {
                al.add(s);
            }
        }
        if (!(status.getRemoved().isEmpty())) {
            for (String s : status.getRemoved()) {
                al.add(s);
            }
        }
        if (!(status.getChanged().isEmpty())) {
            for (String s : status.getChanged()) {
                al.add(s);
            }
        }
        String staged[] = new String[al.size()];
        for (int i = 0; i < staged.length; i++)
            staged[i] = al.get(i);
        return staged;
    }
}