Example usage for org.eclipse.jgit.lib Constants R_REMOTES

List of usage examples for org.eclipse.jgit.lib Constants R_REMOTES

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Constants R_REMOTES.

Prototype

String R_REMOTES

To view the source code for org.eclipse.jgit.lib Constants R_REMOTES.

Click Source Link

Document

Prefix for remotes refs

Usage

From source file:org.eclipse.orion.server.git.servlets.FetchJob.java

License:Open Source License

private IStatus doFetch()
        throws IOException, CoreException, JGitInternalException, InvalidRemoteException, URISyntaxException {
    Repository db = getRepository();// www.  j  a v  a2s .c om
    String branch = getRemoteBranch();

    Git git = new Git(db);
    FetchCommand fc = git.fetch();

    RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
    credentials.setUri(remoteConfig.getURIs().get(0));

    fc.setCredentialsProvider(credentials);
    fc.setRemote(remote);
    if (branch != null) {
        // refs/heads/{branch}:refs/remotes/{remote}/{branch}
        RefSpec spec = new RefSpec(
                Constants.R_HEADS + branch + ":" + Constants.R_REMOTES + remote + "/" + branch); //$NON-NLS-1$ //$NON-NLS-2$
        spec = spec.setForceUpdate(force);
        fc.setRefSpecs(spec);
    }
    FetchResult fetchResult = fc.call();

    // handle result
    for (TrackingRefUpdate updateRes : fetchResult.getTrackingRefUpdates()) {
        Result res = updateRes.getResult();
        // handle status for given ref
        switch (res) {
        case NOT_ATTEMPTED:
        case NO_CHANGE:
        case NEW:
        case FORCED:
        case FAST_FORWARD:
        case RENAMED:
            // do nothing, as these statuses are OK
            break;
        case REJECTED:
        case REJECTED_CURRENT_BRANCH:
            // show warning, as only force fetch can finish successfully 
            return new Status(IStatus.WARNING, GitActivator.PI_GIT, res.name());
        default:
            return new Status(IStatus.ERROR, GitActivator.PI_GIT, res.name());
        }
    }
    return Status.OK_STATUS;
}

From source file:org.eclipse.orion.server.git.servlets.GitRemoteHandlerV1.java

License:Open Source License

