Example usage for org.eclipse.jgit.api Git getRepository

List of usage examples for org.eclipse.jgit.api Git getRepository

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git getRepository.

Prototype

public Repository getRepository() 

Source Link

Document

Get repository

Usage

From source file:org.commonwl.view.workflow.WorkflowService.java

License:Apache License

/**
 * Get a list of workflows from a directory
 * @param gitInfo The Git directory information
 * @return The list of workflow overviews
 *//*from  w w w.  java 2s  .com*/
public List<WorkflowOverview> getWorkflowsFromDirectory(GitDetails gitInfo)
        throws IOException, GitAPIException {
    List<WorkflowOverview> workflowsInDir = new ArrayList<>();
    try {
        boolean safeToAccess = gitSemaphore.acquire(gitInfo.getRepoUrl());
        Git repo = null;
        while (repo == null) {
            try {
                repo = gitService.getRepository(gitInfo, safeToAccess);
            } catch (RefNotFoundException ex) {
                // Attempt slashes in branch fix
                GitDetails correctedForSlash = gitService.transferPathToBranch(gitInfo);
                if (correctedForSlash != null) {
                    gitInfo = correctedForSlash;
                } else {
                    throw ex;
                }
            }
        }

        Path localPath = repo.getRepository().getWorkTree().toPath();
        Path pathToDirectory = localPath.resolve(gitInfo.getPath()).normalize().toAbsolutePath();
        Path root = Paths.get("/").toAbsolutePath();
        if (pathToDirectory.equals(root)) {
            pathToDirectory = localPath;
        } else if (!pathToDirectory.startsWith(localPath.normalize().toAbsolutePath())) {
            // Prevent path traversal attacks
            throw new WorkflowNotFoundException();
        }

        File directory = new File(pathToDirectory.toString());
        if (directory.exists() && directory.isDirectory()) {
            for (final File file : directory.listFiles()) {
                int eIndex = file.getName().lastIndexOf('.') + 1;
                if (eIndex > 0) {
                    String extension = file.getName().substring(eIndex);
                    if (extension.equals("cwl")) {
                        WorkflowOverview overview = cwlService.getWorkflowOverview(file);
                        if (overview != null) {
                            workflowsInDir.add(overview);
                        }
                    }
                }
            }
        }
    } finally {
        gitSemaphore.release(gitInfo.getRepoUrl());
    }
    return workflowsInDir;
}

From source file:org.commonwl.view.workflow.WorkflowService.java

License:Apache License

/**
 * Builds a new queued workflow from Git
 * @param gitInfo Git information for the workflow
 * @return A queued workflow model//from  w  w  w.ja  v a 2 s .  c  o m
 * @throws GitAPIException Git errors
 * @throws WorkflowNotFoundException Workflow was not found within the repository
 * @throws IOException Other file handling exceptions
 */
