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.apache.openaz.xacml.admin.XacmlAdminUI.java

License:Apache License

private static void initializeGitRepository() throws ServletException {
    XacmlAdminUI.repositoryPath = Paths
            .get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_REPOSITORY));
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    try {//from w  w  w .j  a v a2 s . c om
        XacmlAdminUI.repository = builder.setGitDir(XacmlAdminUI.repositoryPath.toFile()).readEnvironment()
                .findGitDir().setBare().build();
        if (Files.notExists(XacmlAdminUI.repositoryPath)
                || Files.notExists(Paths.get(XacmlAdminUI.repositoryPath.toString(), "HEAD"))) {
            //
            // Create it if it doesn't exist. As a bare repository
            //
            logger.info("Creating bare git repository: " + XacmlAdminUI.repositoryPath.toString());
            XacmlAdminUI.repository.create();
            //
            // Add the magic file so remote works.
            //
            Path daemon = Paths.get(XacmlAdminUI.repositoryPath.toString(), "git-daemon-export-ok");
            Files.createFile(daemon);
        }
    } catch (IOException e) {
        logger.error("Failed to build repository: " + repository, e);
        throw new ServletException(e.getMessage(), e.getCause());
    }
    //
    // Make sure the workspace directory is created
    //
    Path workspace = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_WORKSPACE));
    workspace = workspace.toAbsolutePath();
    if (Files.notExists(workspace)) {
        try {
            Files.createDirectory(workspace);
        } catch (IOException e) {
            logger.error("Failed to build workspace: " + workspace, e);
            throw new ServletException(e.getMessage(), e.getCause());
        }
    }
    //
    // Create the user workspace directory
    //
    workspace = Paths.get(workspace.toString(), "pe");
    if (Files.notExists(workspace)) {
        try {
            Files.createDirectory(workspace);
        } catch (IOException e) {
            logger.error("Failed to create directory: " + workspace, e);
            throw new ServletException(e.getMessage(), e.getCause());
        }
    }
    //
    // Get the path to where the repository is going to be
    //
    Path gitPath = Paths.get(workspace.toString(), XacmlAdminUI.repositoryPath.getFileName().toString());
    if (Files.notExists(gitPath)) {
        try {
            Files.createDirectory(gitPath);
        } catch (IOException e) {
            logger.error("Failed to create directory: " + gitPath, e);
            throw new ServletException(e.getMessage(), e.getCause());
        }
    }
    //
    // Initialize the domain structure
    //
    String base = null;
    String domain = XacmlAdminUI.getDomain();
    if (domain != null) {
        for (String part : Splitter.on(':').trimResults().split(domain)) {
            if (base == null) {
                base = part;
            }
            Path subdir = Paths.get(gitPath.toString(), part);
            if (Files.notExists(subdir)) {
                try {
                    Files.createDirectory(subdir);
                    Files.createFile(Paths.get(subdir.toString(), ".svnignore"));
                } catch (IOException e) {
                    logger.error("Failed to create: " + subdir, e);
                    throw new ServletException(e.getMessage(), e.getCause());
                }
            }
        }
    } else {
        try {
            Files.createFile(Paths.get(workspace.toString(), ".svnignore"));
            base = ".svnignore";
        } catch (IOException e) {
            logger.error("Failed to create file", e);
            throw new ServletException(e.getMessage(), e.getCause());
        }
    }
    try {
        //
        // These are the sequence of commands that must be done initially to
        // finish setting up the remote bare repository.
        //
        Git git = Git.init().setDirectory(gitPath.toFile()).setBare(false).call();
        git.add().addFilepattern(base).call();
        git.commit().setMessage("Initialize Bare Repository").call();
        StoredConfig config = git.getRepository().getConfig();
        config.setString("remote", "origin", "url", XacmlAdminUI.repositoryPath.toAbsolutePath().toString());
        config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
        config.save();
        git.push().setRemote("origin").add("master").call();
        /*
         * This will not work unless git.push().setRemote("origin").add("master").call();
         * is called first. Otherwise it throws an exception. However, if the push() is
         * called then calling this function seems to add nothing.
         * 
        git.branchCreate().setName("master")
           .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM)
           .setStartPoint("origin/master").setForce(true).call();
        */
    } catch (GitAPIException | IOException e) {
        logger.error(e);
        throw new ServletException(e.getMessage(), e.getCause());
    }
}

From source file:org.apache.openaz.xacml.admin.XacmlAdminUI.java

License:Apache License