private boolean handleGet(HttpServletRequest request, HttpServletResponse response, String path)
        throws IOException, JSONException, ServletException, URISyntaxException, CoreException {
    Path p = new Path(path);
    // FIXME: what if a remote or branch is named "file"?
    if (p.segment(0).equals("file")) { //$NON-NLS-1$
        // /git/remote/file/{path}
        File gitDir = GitUtils.getGitDir(p);
        Repository db = new FileRepository(gitDir);
        Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
        JSONObject result = new JSONObject();
        JSONArray children = new JSONArray();
        URI baseLocation = getURI(request);
        for (String configName : configNames) {
            JSONObject o = new JSONObject();
            o.put(ProtocolConstants.KEY_NAME, configName);
            o.put(ProtocolConstants.KEY_TYPE, GitConstants.KEY_REMOTE_NAME);
            o.put(GitConstants.KEY_URL, db.getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION,
                    configName, "url" /*RemoteConfig.KEY_URL*/));
            String pushUrl = null;
            if ((pushUrl = db.getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, configName,
                    "pushurl" /*RemoteConfig.KEY_PUSHURL*/)) != null)
                o.put(GitConstants.KEY_PUSH_URL, pushUrl);
            o.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_2
                    .baseToRemoteLocation(baseLocation, configName, "" /* no branch name */)); //$NON-NLS-1$
            children.put(o);//from   w w w .j a v  a 2 s.c o  m
        }
        result.put(ProtocolConstants.KEY_CHILDREN, children);
        OrionServlet.writeJSONResponse(request, response, result);
        return true;
    } else if (p.segment(1).equals("file")) { //$NON-NLS-1$
        // /git/remote/{remote}/file/{path}
        File gitDir = GitUtils.getGitDir(p.removeFirstSegments(1));
        Repository db = new FileRepository(gitDir);
        Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
        JSONObject result = new JSONObject();
        URI baseLocation = getURI(request);

        for (String configName : configNames) {
            if (configName.equals(p.segment(0))) {
                result.put(ProtocolConstants.KEY_NAME, configName);
                result.put(ProtocolConstants.KEY_TYPE, GitConstants.KEY_REMOTE_NAME);
                result.put(ProtocolConstants.KEY_LOCATION, BaseToRemoteConverter.REMOVE_FIRST_3
                        .baseToRemoteLocation(baseLocation, p.segment(0), "" /* no branch name */)); //$NON-NLS-1$

                JSONArray children = new JSONArray();
                List<Ref> refs = new ArrayList<Ref>();
                for (Entry<String, Ref> refEntry : db.getRefDatabase()
                        .getRefs(Constants.R_REMOTES + p.uptoSegment(1)).entrySet()) {
                    if (!refEntry.getValue().isSymbolic()) {
                        Ref ref = refEntry.getValue();
                        String name = ref.getName();
                        name = Repository.shortenRefName(name)
                                .substring(Constants.DEFAULT_REMOTE_NAME.length() + 1);
                        if (db.getBranch().equals(name)) {
                            refs.add(0, ref);
                        } else {
                            refs.add(ref);
                        }
                    }
                }
                for (Ref ref : refs) {
                    JSONObject o = new JSONObject();
                    String name = ref.getName();
                    o.put(ProtocolConstants.KEY_NAME, name.substring(Constants.R_REMOTES.length()));
                    o.put(ProtocolConstants.KEY_FULL_NAME, name);
                    o.put(ProtocolConstants.KEY_TYPE, GitConstants.REMOTE_TRACKING_BRANCH_TYPE);
                    o.put(ProtocolConstants.KEY_ID, ref.getObjectId().name());
                    // see bug 342602
                    // o.put(GitConstants.KEY_COMMIT, baseToCommitLocation(baseLocation, name));
                    o.put(ProtocolConstants.KEY_LOCATION,
                            BaseToRemoteConverter.REMOVE_FIRST_3.baseToRemoteLocation(baseLocation,
                                    "" /*short name is {remote}/{branch}*/, Repository.shortenRefName(name))); //$NON-NLS-1$
                    o.put(GitConstants.KEY_COMMIT, BaseToCommitConverter.getCommitLocation(baseLocation,
                            ref.getObjectId().name(), BaseToCommitConverter.REMOVE_FIRST_3));
                    o.put(GitConstants.KEY_HEAD, BaseToCommitConverter.getCommitLocation(baseLocation,
                            Constants.HEAD, BaseToCommitConverter.REMOVE_FIRST_3));
                    o.put(GitConstants.KEY_CLONE,
                            BaseToCloneConverter.getCloneLocation(baseLocation, BaseToCloneConverter.REMOTE));
                    o.put(GitConstants.KEY_BRANCH, BaseToBranchConverter.getBranchLocation(baseLocation,
                            BaseToBranchConverter.REMOTE));
                    o.put(GitConstants.KEY_INDEX,
                            BaseToIndexConverter.getIndexLocation(baseLocation, BaseToIndexConverter.REMOTE));
                    children.put(o);
                }
                result.put(ProtocolConstants.KEY_CHILDREN, children);
                OrionServlet.writeJSONResponse(request, response, result);
                return true;
            }
        }
        String msg = NLS.bind("Couldn't find remote : {0}", p.segment(0));
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
    } else if (p.segment(2).equals("file")) { //$NON-NLS-1$
        // /git/remote/{remote}/{branch}/file/{path}
        File gitDir = GitUtils.getGitDir(p.removeFirstSegments(2));
        Repository db = new FileRepository(gitDir);
        Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
        URI baseLocation = getURI(request);
        for (String configName : configNames) {
            if (configName.equals(p.segment(0))) {
                for (Entry<String, Ref> refEntry : db.getRefDatabase().getRefs(Constants.R_REMOTES)
                        .entrySet()) {
                    Ref ref = refEntry.getValue();
                    String name = ref.getName();
                    if (!ref.isSymbolic()
                            && name.equals(Constants.R_REMOTES + p.uptoSegment(2).removeTrailingSeparator())) {
                        JSONObject result = new JSONObject();
                        result.put(ProtocolConstants.KEY_NAME, name.substring(Constants.R_REMOTES.length()));
                        result.put(ProtocolConstants.KEY_FULL_NAME, name);
                        result.put(ProtocolConstants.KEY_TYPE, GitConstants.REMOTE_TRACKING_BRANCH_TYPE);
                        result.put(ProtocolConstants.KEY_ID, ref.getObjectId().name());
                        // see bug 342602
                        // result.put(GitConstants.KEY_COMMIT, baseToCommitLocation(baseLocation, name));
                        result.put(ProtocolConstants.KEY_LOCATION,
                                BaseToRemoteConverter.REMOVE_FIRST_4.baseToRemoteLocation(baseLocation,
                                        "" /*short name is {remote}/{branch}*/, //$NON-NLS-1$
                                        Repository.shortenRefName(name)));
                        result.put(GitConstants.KEY_COMMIT, BaseToCommitConverter.getCommitLocation(
                                baseLocation, ref.getObjectId().name(), BaseToCommitConverter.REMOVE_FIRST_4));
                        result.put(GitConstants.KEY_HEAD, BaseToCommitConverter.getCommitLocation(baseLocation,
                                Constants.HEAD, BaseToCommitConverter.REMOVE_FIRST_4));
                        result.put(GitConstants.KEY_CLONE, BaseToCloneConverter.getCloneLocation(baseLocation,
                                BaseToCloneConverter.REMOTE_BRANCH));
                        OrionServlet.writeJSONResponse(request, response, result);
                        return true;
                    }
                }
            }
        }
        JSONObject errorData = new JSONObject();
        errorData.put(GitConstants.KEY_CLONE,
                BaseToCloneConverter.getCloneLocation(baseLocation, BaseToCloneConverter.REMOTE_BRANCH));

        return statusHandler
                .handleRequest(request, response,
                        new ServerStatus(
                                new Status(IStatus.ERROR, ServerConstants.PI_SERVER_CORE,
                                        "No remote branch found: "
                                                + p.uptoSegment(2).removeTrailingSeparator()),
                                HttpServletResponse.SC_NOT_FOUND, errorData));
    }
    return statusHandler.handleRequest(request, response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
                    "Bad request, \"/git/remote/{remote}/{branch}/file/{path}\" expected", null));
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitFetchTest.java

