List of usage examples for org.eclipse.jgit.api Git close
@Override public void close()
Free resources associated with this instance.
From source file:org.lab41.dendrite.web.controller.GraphExportController.java
License:Apache License
@RequestMapping(value = "/api/graphs/{graphId}/file-save", method = RequestMethod.POST) public ResponseEntity<Map<String, Object>> save(@PathVariable String graphId, @Valid GraphExportBean item, BindingResult result) throws IOException, GitAPIException { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Map<String, Object> response = new HashMap<>(); if (result.hasErrors()) { response.put("status", "error"); response.put("msg", result.toString()); return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); }/*w ww . j a va2 s.co m*/ MetaGraphTx metaGraphTx = metaGraphService.buildTransaction().readOnly().start(); GraphMetadata graphMetadata; Git git; try { graphMetadata = metaGraphTx.getGraph(graphId); git = historyService.projectGitRepository(graphMetadata.getProject()); metaGraphTx.commit(); } catch (Throwable t) { metaGraphTx.rollback(); throw t; } DendriteGraph graph = metaGraphService.getGraph(graphId); if (graph == null) { response.put("status", "error"); response.put("msg", "cannot find graph '" + graphId + "'"); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } logger.debug("saving graph '" + graphId + "'"); // extract the storage location for the history String format = item.getFormat(); DendriteGraphTx tx = graph.buildTransaction().readOnly().start(); try { try { String path; if (format.equalsIgnoreCase("GraphSON")) { path = new File(git.getRepository().getWorkTree(), graphId + ".json").getPath(); GraphSONWriter.outputGraph(tx, path); } else if (format.equalsIgnoreCase("GraphML")) { path = new File(git.getRepository().getWorkTree(), graphId + ".xml").getPath(); GraphMLWriter.outputGraph(tx, path); } else if (format.equalsIgnoreCase("GML")) { path = new File(git.getRepository().getWorkTree(), graphId + ".gml").getPath(); GMLWriter.outputGraph(tx, path); } else { tx.rollback(); response.put("status", "error"); response.put("msg", "unknown format '" + format + "'"); return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); } git.add().addFilepattern(".").call(); git.commit().setAuthor(authentication.getName(), "").setMessage("commit").call(); } finally { git.close(); } } catch (IOException e) { tx.rollback(); response.put("status", "error"); response.put("msg", "exception: " + e.toString()); return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); } tx.commit(); response.put("status", "ok"); return new ResponseEntity<>(response, HttpStatus.NO_CONTENT); }
From source file:org.phoenicis.repository.types.GitRepository.java
License:Open Source License
private void cloneOrUpdate() throws RepositoryException { final boolean folderExists = this.localFolder.exists(); // check that the repository folder exists if (!folderExists) { LOGGER.info("Creating local folder for " + this); if (!this.localFolder.mkdirs()) { throw new RepositoryException("Couldn't create local folder for " + this); }/*from w w w . ja v a 2 s. c o m*/ } Git gitRepository = null; /* * if the repository folder previously didn't exist, clone the * repository now and checkout the correct branch */ if (!folderExists) { LOGGER.info("Cloning " + this); try { gitRepository = Git.cloneRepository().setURI(this.repositoryUri.toString()) .setDirectory(this.localFolder).setBranch(this.branch).call(); } catch (GitAPIException e) { throw new RepositoryException( String.format("Folder '%s' is no git-repository", this.localFolder.getAbsolutePath()), e); } finally { // close repository to free resources if (gitRepository != null) { gitRepository.close(); } } } /* * otherwise open the folder and pull the newest updates from the * repository */ else { // if anything doesn't work here, we still have our local checkout // e.g. could be that the git repository cannot be accessed, there is not Internet connection etc. // TODO: it might make sense to ensure that our local checkout is not empty / a valid git repository try { LOGGER.info("Opening " + this); gitRepository = Git.open(localFolder); LOGGER.info("Pulling new commits from " + this); gitRepository.pull().call(); } catch (Exception e) { LOGGER.warn("Could not update {0}. Local checkout will be used.", e); } finally { // close repository to free resources if (gitRepository != null) { gitRepository.close(); } } } }
From source file:org.spdx.tools.LicenseListPublisher.java
License:Apache License
/** * Publish a license list to the license data git repository * @param release license list release name (must be associatd with a tag in the license-list-xml repo) * @param gitUserName github username to be used - must have commit access to the license-xml-data repo * @param gitPassword github password//w w w . j a v a 2 s. com * @throws LicensePublisherException * @throws LicenseGeneratorException */ private static void publishLicenseList(String release, String gitUserName, String gitPassword, boolean ignoreWarnings) throws LicensePublisherException, LicenseGeneratorException { CredentialsProvider githubCredentials = new UsernamePasswordCredentialsProvider(gitUserName, gitPassword); File licenseXmlDir = null; File licenseDataDir = null; Git licenseXmlGit = null; Git licenseDataGit = null; try { licenseXmlDir = Files.createTempDirectory("LicenseXML").toFile(); System.out.println("Cloning the license XML repository - this could take a while..."); licenseXmlGit = Git.cloneRepository().setCredentialsProvider(githubCredentials) .setDirectory(licenseXmlDir).setURI(LICENSE_XML_URI).call(); Ref releaseTag = licenseXmlGit.getRepository().getTags().get(release); if (releaseTag == null) { throw new LicensePublisherException( "Release " + release + " not found as a tag in the License List XML repository"); } licenseXmlGit.checkout().setName(releaseTag.getName()).call(); licenseDataDir = Files.createTempDirectory("LicenseData").toFile(); System.out.println("Cloning the license data repository - this could take a while..."); licenseDataGit = Git.cloneRepository().setCredentialsProvider(githubCredentials) .setDirectory(licenseDataDir).setURI(LICENSE_DATA_URI).call(); Ref dataReleaseTag = licenseDataGit.getRepository().getTags().get(release); boolean dataReleaseTagExists = false; if (dataReleaseTag != null) { dataReleaseTagExists = true; licenseDataGit.checkout().setName(releaseTag.getName()).call(); } cleanLicenseDataDir(licenseDataDir); String todayDate = new SimpleDateFormat("dd-MMM-yyyy").format(Calendar.getInstance().getTime()); List<String> warnings = LicenseRDFAGenerator.generateLicenseData( new File(licenseXmlDir.getPath() + File.separator + "src"), licenseDataDir, release, todayDate); if (warnings.size() > 0 && !ignoreWarnings) { throw new LicensePublisherException( "There are some skipped or invalid license input data. Publishing aborted. To ignore, add the --ignore option as the first parameter"); } licenseDataGit.add().addFilepattern(".").call(); licenseDataGit.commit().setAll(true) .setCommitter("SPDX License List Publisher", "spdx-tech@lists.spdx.org") .setMessage("License List Publisher for " + gitUserName + ". License list version " + release) .call(); if (!dataReleaseTagExists) { licenseDataGit.tag().setName(release).setMessage("SPDX License List release " + release).call(); } licenseDataGit.push().setCredentialsProvider(githubCredentials).setPushTags().call(); } catch (IOException e) { throw new LicensePublisherException("I/O Error publishing license list", e); } catch (InvalidRemoteException e) { throw new LicensePublisherException("Invalid remote error trying to access the git repositories", e); } catch (TransportException e) { throw new LicensePublisherException("Transport error trying to access the git repositories", e); } catch (GitAPIException e) { throw new LicensePublisherException("GIT API error trying to access the git repositories", e); } finally { if (licenseXmlGit != null) { licenseXmlGit.close(); } if (licenseDataGit != null) { licenseDataGit.close(); } if (licenseXmlDir != null) { deleteDir(licenseXmlDir); } if (licenseDataDir != null) { deleteDir(licenseDataDir); } } }
From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.java
License:Apache License
/** * Get the working directory ready./*from w w w . java 2s . c o m*/ */ public String refresh(String label) { initialize(); Git git = null; try { git = createGitClient(); if (shouldPull(git)) { fetch(git, label); //checkout after fetch so we can get any new branches, tags, ect. checkout(git, label); if (isBranch(git, label)) { //merge results from fetch merge(git, label); if (!isClean(git)) { logger.warn("The local repository is dirty. Resetting it to origin/" + label + "."); resetHard(git, label, "refs/remotes/origin/" + label); } } } else { //nothing to update so just checkout checkout(git, label); } //always return what is currently HEAD as the version return git.getRepository().getRef("HEAD").getObjectId().getName(); } catch (RefNotFoundException e) { throw new NoSuchLabelException("No such label: " + label, e); } catch (GitAPIException e) { throw new IllegalStateException("Cannot clone or checkout repository", e); } catch (Exception e) { throw new IllegalStateException("Cannot load environment", e); } finally { try { if (git != null) { git.close(); } } catch (Exception e) { this.logger.warn("Could not close git repository", e); } } }
From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.java
License:Apache License
/** * Clones the remote repository and then opens a connection to it. * @throws GitAPIException/*w ww . jav a 2 s . c o m*/ * @throws IOException */ private void initClonedRepository() throws GitAPIException, IOException { if (!getUri().startsWith(FILE_URI_PREFIX)) { deleteBaseDirIfExists(); Git git = cloneToBasedir(); if (git != null) { git.close(); } git = openGitRepository(); if (git != null) { git.close(); } } }
From source file:org.springframework.cloud.release.internal.git.GitRepo.java
License:Apache License
/** * Clones the project/*from www . j a v a 2s. co m*/ * @param projectUri - URI of the project * @return file where the project was cloned */ File cloneProject(URI projectUri) { try { log.info("Cloning repo from [{}] to [{}]", projectUri, this.basedir); Git git = cloneToBasedir(projectUri, this.basedir); if (git != null) { git.close(); } File clonedRepo = git.getRepository().getWorkTree(); log.info("Cloned repo to [{}]", clonedRepo); return clonedRepo; } catch (Exception e) { throw new IllegalStateException("Exception occurred while cloning repo", e); } }
From source file:org.springframework.cloud.release.internal.git.GitRepo.java
License:Apache License
private Ref checkoutBranch(File projectDir, String branch) throws GitAPIException { Git git = this.gitFactory.open(projectDir); CheckoutCommand command = git.checkout().setName(branch); try {/*from www .j av a2 s .c om*/ if (shouldTrack(git, branch)) { trackBranch(command, branch); } return command.call(); } catch (GitAPIException e) { deleteBaseDirIfExists(); throw e; } finally { git.close(); } }
From source file:org.walkmod.git.readers.GitFileReader.java
License:Open Source License
@Override public Resource<File> read() throws Exception { File file = new File(".git"); Resource<File> result = null; if (file.exists()) { Git git = Git.open(file.getAbsoluteFile().getParentFile().getCanonicalFile()); try {/*from w w w. java2 s . co m*/ StatusCommand cmd = git.status(); List<String> cfgIncludesList = null; String[] cfgIncludes = getIncludes(); if (cfgIncludes != null && cfgIncludes.length > 0) { cfgIncludesList = Arrays.asList(cfgIncludes); } String path = getPath(); Status status = cmd.call(); Set<String> uncommitted = status.getUncommittedChanges(); uncommitted.addAll(status.getUntracked()); Set<String> includes = new HashSet<String>(); if (!uncommitted.isEmpty()) { for (String uncommittedFile : uncommitted) { if (uncommittedFile.startsWith(path)) { String fileName = uncommittedFile.substring(path.length() + 1); if (cfgIncludesList == null || cfgIncludesList.contains(fileName)) { includes.add(fileName); } } } } else { Set<String> filesInCommit = getFilesInHEAD(git.getRepository()); for (String committedFile : filesInCommit) { if (committedFile.startsWith(path)) { String fileName = committedFile.substring(path.length() + 1); if (cfgIncludesList == null || cfgIncludesList.contains(fileName)) { includes.add(fileName); } } } } if (!includes.isEmpty()) { String[] includesArray = new String[includes.size()]; includesArray = includes.toArray(includesArray); setIncludes(includesArray); } } finally { git.close(); } } result = super.read(); return result; }
From source file:org.yakindu.sct.examples.wizard.service.git.GitRepositoryExampleService.java
License:Open Source License
protected IStatus cloneRepository(IProgressMonitor monitor) { String repoURL = getPreference(ExamplesPreferenceConstants.REMOTE_LOCATION); String remoteBranch = getPreference(ExamplesPreferenceConstants.REMOTE_BRANCH); Git call = null; java.nio.file.Path storageLocation = getStorageLocation(); try {//from w ww .ja v a 2s .co m call = Git.cloneRepository().setURI(repoURL).setDirectory(storageLocation.toFile()) .setProgressMonitor(new EclipseGitProgressTransformer(monitor)).setBranch(remoteBranch).call(); } catch (GitAPIException e) { try { deleteFolder(storageLocation); } catch (IOException ex) { ex.printStackTrace(); } return new Status(IStatus.ERROR, ExampleActivator.PLUGIN_ID, "Unable to clone repository " + repoURL + "!"); } finally { if (call != null) call.close(); if (monitor.isCanceled()) { try { deleteFolder(storageLocation); } catch (IOException e) { e.printStackTrace(); } } } return Status.OK_STATUS; }
From source file:ru.nikitenkogleb.androidtools.newappwizard.GitSupport.java
/** Creates new Git Support module */ public GitSupport(String login, String password, String repository, String projectPath, String tempFolder, String initBranch) {/* ww w . j a v a2 s. co m*/ final String home = System.getProperty("user.home"); if (login == null || login.isEmpty()) { mSshConfigCallback = new SSHConfigCallback(home + Path.SEPARATOR + ".ssh" + Path.SEPARATOR + "id_rsa", new CredentialsProvider(password)); mHttpsCredentialsProvider = null; } else { mSshConfigCallback = null; mHttpsCredentialsProvider = new UsernamePasswordCredentialsProvider(login, password); } try { final CloneCommand cloneCommand = Git.cloneRepository().setURI(repository) .setDirectory(new File(tempFolder)); if (mSshConfigCallback != null) cloneCommand.setTransportConfigCallback(mSshConfigCallback); else cloneCommand.setCredentialsProvider(mHttpsCredentialsProvider); final Git mGit = cloneCommand.call(); try { mGit.checkout().setCreateBranch(true).setName(initBranch).call(); } catch (RefNotFoundException e) { e.printStackTrace(); final StoredConfig config = mGit.getRepository().getConfig(); config.setString("remote", "origin", "url", repository); config.save(); } mGit.close(); move(new File(tempFolder + "/.git"), new File(projectPath + "/.git")); move(new File(tempFolder + "/README.md"), new File(projectPath + "/README.md")); move(new File(tempFolder + "/LICENSE"), new File(projectPath + "/LICENSE")); move(new File(tempFolder + "/.gitignore"), new File(projectPath + "/.gitignore")); new File(tempFolder).delete(); mProjectPath = projectPath; } catch (GitAPIException | IOException e) { e.printStackTrace(); } }