public QueuedWorkflow createQueuedWorkflow(GitDetails gitInfo)
        throws GitAPIException, WorkflowNotFoundException, IOException {
    QueuedWorkflow queuedWorkflow;

    try {
        boolean safeToAccess = gitSemaphore.acquire(gitInfo.getRepoUrl());
        Git repo = null;
        while (repo == null) {
            try {
                repo = gitService.getRepository(gitInfo, safeToAccess);
            } catch (RefNotFoundException ex) {
                // Attempt slashes in branch fix
                GitDetails correctedForSlash = gitService.transferPathToBranch(gitInfo);
                if (correctedForSlash != null) {
                    gitInfo = correctedForSlash;
                } else {
                    throw ex;
                }
            }
        }
        Path localPath = repo.getRepository().getWorkTree().toPath();
        String latestCommit = gitService.getCurrentCommitID(repo);

        Path workflowFile = localPath.resolve(gitInfo.getPath()).normalize().toAbsolutePath();
        // Prevent path traversal attacks
        if (!workflowFile.startsWith(localPath.normalize().toAbsolutePath())) {
            throw new WorkflowNotFoundException();
        }

        // Check workflow is readable
        if (!Files.isReadable(workflowFile)) {
            throw new WorkflowNotFoundException();
        }

        // Handling of packed workflows
        String packedWorkflowId = gitInfo.getPackedId();
        if (packedWorkflowId == null) {
            if (cwlService.isPacked(workflowFile.toFile())) {
                List<WorkflowOverview> overviews = cwlService
                        .getWorkflowOverviewsFromPacked(workflowFile.toFile());
                if (overviews.size() == 0) {
                    throw new IOException("No workflow was found within the packed CWL file");
                } else {
                    // Dummy queued workflow object to return the list
                    QueuedWorkflow overviewList = new QueuedWorkflow();
                    overviewList.setWorkflowList(overviews);
                    return overviewList;
                }
            }
        } else {
            // Packed ID specified but was not found
            if (!cwlService.isPacked(workflowFile.toFile())) {
                throw new WorkflowNotFoundException();
            }
        }

        Workflow basicModel = cwlService.parseWorkflowNative(workflowFile, packedWorkflowId);

        // Set origin details
        basicModel.setRetrievedOn(new Date());
        basicModel.setRetrievedFrom(gitInfo);
        basicModel.setLastCommit(latestCommit);

        // Save the queued workflow to database
        queuedWorkflow = new QueuedWorkflow();
        queuedWorkflow.setTempRepresentation(basicModel);
        queuedWorkflowRepository.save(queuedWorkflow);

        // ASYNC OPERATIONS
        // Parse with cwltool and update model
        try {
            cwlToolRunner.createWorkflowFromQueued(queuedWorkflow);
        } catch (Exception e) {
            logger.error("Could not update workflow with cwltool", e);
        }

    } finally {
        gitSemaphore.release(gitInfo.getRepoUrl());
    }

    // Return this model to be displayed
    return queuedWorkflow;
}

From source file:org.commonwl.view.workflow.WorkflowServiceTest.java

License:Apache License

/**
 * Getting a list of workflow overviews from a directory
 *///from   w  w  w  .  java  2 s.c om
@Test
public void getWorkflowsFromDirectory() throws Exception {

    // Mock CWL service which returns simple overview once simulating 1 workflow found
    CWLService mockCWLService = Mockito.mock(CWLService.class);
    when(mockCWLService.getWorkflowOverview(anyObject()))
            .thenReturn(new WorkflowOverview("workflow.cwl", "label", "doc"))
            .thenReturn(new WorkflowOverview("workflow2.cwl", "label2", "doc2")).thenReturn(null);

    Repository mockRepo = Mockito.mock(Repository.class);
    when(mockRepo.getWorkTree()).thenReturn(new File("src/test/resources/cwl/hello"));

    Git mockGitRepo = Mockito.mock(Git.class);
    when(mockGitRepo.getRepository()).thenReturn(mockRepo);

    GitService mockGitService = Mockito.mock(GitService.class);
    when(mockGitService.getRepository(anyObject(), anyBoolean())).thenReturn(mockGitRepo);

    // Create service under test
    WorkflowService testWorkflowService = new WorkflowService(mockGitService, mockCWLService,
            Mockito.mock(WorkflowRepository.class), Mockito.mock(QueuedWorkflowRepository.class),
            Mockito.mock(ROBundleFactory.class), Mockito.mock(GraphVizService.class),
            Mockito.mock(CWLToolRunner.class), Mockito.mock(GitSemaphore.class), 1);

    // Get a list of workflows from the directory
    List<WorkflowOverview> list = testWorkflowService
            .getWorkflowsFromDirectory(new GitDetails(null, null, "/"));

    // 1 workflow should be found
    assertTrue(list.size() == 2);
    assertEquals("workflow.cwl", list.get(0).getFileName());
    assertEquals("label", list.get(0).getLabel());
    assertEquals("doc", list.get(0).getDoc());

    assertEquals("workflow2.cwl", list.get(1).getFileName());
    assertEquals("label2", list.get(1).getLabel());
    assertEquals("doc2", list.get(1).getDoc());

}