/**
 * Initializes a user's git repository./*from w  w w  .ja v  a 2  s.com*/
 * 
 * 
 * @param workspacePath
 * @param userId
 * @param email
 * @return
 * @throws IOException
 * @throws InvalidRemoteException
 * @throws TransportException
 * @throws GitAPIException
 */
private static Path initializeUserRepository(Path workspacePath, String userId, URI email)
        throws IOException, InvalidRemoteException, TransportException, GitAPIException {
    Path gitPath = null;
    //
    // Initialize the User's Git repository
    //
    if (Files.notExists(workspacePath)) {
        logger.info("Creating user workspace: " + workspacePath.toAbsolutePath().toString());
        //
        // Create our user's directory
        //
        Files.createDirectory(workspacePath);
    }
    gitPath = Paths.get(workspacePath.toString(), XacmlAdminUI.repositoryPath.getFileName().toString());
    if (Files.notExists(gitPath)) {
        //
        // It doesn't exist yet, so Clone it and check it out
        //
        logger.info("Cloning user git directory: " + gitPath.toAbsolutePath().toString());
        Git.cloneRepository().setURI(XacmlAdminUI.repositoryPath.toUri().toString())
                .setDirectory(gitPath.toFile()).setNoCheckout(false).call();
        //
        // Set userid
        //
        Git git = Git.open(gitPath.toFile());
        StoredConfig config = git.getRepository().getConfig();
        config.setString("user", null, "name", userId);
        if (email != null && email.getPath() != null) {
            config.setString("user", null, "email", email.toString());
        }
        config.save();
    }
    return gitPath;
}

From source file:org.aysada.licensescollector.dependencies.impl.GitCodeBaseProvider.java

License:Open Source License

public File getLocalRepositoryRoot(String remoteUrl) {
    try {/*w ww.  j a  v a2  s  . c o  m*/
        File prjWs = getLocalWSFor(remoteUrl);
        if (prjWs.exists()) {
            Repository repo = Git.open(prjWs).getRepository();
            Git git = new Git(repo);
            git.fetch().call();
            git.close();
            LOGGER.info("Lcoal git repo for {} updated.", remoteUrl);
            return repo.getDirectory();
        } else {
            prjWs.mkdir();
            Git localRepo = Git.cloneRepository().setDirectory(prjWs).setURI(remoteUrl)
                    .setCloneAllBranches(false).call();
            File directory = localRepo.getRepository().getDirectory();
            localRepo.close();
            LOGGER.info("Cloned lcoal git repo for {}.", remoteUrl);
            return directory;
        }
    } catch (IOException | GitAPIException e) {
        LOGGER.error("Error working with git.", e);
    }
    return null;
}

From source file:org.cicomponents.test.GitEmitterTest.java

License:Mozilla Public License

@Test
@SneakyThrows/*from  w ww  .ja va  2s .c  o  m*/
public void listenerDiscovery() {
    try (WorkingDirectory directory = workingDirectoryProvider.getDirectory()) {
        Git git = Git.init().setDirectory(new File(directory.getDirectory())).call();
        RevCommit commit = git.commit().setAllowEmpty(true).setMessage("Test").call();

        Hashtable<String, Object> properties = new Hashtable<>();
        properties.put("repository", "file://" + git.getRepository().getDirectory().getAbsolutePath());
        properties.put("type", "latest");
        Listener listener = new Listener();
        ServiceRegistration<ResourceListener> registration = bundleContext
                .registerService(ResourceListener.class, listener, properties);

        Collection<ServiceReference<GitRevisionEmitter>> references = bundleContext.getServiceReferences(
                GitRevisionEmitter.class, "(objectClass=" + GitRevisionEmitter.class.getName() + ")");
        assertFalse(references.isEmpty());

        registration.unregister();

        git.close();
    }
}

From source file:org.cicomponents.test.GitEmitterTest.java

License:Mozilla Public License