License:Open Source License

@Test
public void testPushCommitAndFetch() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());

    // clone1//  www.ja va2  s . c  o  m
    JSONObject project1 = createProjectOrLink(workspaceLocation, getMethodName() + "1", null);
    IPath clonePath1 = new Path("file").append(project1.getString(ProtocolConstants.KEY_ID)).makeAbsolute();
    String contentLocation1 = clone(clonePath1).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

    // get project1 metadata
    WebRequest request = getGetFilesRequest(project1.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project1 = new JSONObject(response.getText());
    JSONObject gitSection1 = project1.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection1);
    String gitRemoteUri1 = gitSection1.getString(GitConstants.KEY_REMOTE);

    // clone2
    JSONObject project2 = createProjectOrLink(workspaceLocation, getMethodName() + "2", null);
    String projectId2 = project2.getString(ProtocolConstants.KEY_ID);
    IPath clonePath2 = new Path("file").append(project2.getString(ProtocolConstants.KEY_ID)).makeAbsolute();
    clone(clonePath2);

    // get project2 metadata
    request = getGetFilesRequest(project2.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project2 = new JSONObject(response.getText());
    JSONObject gitSection2 = project2.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection2);
    String gitRemoteUri2 = gitSection2.getString(GitConstants.KEY_REMOTE);
    String gitIndexUri2 = gitSection2.getString(GitConstants.KEY_INDEX);
    String gitHeadUri2 = gitSection2.getString(GitConstants.KEY_HEAD);

    // clone2: change
    request = getPutFileRequest(projectId2 + "/test.txt", "incoming change");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone2: add
    request = GitAddTest.getPutGitIndexRequest(gitIndexUri2);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone2: commit
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri2, "incoming change commit", false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone2: push
    ServerStatus pushStatus = push(gitRemoteUri2, 1, 0, Constants.MASTER, Constants.HEAD, false);
    assertEquals(true, pushStatus.isOK());

    JSONObject masterDetails = getRemoteBranch(gitRemoteUri1, 1, 0, Constants.MASTER);
    String refId1 = masterDetails.getString(ProtocolConstants.KEY_ID);
    String remoteBranchLocation = masterDetails.getString(ProtocolConstants.KEY_LOCATION);

    // clone1: fetch
    fetch(remoteBranchLocation);

    masterDetails = getRemoteBranch(gitRemoteUri1, 1, 0, Constants.MASTER);
    String newRefId1 = masterDetails.getString(ProtocolConstants.KEY_ID);
    assertFalse(newRefId1.equals(refId1));

    // clone1: log master..origin/master
    // TODO replace with tests methods from GitLogTest, bug 340051
    Repository db1 = getRepositoryForContentLocation(contentLocation1);
    ObjectId master = db1.resolve(Constants.MASTER);
    ObjectId originMaster = db1
            .resolve(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + '/' + Constants.MASTER);
    Git git = new Git(db1);
    Iterable<RevCommit> commits = git.log().addRange(master, originMaster).call();
    int c = 0;
    for (RevCommit commit : commits) {
        assertEquals("incoming change commit", commit.getFullMessage());
        c++;
    }
    // a single incoming commit
    assertEquals(1, c);
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitFetchTest.java

License:Open Source License