From source file:org.commonwl.view.workflow.WorkflowServiceTest.java

License:Apache License

/**
 * Getting a workflow when cache has expired
 * And a new workflow needs to be created
 *///from   ww  w.  j  a v  a 2s  . co  m
@Test
public void getWorkflowCacheHasExpired() throws Exception {

    GitDetails githubInfo = new GitDetails("https://github.com/common-workflow-language/workflows.git",
            "master", "dna.cwl");

    Workflow oldWorkflow = new Workflow("old", "This is the expired workflow", new HashMap<>(), new HashMap<>(),
            new HashMap<>());
    oldWorkflow.setId("theworkflowid");
    oldWorkflow.setRetrievedOn(new Date());
    oldWorkflow.setRetrievedFrom(githubInfo);
    oldWorkflow.setLastCommit("d46ce365f1a10c4c4d6b0caed51c6f64b84c2f63");
    oldWorkflow.setRoBundlePath(roBundleFolder.newFile("robundle.zip").getAbsolutePath());

    Workflow updatedWorkflow = new Workflow("new", "This is the updated workflow", new HashMap<>(),
            new HashMap<>(), new HashMap<>());
    updatedWorkflow.setId("newworkflowid");

    WorkflowRepository mockWorkflowRepo = Mockito.mock(WorkflowRepository.class);
    when(mockWorkflowRepo.findByRetrievedFrom(anyObject())).thenReturn(oldWorkflow);

    CWLService mockCWLService = Mockito.mock(CWLService.class);
    when(mockCWLService.parseWorkflowNative(anyObject(), anyObject())).thenReturn(updatedWorkflow);

    Repository mockRepo = Mockito.mock(Repository.class);
    when(mockRepo.getWorkTree()).thenReturn(new File("src/test/resources/cwl/make_to_cwl"));

    Git mockGitRepo = Mockito.mock(Git.class);
    when(mockGitRepo.getRepository()).thenReturn(mockRepo);

    GitService mockGitService = Mockito.mock(GitService.class);
    when(mockGitService.getRepository(anyObject(), anyBoolean())).thenReturn(mockGitRepo);
    when(mockGitService.getCurrentCommitID(anyObject())).thenReturn("newCommitId");

    // Create service under test with negative cache time (always create new workflow)
    WorkflowService testWorkflowService = new WorkflowService(mockGitService, mockCWLService, mockWorkflowRepo,
            Mockito.mock(QueuedWorkflowRepository.class), Mockito.mock(ROBundleFactory.class),
            Mockito.mock(GraphVizService.class), Mockito.mock(CWLToolRunner.class),
            Mockito.mock(GitSemaphore.class), -1);

    // Will use check cache algorithm, find expired,
    // check git and find commit IDs do not match,
    // and thus create a new workflow + matching RO bundle
    Workflow workflow = testWorkflowService.getWorkflow(githubInfo);

    // Check the old workflow was deleted
    // TODO: check new workflow was queued
    assertEquals(workflow, null);

}

From source file:org.craftercms.commons.git.impl.GitRepositoryFactoryImpl.java

License:Open Source License

@Override
public GitRepository open(File dir) throws GitException {
    try {/*from w w w .  j  av  a 2s.c  o  m*/
        Git git = Git.open(dir);

        logger.debug("Git repository opened at {}", git.getRepository().getDirectory());

        return new GitRepositoryImpl(git);
    } catch (IOException e) {
        throw new GitException("Error opening Git repository at " + dir, e);
    }
}

From source file:org.craftercms.commons.git.impl.GitRepositoryFactoryImpl.java

License:Open Source License