@Test
@SneakyThrows/*from   ww  w . j  av  a  2s  .  c  om*/
public void listenerRemoval() {
    try (WorkingDirectory directory = workingDirectoryProvider.getDirectory()) {
        Git git = Git.init().setDirectory(new File(directory.getDirectory())).call();
        RevCommit commit = git.commit().setAllowEmpty(true).setMessage("Test").call();

        Hashtable<String, Object> properties = new Hashtable<>();
        properties.put("repository", "file://" + git.getRepository().getDirectory().getAbsolutePath());
        properties.put("type", "latest");
        Listener listener = new Listener();
        ServiceRegistration<ResourceListener> registration = bundleContext
                .registerService(ResourceListener.class, listener, properties);

        Collection<ServiceReference<GitRevisionEmitter>> references = bundleContext.getServiceReferences(
                GitRevisionEmitter.class, "(objectClass=" + GitRevisionEmitter.class.getName() + ")");
        assertFalse(references.isEmpty());

        ObjectId objectId = listener.getFuture().get();
        assertEquals(commit.toObjectId(), objectId);
        listener.reset();

        registration.unregister();

        git.commit().setAllowEmpty(true).setMessage("Test #1").call();

        try {
            listener.getFuture().get(11, TimeUnit.SECONDS);
            fail("Listener was not removed");
        } catch (TimeoutException e) {
            // this is what should happen
        }

        git.close();
    }
}

From source file:org.cicomponents.test.GitEmitterTest.java

License:Mozilla Public License

@Test
@SneakyThrows//from  w  w  w .  j av a  2  s  . c  om
public void listener() {
    try (WorkingDirectory directory = workingDirectoryProvider.getDirectory()) {
        Git git = Git.init().setDirectory(new File(directory.getDirectory())).call();
        RevCommit commit = git.commit().setAllowEmpty(true).setMessage("Test").call();

        Hashtable<String, Object> properties = new Hashtable<>();
        properties.put("repository", "file://" + git.getRepository().getDirectory().getAbsolutePath());
        properties.put("type", "latest");
        Listener listener = new Listener();
        ServiceRegistration<ResourceListener> registration = bundleContext
                .registerService(ResourceListener.class, listener, properties);

        Collection<ServiceReference<GitRevisionEmitter>> references = bundleContext.getServiceReferences(
                GitRevisionEmitter.class, "(objectClass=" + GitRevisionEmitter.class.getName() + ")");

        ObjectId objectId = listener.getFuture().get();
        assertEquals(commit.toObjectId(), objectId);
        listener.reset();

        // Test ongoing commits
        commit = git.commit().setAllowEmpty(true).setMessage("Test #1").call();

        objectId = listener.getFuture().get();
        assertEquals(commit.toObjectId(), objectId);

        git.close();
        registration.unregister();
    }
}

From source file:org.commonwl.view.cwl.CWLToolRunner.java

License:Apache License

@Async
public void createWorkflowFromQueued(QueuedWorkflow queuedWorkflow) throws IOException, InterruptedException {

    Workflow tempWorkflow = queuedWorkflow.getTempRepresentation();
    GitDetails gitInfo = tempWorkflow.getRetrievedFrom();
    final String repoUrl = gitInfo.getRepoUrl();
    // Parse using cwltool and replace in database
    try {//from w  w  w. j av a 2 s  .co m
        boolean safeToAccess = gitSemaphore.acquire(repoUrl);
        Git repo = gitService.getRepository(gitInfo, safeToAccess);
        Path localPath = repo.getRepository().getWorkTree().toPath();
        Path workflowFile = localPath.resolve(gitInfo.getPath()).normalize().toAbsolutePath();
        Workflow newWorkflow = cwlService.parseWorkflowWithCwltool(tempWorkflow, workflowFile, localPath);

        // Success
        newWorkflow.setRetrievedFrom(tempWorkflow.getRetrievedFrom());
        newWorkflow.setRetrievedOn(new Date());
        newWorkflow.setLastCommit(tempWorkflow.getLastCommit());
        newWorkflow.setCwltoolVersion(cwlToolVersion);

        workflowRepository.save(newWorkflow);

        // Generate RO bundle
        roBundleFactory.createWorkflowRO(newWorkflow);

        // Mark success on queue
        queuedWorkflow.setCwltoolStatus(CWLToolStatus.SUCCESS);

    } catch (QueryException ex) {
        logger.error("Jena query exception ", ex);
        queuedWorkflow.setCwltoolStatus(CWLToolStatus.ERROR);
        queuedWorkflow.setMessage("An error occurred when executing a query on the SPARQL store");
    } catch (CWLValidationException ex) {
        logger.error(ex.getMessage(), ex);
        queuedWorkflow.setCwltoolStatus(CWLToolStatus.ERROR);
        queuedWorkflow.setMessage(ex.getMessage());
    } catch (Exception ex) {
        logger.error("Unexpected error", ex);
        queuedWorkflow.setCwltoolStatus(CWLToolStatus.ERROR);
        queuedWorkflow.setMessage("Whoops! Cwltool ran successfully, but an unexpected "
                + "error occurred in CWLViewer!\n" + "Help us by reporting it on Gitter or a Github issue\n");
    } finally {
        gitSemaphore.release(repoUrl);
        queuedWorkflowRepository.save(queuedWorkflow);
    }

}