@Test
public void testPushAndFetchWithPrivateKeyAndPassphrase() throws Exception {

    Assume.assumeTrue(sshRepo2 != null);
    Assume.assumeTrue(knownHosts2 != null);
    Assume.assumeTrue(privateKey != null);
    Assume.assumeTrue(passphrase != null);

    URI workspaceLocation = createWorkspace(getMethodName());
    URIish uri = new URIish(sshRepo2);

    // clone1: create
    JSONObject project1 = createProjectOrLink(workspaceLocation, getMethodName() + "1", null);
    IPath clonePath = new Path("file").append(project1.getString(ProtocolConstants.KEY_ID)).makeAbsolute();
    WebRequest request = new PostGitCloneRequest().setURIish(uri).setFilePath(clonePath)
            .setKnownHosts(knownHosts2).setPrivateKey(privateKey).setPublicKey(publicKey)
            .setPassphrase(passphrase).getWebRequest();
    String cloneContentLocation1 = clone(request);

    // clone1: get project/folder metadata
    request = getGetFilesRequest(cloneContentLocation1);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project1 = new JSONObject(response.getText());

    // clone1: get git links
    JSONObject gitSection1 = project1.getJSONObject(GitConstants.KEY_GIT);
    String gitRemoteUri1 = gitSection1.getString(GitConstants.KEY_REMOTE);

    // clone2: create
    JSONObject project2 = createProjectOrLink(workspaceLocation, getMethodName() + "2", null);
    String projectId2 = project2.getString(ProtocolConstants.KEY_ID);
    clonePath = new Path("file").append(projectId2).makeAbsolute();
    request = new PostGitCloneRequest().setURIish(uri).setFilePath(clonePath).setKnownHosts(knownHosts2)
            .setPrivateKey(privateKey).setPublicKey(publicKey).setPassphrase(passphrase).getWebRequest();
    String cloneContentLocation2 = clone(request);

    // clone2: get project/folder metadata
    request = getGetFilesRequest(cloneContentLocation2);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project2 = new JSONObject(response.getText());

    // clone2: get git links
    JSONObject gitSection2 = project2.getJSONObject(GitConstants.KEY_GIT);
    String gitRemoteUri2 = gitSection2.getString(GitConstants.KEY_REMOTE);
    String gitIndexUri2 = gitSection2.getString(GitConstants.KEY_INDEX);
    String gitHeadUri2 = gitSection2.getString(GitConstants.KEY_HEAD);

    // clone2: change
    request = getPutFileRequest(projectId2 + "/test.txt", "incoming change");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone2: add
    request = GitAddTest.getPutGitIndexRequest(gitIndexUri2);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone2: commit
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri2, "incoming change commit", false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone2: push
    ServerStatus pushStatus = push(gitRemoteUri2, 1, 0, Constants.MASTER, Constants.HEAD, false, null,
            knownHosts2, privateKey, publicKey, passphrase, true);
    assertEquals(true, pushStatus.isOK());

    JSONObject details = getRemoteBranch(gitRemoteUri1, 1, 0, Constants.MASTER);
    String refId1 = details.getString(ProtocolConstants.KEY_ID);
    String remoteBranchLocation = details.getString(ProtocolConstants.KEY_LOCATION);

    // clone1: fetch
    fetch(remoteBranchLocation, null, knownHosts2, privateKey, publicKey, passphrase, true);

    details = getRemoteBranch(gitRemoteUri1, 1, 0, Constants.MASTER);
    String newRefId1 = details.getString(ProtocolConstants.KEY_ID);
    assertFalse(newRefId1.equals(refId1));

    // clone1: log master..origin/master
    // TODO replace with tests methods from GitLogTest, bug 340051
    Repository db1 = getRepositoryForContentLocation(cloneContentLocation1);
    ObjectId master = db1.resolve(Constants.MASTER);
    ObjectId originMaster = db1//  w  w w . ja  va  2s.  c  o m
            .resolve(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + '/' + Constants.MASTER);
    Git git = new Git(db1);
    Iterable<RevCommit> commits = git.log().addRange(master, originMaster).call();
    int c = 0;
    for (RevCommit commit : commits) {
        assertEquals("incoming change commit", commit.getFullMessage());
        c++;
    }
    // a single incoming commit
    assertEquals(1, c);
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitLogTest.java

License:Open Source License

@Test
public void testLogWithBranch() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    JSONObject projectTop = createProjectOrLink(workspaceLocation, getMethodName() + "-top", null);
    IPath clonePathTop = new Path("file").append(projectTop.getString(ProtocolConstants.KEY_ID)).makeAbsolute();

    JSONObject projectFolder = createProjectOrLink(workspaceLocation, getMethodName() + "-folder", null);
    IPath clonePathFolder = new Path("file").append(projectFolder.getString(ProtocolConstants.KEY_ID))
            .append("folder").makeAbsolute();

    IPath[] clonePaths = new IPath[] { clonePathTop, clonePathFolder };

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        JSONObject clone = clone(clonePath);
        String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
        String branchesLocation = clone.getString(GitConstants.KEY_BRANCH);

        // get project metadata
        WebRequest request = getGetFilesRequest(cloneContentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project = new JSONObject(response.getText());

        JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
        String gitCommitUri = gitSection.getString(GitConstants.KEY_COMMIT);

        JSONArray commitsArray = log(gitCommitUri, true);
        assertEquals(1, commitsArray.length());

        branch(branchesLocation, "branch");

        commitsArray = log(gitCommitUri, true);
        assertEquals(1, commitsArray.length());

        JSONArray branchesArray = commitsArray.getJSONObject(0).getJSONArray(GitConstants.KEY_BRANCHES);
        assertEquals(3, branchesArray.length());
        assertEquals(Constants.R_HEADS + "branch",
                branchesArray.getJSONObject(0).get(ProtocolConstants.KEY_FULL_NAME));
        assertEquals(Constants.R_HEADS + Constants.MASTER,
                branchesArray.getJSONObject(1).get(ProtocolConstants.KEY_FULL_NAME));
        assertEquals(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + Constants.MASTER,
                branchesArray.getJSONObject(2).get(ProtocolConstants.KEY_FULL_NAME));
    }/*from  w ww .ja  v  a 2 s. c  o  m*/
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitLogTest.java

License:Open Source License

@Test
public void testLogAllBranches() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    JSONObject projectTop = createProjectOrLink(workspaceLocation, getMethodName() + "-top", null);
    IPath clonePathTop = new Path("file").append(projectTop.getString(ProtocolConstants.KEY_ID)).makeAbsolute();

    JSONObject projectFolder = createProjectOrLink(workspaceLocation, getMethodName() + "-folder", null);
    IPath clonePathFolder = new Path("file").append(projectFolder.getString(ProtocolConstants.KEY_ID))
            .append("folder").makeAbsolute();

    IPath[] clonePaths = new IPath[] { clonePathTop, clonePathFolder };

    for (IPath clonePath : clonePaths) {
        // clone a repo
        JSONObject clone = clone(clonePath);
        String cloneLocation = clone.getString(ProtocolConstants.KEY_LOCATION);
        String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
        String branchesLocation = clone.getString(GitConstants.KEY_BRANCH);
        String gitCommitUri = clone.getString(GitConstants.KEY_COMMIT);

        // get project metadata
        WebRequest request = getGetFilesRequest(cloneContentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project = new JSONObject(response.getText());
        JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
        String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

        // create branch
        final String newBranchName = "branch";
        branch(branchesLocation, newBranchName);

        // modify
        String projectLocation = project.getString(ProtocolConstants.KEY_LOCATION);
        request = getPutFileRequest(projectLocation + "test.txt", "first change");
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // add/*  w ww. j  a va 2s .  c  o m*/
        request = GitAddTest.getPutGitIndexRequest(gitIndexUri + "test.txt");
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // commit1
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit1", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // checkout "branch"
        checkoutBranch(cloneLocation, newBranchName);

        // modify again
        request = getPutFileRequest(projectLocation + "test.txt", "second change");
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // add
        request = GitAddTest.getPutGitIndexRequest(gitIndexUri + "test.txt");
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // commit2
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit2", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // get standard log for HEAD - only init and commit2 should be visible
        JSONArray commitsArray = log(gitHeadUri, false);
        assertEquals(2, commitsArray.length());

        JSONObject commit = commitsArray.getJSONObject(0);
        assertEquals("commit2", commit.get(GitConstants.KEY_COMMIT_MESSAGE));

        commit = commitsArray.getJSONObject(1);
        assertEquals("Initial commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE));

        // get log for all branches - initial commit, commit1 and commit2 should be visible
        commitsArray = log(gitCommitUri, false);
        assertEquals(3, commitsArray.length());

        commit = commitsArray.getJSONObject(0);
        assertEquals("commit2", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        JSONArray branchesArray = commit.getJSONArray(GitConstants.KEY_BRANCHES);
        assertEquals(1, branchesArray.length());
        assertEquals(Constants.R_HEADS + newBranchName,
                branchesArray.getJSONObject(0).get(ProtocolConstants.KEY_FULL_NAME));

        commit = commitsArray.getJSONObject(1);
        assertEquals("commit1", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        branchesArray = commit.getJSONArray(GitConstants.KEY_BRANCHES);
        assertEquals(1, branchesArray.length());
        assertEquals(Constants.R_HEADS + Constants.MASTER,
                branchesArray.getJSONObject(0).get(ProtocolConstants.KEY_FULL_NAME));

        commit = commitsArray.getJSONObject(2);
        assertEquals("Initial commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        branchesArray = commit.getJSONArray(GitConstants.KEY_BRANCHES);
        assertEquals(1, branchesArray.length());
        assertEquals(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + Constants.MASTER,
                branchesArray.getJSONObject(0).get(ProtocolConstants.KEY_FULL_NAME));
    }
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitPushTest.java

License:Open Source License

@Test
public void testPushToDelete() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    JSONObject projectTop1 = createProjectOrLink(workspaceLocation, getMethodName() + "-top1", null);
    IPath clonePathTop1 = new Path("file").append(projectTop1.getString(ProtocolConstants.KEY_ID))
            .makeAbsolute();//from ww  w.j av a  2 s.c o  m

    JSONObject projectTop2 = createProjectOrLink(workspaceLocation, getMethodName() + "-top2", null);
    IPath clonePathTop2 = new Path("file").append(projectTop2.getString(ProtocolConstants.KEY_ID))
            .makeAbsolute();

    JSONObject projectFolder1 = createProjectOrLink(workspaceLocation, getMethodName() + "-folder1", null);
    IPath clonePathFolder1 = new Path("file").append(projectFolder1.getString(ProtocolConstants.KEY_ID))
            .append("folder1").makeAbsolute();

    JSONObject projectFolder2 = createProjectOrLink(workspaceLocation, getMethodName() + "-folder2", null);
    IPath clonePathFolder2 = new Path("file").append(projectFolder2.getString(ProtocolConstants.KEY_ID))
            .append("folder2").makeAbsolute();

    JSONObject projectTop3 = createProjectOrLink(workspaceLocation, getMethodName() + "-top3", null);
    IPath clonePathTop3 = new Path("file").append(projectTop3.getString(ProtocolConstants.KEY_ID))
            .makeAbsolute();

    JSONObject projectFolder3 = createProjectOrLink(workspaceLocation, getMethodName() + "-folder3", null);
    IPath clonePathFolder3 = new Path("file").append(projectFolder3.getString(ProtocolConstants.KEY_ID))
            .append("folder1").makeAbsolute();

    IPath[] clonePathsTop = new IPath[] { clonePathTop1, clonePathTop2 };
    IPath[] clonePathsFolder = new IPath[] { clonePathFolder1, clonePathFolder2 };
    IPath[] clonePathsMixed = new IPath[] { clonePathTop3, clonePathFolder3 };
    IPath[][] clonePaths = new IPath[][] { clonePathsTop, clonePathsFolder, clonePathsMixed };

    for (IPath[] clonePath : clonePaths) {
        // clone 1
        JSONObject clone1 = clone(clonePath[0]);
        String cloneLocation1 = clone1.getString(ProtocolConstants.KEY_LOCATION);
        String contentLocation1 = clone1.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
        String branchesLocation1 = clone1.getString(GitConstants.KEY_BRANCH);

        // clone 1 - get project1 metadata
        WebRequest request = getGetFilesRequest(contentLocation1);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project1 = new JSONObject(response.getText());
        String projectLocation1 = project1.getString(ProtocolConstants.KEY_LOCATION);
        JSONObject gitSection1 = project1.getJSONObject(GitConstants.KEY_GIT);
        String gitRemoteUri1 = gitSection1.getString(GitConstants.KEY_REMOTE);
        String gitIndexUri1 = gitSection1.getString(GitConstants.KEY_INDEX);
        String gitHeadUri1 = gitSection1.getString(GitConstants.KEY_HEAD);

        // clone 1 - create branch "a"
        response = branch(branchesLocation1, "a");
        JSONObject newBranch = new JSONObject(response.getText());
        String remoteBranchLocation1 = newBranch.getString(GitConstants.KEY_REMOTE);

        // clone 1 - checkout "a"
        final String newBranchName = "a";
        response = checkoutBranch(cloneLocation1, newBranchName);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // clone 1 - change
        request = getPutFileRequest(projectLocation1 + "/test.txt", "clone1 change");
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // clone 1 - add
        request = GitAddTest.getPutGitIndexRequest(gitIndexUri1);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // clone 1 - commit
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri1, "clone1 change commit", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // clone 1 - push "a"
        ServerStatus pushStatus = push(remoteBranchLocation1, Constants.HEAD, false);
        assertEquals(true, pushStatus.isOK());

        // clone 1 - list remote branches - expect 2
        JSONObject remote1 = getRemote(gitRemoteUri1, 1, 0, Constants.DEFAULT_REMOTE_NAME);
        String remoteLocation1 = remote1.getString(ProtocolConstants.KEY_LOCATION);

        request = GitRemoteTest.getGetGitRemoteRequest(remoteLocation1);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        remote1 = new JSONObject(response.getText());
        JSONArray refsArray = remote1.getJSONArray(ProtocolConstants.KEY_CHILDREN);
        assertEquals(2, refsArray.length());
        JSONObject ref = refsArray.getJSONObject(0);
        assertEquals(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + newBranchName,
                ref.getString(ProtocolConstants.KEY_FULL_NAME));
        ref = refsArray.getJSONObject(1);
        assertEquals(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + Constants.MASTER,
                ref.getString(ProtocolConstants.KEY_FULL_NAME));

        // clone 2 
        JSONObject clone2 = clone(clonePath[1]);
        String cloneLocation2 = clone2.getString(ProtocolConstants.KEY_LOCATION);
        String contentLocation2 = clone2.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

        // clone 2 - get project2 metadata
        request = getGetFilesRequest(contentLocation2);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project2 = new JSONObject(response.getText());
        JSONObject gitSection2 = project2.getJSONObject(GitConstants.KEY_GIT);
        String gitRemoteUri2 = gitSection2.getString(GitConstants.KEY_REMOTE);

        // clone 2 - check if the branch "a" is available
        JSONObject remote2 = getRemote(gitRemoteUri2, 1, 0, Constants.DEFAULT_REMOTE_NAME);
        String remoteLocation2 = remote2.getString(ProtocolConstants.KEY_LOCATION);

        request = GitRemoteTest.getGetGitRemoteRequest(remoteLocation2);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        remote2 = new JSONObject(response.getText());
        refsArray = remote2.getJSONArray(ProtocolConstants.KEY_CHILDREN);
        assertEquals(2, refsArray.length());
        ref = refsArray.getJSONObject(0);
        assertEquals(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + Constants.MASTER,
                ref.getString(ProtocolConstants.KEY_FULL_NAME));
        ref = refsArray.getJSONObject(1);
        assertEquals(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + newBranchName,
                ref.getString(ProtocolConstants.KEY_FULL_NAME));
        String remoteBranchLocation2 = ref.getString(ProtocolConstants.KEY_LOCATION);

        // clone 2 - checkout branch "a"
        response = checkoutBranch(cloneLocation2, newBranchName);

        // clone 1 - delete remote branch "a"
        push(remoteBranchLocation1, "", false, false);

        // clone 1 - list remote branches - expect 1
        request = GitRemoteTest.getGetGitRemoteRequest(remoteLocation1);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        remote1 = new JSONObject(response.getText());
        refsArray = remote1.getJSONArray(ProtocolConstants.KEY_CHILDREN);
        assertEquals(1, refsArray.length());
        ref = refsArray.getJSONObject(0);
        assertEquals(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + Constants.MASTER,
                ref.getString(ProtocolConstants.KEY_FULL_NAME));

        // clone 2 - fetch
        request = GitFetchTest.getPostGitRemoteRequest(remoteBranchLocation2, true, false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_ACCEPTED, response.getResponseCode());
        String taskLocation = response.getHeaderField(ProtocolConstants.HEADER_LOCATION);
        assertNotNull(taskLocation);
        String location = waitForTaskCompletion(taskLocation);

        // clone 2 - fetch task should fail
        request = getGetRequest(location);
        response = webConversation.getResponse(request);
        JSONObject status = new JSONObject(response.getText());
        assertFalse(status.getBoolean("Running"));
        assertEquals("Error", status.getJSONObject("Result").getString("Severity"));
    }
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitTest.java

License:Open Source License

protected JSONObject getRemoteBranch(String gitRemoteUri, int size, int i, String name)
        throws IOException, SAXException, JSONException {
    assertRemoteUri(gitRemoteUri);//from   ww w  .ja  v  a  2 s .  c o m
    JSONObject remote = getRemote(gitRemoteUri, 1, 0, Constants.DEFAULT_REMOTE_NAME);
    String remoteLocation = remote.getString(ProtocolConstants.KEY_LOCATION);

    WebRequest request = GitRemoteTest.getGetGitRemoteRequest(remoteLocation);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    remote = new JSONObject(response.getText());
    assertNotNull(remote);
    assertEquals(Constants.DEFAULT_REMOTE_NAME, remote.getString(ProtocolConstants.KEY_NAME));
    assertNotNull(remote.getString(ProtocolConstants.KEY_LOCATION));
    JSONArray refsArray = remote.getJSONArray(ProtocolConstants.KEY_CHILDREN);
    assertEquals(size, refsArray.length());
    JSONObject ref = refsArray.getJSONObject(i);
    assertEquals(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + name,
            ref.getString(ProtocolConstants.KEY_FULL_NAME));
    String newRefId = ref.getString(ProtocolConstants.KEY_ID);
    assertNotNull(newRefId);
    assertTrue(ObjectId.isId(newRefId));
    String remoteBranchLocation = ref.getString(ProtocolConstants.KEY_LOCATION);
    ref.getString(GitConstants.KEY_COMMIT);

    request = GitRemoteTest.getGetGitRemoteRequest(remoteBranchLocation);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject remoteBranch = new JSONObject(response.getText());
    remoteBranch.getString(GitConstants.KEY_COMMIT);
    remoteBranch.getString(GitConstants.KEY_HEAD);

    return remoteBranch;
}

From source file:org.fedoraproject.eclipse.packager.git.api.ConvertLocalToRemoteCommand.java

License:Open Source License

/**
 * Implementation of the {@code ConvertLocalToRemoteCommand}.
 *
 * @param monitor//from   w w  w .j  a  v  a 2s .c  o  m
 * @throws CommandMisconfiguredException
 *             If the command was not properly configured when it was
 *             called.
 * @throws CommandListenerException
 *             If some listener detected a problem.
 * @return The result of this command.
 * @throws LocalProjectConversionFailedException
 * @throws RemoteAlreadyExistsException
 */
@Override
public ConvertLocalResult call(IProgressMonitor monitor) throws CommandMisconfiguredException,
        CommandListenerException, LocalProjectConversionFailedException, RemoteAlreadyExistsException {

    try {
        callPreExecListeners();
    } catch (CommandListenerException e) {
        if (e.getCause() instanceof CommandMisconfiguredException) {
            // explicitly throw the specific exception
            throw (CommandMisconfiguredException) e.getCause();
        }
        throw e;
    }

    IFpProjectBits projectBits = FedoraPackagerUtils.getVcsHandler(projectRoot);

    // Find the local repository
    RepositoryCache repoCache = org.eclipse.egit.core.Activator.getDefault().getRepositoryCache();

    try {
        git = new Git(
                repoCache.lookupRepository(projectRoot.getProject().getFile(".git").getLocation().toFile())); //$NON-NLS-1$

        String uri = projectBits.getScmUrl();
        Map<String, Ref> ref = git.getRepository().getAllRefs();

        Set<String> existingRemoteList = git.getRepository().getConfig()
                .getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);

        if (existingRemoteList.size() == 0) {
            addRemote = true;
            addBranch = true;
        }

        Iterator<String> itr = existingRemoteList.iterator();
        while (itr.hasNext()) {
            String remote = itr.next();
            if (remote.equals("origin")) { //$NON-NLS-1$
                if (!checkExistingRemoteRepository(uri)) {
                    throw new RemoteAlreadyExistsException(NLS.bind(
                            FedoraPackagerGitText.ConvertLocalToRemoteCommand_existingRemoteNotficiation,
                            existingRemote));
                } else {
                    if (ref.toString().contains(Constants.R_REMOTES)) {
                        hadFetched = true;
                        addBranch = true;
                    } else {
                        addRemote = true;
                        addBranch = true;
                        hadFetched = false;
                    }
                }
            } else {
                addRemote = true;
                addBranch = true;
            }
        }

        if (addRemote) {
            addRemoteRepository(uri, monitor);
        }
        if (monitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        if (addBranch) {
            GitUtils.createLocalBranches(git, monitor);
        }
        mergeLocalRemoteBranches(monitor);
        if (monitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        // set the project property to main fedora packager's property
        projectRoot.getProject().setPersistentProperty(PackagerPlugin.PROJECT_PROP, "true"); //$NON-NLS-1$
        projectRoot.getProject().setPersistentProperty(PackagerPlugin.PROJECT_LOCAL_PROP, null);
    } catch (Exception e) {
        if (e instanceof OperationCanceledException) {
            throw ((OperationCanceledException) e);
        } else if (e instanceof RemoteAlreadyExistsException) {
            throw ((RemoteAlreadyExistsException) e);
        } else {
            throw new LocalProjectConversionFailedException(e.getMessage(), e);
        }
    }

    ConvertLocalResult result = new ConvertLocalResult(git, addRemote, addBranch, hadFetched);

    // Call post-exec listeners
    callPostExecListeners();
    result.setSuccessful(true);
    setCallable(false);
    return result;
}

From source file:org.fedoraproject.eclipse.packager.git.api.ConvertLocalToRemoteCommand.java

License:Open Source License

/**
 * Adds the corresponding remote repository as the default name 'origin' to
 * the existing local repository (uses the JGit API)
 *
 * @param uri// w  w w.  j a  va  2s .  c o  m
 * @param monitor
 * @throws LocalProjectConversionFailedException
 */
private void addRemoteRepository(String uri, IProgressMonitor monitor)
        throws LocalProjectConversionFailedException {

    try {
        RemoteConfig config = new RemoteConfig(git.getRepository().getConfig(), "origin"); //$NON-NLS-1$
        config.addURI(new URIish(uri));
        String dst = Constants.R_REMOTES + config.getName();
        RefSpec refSpec = new RefSpec();
        refSpec = refSpec.setForceUpdate(true);
        refSpec = refSpec.setSourceDestination(Constants.R_HEADS + "*", dst + "/*"); //$NON-NLS-1$ //$NON-NLS-2$

        config.addFetchRefSpec(refSpec);
        config.update(git.getRepository().getConfig());
        git.getRepository().getConfig().save();

        // fetch all the remote branches,
        // create corresponding branches locally and merge them
        FetchCommand fetch = git.fetch();
        fetch.setRemote("origin"); //$NON-NLS-1$
        fetch.setTimeout(0);
        fetch.setRefSpecs(refSpec);
        if (monitor.isCanceled()) {
            throw new OperationCanceledException();
        }
        fetch.call();

    } catch (Exception e) {
        throw new LocalProjectConversionFailedException(e.getCause().getMessage(), e);
    }
}