@Override
public GitRepository init(File dir, boolean bare) throws GitException {
    try {//from   w ww. j  av a  2 s .  com
        Git git = Git.init().setDirectory(dir).setBare(bare).call();

        logger.info("New Git repository created at {}", git.getRepository().getDirectory());

        return new GitRepositoryImpl(git);
    } catch (GitAPIException e) {
        throw new GitException("Error creating new Git repository in " + dir, e);
    }
}

From source file:org.craftercms.commons.git.impl.GitRepositoryFactoryImplTest.java

License:Open Source License

@Test
public void testOpen() throws Exception {
    Git git = Git.init().setDirectory(tmpDir.getRoot()).call();

    GitRepository repo = repositoryFactory.open(tmpDir.getRoot());

    assertNotNull(repo);//from  w  ww  .j a va2s  .c  om
    assertEquals(git.getRepository().getDirectory().getCanonicalPath(), repo.getDirectory().getCanonicalPath());
}

From source file:org.craftercms.commons.git.impl.GitRepositoryImplTest.java

License:Open Source License

@Test
public void testPush() throws Exception {
    File masterRepoDir = tmpDir.newFolder("master.git");
    File cloneRepoDir = tmpDir.newFolder("clone");

    Git masterGit = Git.init().setDirectory(masterRepoDir).setBare(true).call();
    Git cloneGit = Git.cloneRepository().setURI(masterRepoDir.getCanonicalPath()).setDirectory(cloneRepoDir)
            .call();//from  ww w .  ja  va 2s . co  m
    GitRepositoryImpl cloneRepo = new GitRepositoryImpl(cloneGit);

    File testFile = new File(cloneRepoDir, "test");
    testFile.createNewFile();

    cloneGit.add().addFilepattern("test").call();
    cloneGit.commit().setMessage("Test message").call();

    cloneRepo.push();

    List<RevCommit> commits = IterableUtils.toList(masterGit.log().all().call());

    assertNotNull(commits);
    assertEquals(1, commits.size());
    assertEquals("Test message", commits.get(0).getFullMessage());

    List<String> committedFiles = getCommittedFiles(masterGit.getRepository(), commits.get(0));

    assertNotNull(committedFiles);
    assertEquals(1, committedFiles.size());
    assertEquals("test", committedFiles.get(0));
}

From source file:org.craftercms.commons.git.impl.GitRepositoryImplTest.java

License:Open Source License

@Test
public void testPull() throws Exception {
    File masterRepoDir = tmpDir.newFolder("master");
    File cloneRepoDir = tmpDir.newFolder("clone");

    Git masterGit = Git.init().setDirectory(masterRepoDir).call();
    Git cloneGit = Git.cloneRepository().setURI(masterRepoDir.getCanonicalPath()).setDirectory(cloneRepoDir)
            .call();/*ww w  . j  av a  2 s . com*/
    GitRepositoryImpl cloneRepo = new GitRepositoryImpl(cloneGit);

    File testFile = new File(masterRepoDir, "test");
    testFile.createNewFile();

    masterGit.add().addFilepattern("test").call();
    masterGit.commit().setMessage("Test message").call();

    cloneRepo.pull();

    List<RevCommit> commits = IterableUtils.toList(cloneGit.log().all().call());

    assertNotNull(commits);
    assertEquals(1, commits.size());
    assertEquals("Test message", commits.get(0).getFullMessage());

    List<String> committedFiles = getCommittedFiles(cloneGit.getRepository(), commits.get(0));

    assertNotNull(committedFiles);
    assertEquals(1, committedFiles.size());
    assertEquals("test", committedFiles.get(0));
}

From source file:org.craftercms.deployer.impl.processors.GitDiffProcessor.java

License:Open Source License

protected ObjectId getLatestCommitId(Git git) throws DeployerException {
    try {/*from w w  w.  j a  v a 2 s  . c  o  m*/
        return git.getRepository().resolve(Constants.HEAD);
    } catch (IOException e) {
        throw new DeployerException("Unable to retrieve HEAD commit ID", e);
    }
}