From source file:org.commonwl.view.git.GitService.java

License:Apache License

/**
 * Gets the commit ID of the HEAD for the given repository
 * @param repo The Git repository//from w ww  .  ja  va  2s .co m
 * @return The commit ID of the HEAD for the repository
 * @throws IOException If the HEAD is detached
 */
public String getCurrentCommitID(Git repo) throws IOException {
    return repo.getRepository().findRef("HEAD").getObjectId().getName();
}

From source file:org.commonwl.view.researchobject.ROBundleService.java

License:Apache License

/**
 * Creates a new research object bundle for a workflow from a Git repository
 * @param workflow The workflow to create the research object for
 * @return The constructed bundle//from w w  w . j a v a  2 s  .  c  o  m
 */
public Bundle createBundle(Workflow workflow, GitDetails gitInfo) throws IOException {

    // Create a new RO bundle
    Bundle bundle = Bundles.createBundle();
    Manifest manifest = bundle.getManifest();

    // Simplified attribution for RO bundle
    try {
        manifest.setId(new URI(workflow.getPermalink()));

        // Tool attribution in createdBy
        manifest.setCreatedBy(appAgent);

        // Retrieval Info
        // TODO: Make this importedBy/On/From
        manifest.setRetrievedBy(appAgent);
        manifest.setRetrievedOn(manifest.getCreatedOn());
        manifest.setRetrievedFrom(new URI(workflow.getPermalink(Format.ro)));

        // Make a directory in the RO bundle to store the files
        Path bundleRoot = bundle.getRoot();
        Path bundlePath = bundleRoot.resolve("workflow");
        Files.createDirectory(bundlePath);

        // Add the files from the repo to this workflow
        Set<HashableAgent> authors = new HashSet<>();

        boolean safeToAccess = gitSemaphore.acquire(gitInfo.getRepoUrl());
        try {
            Git gitRepo = gitService.getRepository(workflow.getRetrievedFrom(), safeToAccess);
            Path relativePath = Paths.get(FilenameUtils.getPath(gitInfo.getPath()));
            Path gitPath = gitRepo.getRepository().getWorkTree().toPath().resolve(relativePath);
            addFilesToBundle(gitInfo, bundle, bundlePath, gitRepo, gitPath, authors, workflow);
        } finally {
            gitSemaphore.release(gitInfo.getRepoUrl());
        }

        // Add combined authors
        manifest.setAuthoredBy(new ArrayList<>(authors));

        // Add visualisation images
        File png = graphVizService.getGraph(workflow.getID() + ".png", workflow.getVisualisationDot(), "png");
        Files.copy(png.toPath(), bundleRoot.resolve("visualisation.png"));
        PathMetadata pngAggr = bundle.getManifest().getAggregation(bundleRoot.resolve("visualisation.png"));
        pngAggr.setRetrievedFrom(new URI(workflow.getPermalink(Format.png)));

        File svg = graphVizService.getGraph(workflow.getID() + ".svg", workflow.getVisualisationDot(), "svg");
        Files.copy(svg.toPath(), bundleRoot.resolve("visualisation.svg"));
        PathMetadata svgAggr = bundle.getManifest().getAggregation(bundleRoot.resolve("visualisation.svg"));
        svgAggr.setRetrievedFrom(new URI(workflow.getPermalink(Format.svg)));

        // Add annotation files
        GitDetails wfDetails = workflow.getRetrievedFrom();

        // Get URL to run cwltool
        String rawUrl = wfDetails.getRawUrl();
        String packedWorkflowID = wfDetails.getPackedId();
        if (packedWorkflowID != null) {
            if (packedWorkflowID.charAt(0) != '#') {
                rawUrl += "#";
            }
            rawUrl += packedWorkflowID;
        }

        // Run cwltool for annotations
        List<PathAnnotation> manifestAnnotations = new ArrayList<>();
        try {
            addAggregation(bundle, manifestAnnotations, "merged.cwl", cwlTool.getPackedVersion(rawUrl));
        } catch (CWLValidationException ex) {
            logger.error("Could not pack workflow when creating Research Object", ex.getMessage());
        }
        String rdfUrl = workflow.getIdentifier();
        if (rdfService.graphExists(rdfUrl)) {
            addAggregation(bundle, manifestAnnotations, "workflow.ttl",
                    new String(rdfService.getModel(rdfUrl, "TURTLE")));
        }
        bundle.getManifest().setAnnotations(manifestAnnotations);

        // Git2prov history
        List<Path> history = new ArrayList<>();
        // FIXME: Below is a a hack to pretend the URI is a Path
        String git2prov = "http://git2prov.org/git2prov?giturl=" + gitInfo.getRepoUrl()
                + "&serialization=PROV-JSON";
        Path git2ProvPath = bundle.getRoot().relativize(bundle.getRoot().resolve(git2prov));
        history.add(git2ProvPath);
        bundle.getManifest().setHistory(history);

    } catch (URISyntaxException ex) {
        logger.error("Error creating URI for RO Bundle", ex);
    } catch (GitAPIException ex) {
        logger.error("Error getting repository to create RO Bundle", ex);
    }

    // Return the completed bundle
    return bundle;

}

From source file:org.commonwl.view.researchobject.ROBundleServiceTest.java

License:Apache License

@Before
public void setUp() throws Exception {
    Repository mockRepo = Mockito.mock(Repository.class);
    when(mockRepo.getWorkTree()).thenReturn(new File("src/test/resources/cwl/"));

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

    // Get mock Git service
    GitService mockGitService = Mockito.mock(GitService.class);
    when(mockGitService.getRepository(anyObject(), anyBoolean())).thenReturn(gitRepo);

    Set<HashableAgent> authors = new HashSet<>();
    authors.add(new HashableAgent("Mark Robinson", null, new URI("mailto:mark@example.com")));
    when(mockGitService.getAuthors(anyObject(), anyObject())).thenReturn(authors);

    // Mock Graphviz service
    GraphVizService mockGraphvizService = Mockito.mock(GraphVizService.class);
    when(mockGraphvizService.getGraph(anyString(), anyString(), anyString()))
            .thenReturn(new File("src/test/resources/graphviz/testVis.png"))
            .thenReturn(new File("src/test/resources/graphviz/testVis.svg"));

    // Mock CWLTool
    CWLTool mockCwlTool = Mockito.mock(CWLTool.class);
    when(mockCwlTool.getPackedVersion(anyString())).thenReturn("cwlVersion: v1.0");

    // Mock RDF Service
    ResultSet emptyResult = Mockito.mock(ResultSet.class);
    when(emptyResult.hasNext()).thenReturn(false);
    RDFService mockRdfService = Mockito.mock(RDFService.class);
    when(mockRdfService.getAuthors(anyString(), anyString())).thenReturn(emptyResult);
    when(mockRdfService.graphExists(anyString())).thenReturn(true);
    when(mockRdfService.getModel(anyObject(), anyObject()))
            .thenReturn("@prefix cwl: <https://w3id.org/cwl/cwl#> .".getBytes());

    // Create new RO bundle
    roBundleService = new ROBundleService(roBundleFolder.getRoot().toPath(), "CWL Viewer",
            "https://view.commonwl.org", 5242880, mockGraphvizService, mockGitService, mockRdfService,
            Mockito.mock(GitSemaphore.class), mockCwlTool);
    roBundleServiceZeroSizeLimit = new ROBundleService(roBundleFolder.getRoot().toPath(), "CWL Viewer",
            "https://view.commonwl.org", 0, mockGraphvizService, mockGitService, mockRdfService,
            Mockito.mock(GitSemaphore.class), mockCwlTool);

    GitDetails lobSTRdraft3Details = new GitDetails("https://github.com/common-workflow-language/workflows.git",
            "933bf2a1a1cce32d88f88f136275535da9df0954", "workflows/lobSTR/lobSTR-workflow.cwl");
    lobSTRdraft3 = Mockito.mock(Workflow.class);
    when(lobSTRdraft3.getID()).thenReturn("testID");
    when(lobSTRdraft3.getRetrievedFrom()).thenReturn(lobSTRdraft3Details);
    when(lobSTRdraft3.getLastCommit()).thenReturn("933bf2a1a1cce32d88f88f136275535da9df0954");
    final String permalink = "https://w3id.org/cwl/view/git/"
            + "933bf2a1a1cce32d88f88f136275535da9df0954/workflows/lobSTR/lobSTR-workflow.cwl";
    when(lobSTRdraft3.getIdentifier()).thenReturn(permalink);
    when(lobSTRdraft3.getPermalink()).thenReturn(permalink);
    when(lobSTRdraft3.getPermalink(any())).thenAnswer(new Answer<String>() {
        @Override/*from w w w  . j  a va2  s.  co m*/
        public String answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            return permalink + "?format=" + args[0];
        }
    });
}