List of usage examples for org.eclipse.jgit.lib Repository close
@Override public void close()
Decrement the use count, and maybe close resources.
From source file:i5.las2peer.services.gamificationGamifierService.GamificationGamifierService.java
License:Open Source License
@POST @Path("/repo") @Produces(MediaType.APPLICATION_JSON)//from w w w . j a va2 s . com @ApiOperation(value = "memberLoginValidation", notes = "Simple function to validate a member login.") @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Member is registered"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "User data error to be retrieved"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Cannot connect to database"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "User data error to be retrieved. Not JSON object") }) public HttpResponse updateRepository( @ApiParam(value = "Data in JSON", required = true) @ContentParam byte[] contentB) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/gamifier/repo"); long randomLong = new Random().nextLong(); //To be able to match UserAgent userAgent = (UserAgent) getContext().getMainAgent(); // take username as default name String name = userAgent.getLoginName(); System.out.println("User name : " + name); if (name.equals("anonymous")) { return unauthorizedMessage(); } L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_9, "" + randomLong); JSONObject objResponse = new JSONObject(); String content = new String(contentB); if (content.equals(null)) { objResponse.put("message", "Cannot update repository. Cannot parse json data into string"); //L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); L2pLogger.logEvent(this, Event.AGENT_UPLOAD_FAILED, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } // if(!initializeDBConnection()){ // objResponse.put("message", "Cannot connect to database"); // L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); // return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); // } JSONObject obj; String originRepositoryName; String newRepositoryName; String fileContent; String appId; String epURL; String aopScript; try { obj = (JSONObject) JSONValue.parseWithException(content); originRepositoryName = stringfromJSON(obj, "originRepositoryName"); newRepositoryName = stringfromJSON(obj, "newRepositoryName"); //fileContent = stringfromJSON(obj,"fileContent"); appId = stringfromJSON(obj, "appId"); epURL = stringfromJSON(obj, "epURL"); aopScript = stringfromJSON(obj, "aopScript"); } catch (ParseException e) { e.printStackTrace(); objResponse.put("message", "Cannot update repository. Cannot parse json data into string. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (IOException e) { e.printStackTrace(); objResponse.put("message", "Cannot update repository. Cannot parse json data into string. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } // check if repo exist TreeWalk treeWalk = null; Repository newRepository = null; Repository originRepository = null; // helper variables // variables holding content to be modified and added to repository later String widget = null; try { RepositoryHelper.deleteRemoteRepository(newRepositoryName, gitHubOrganizationNewRepo, gitHubUserNewRepo, gitHubPasswordNewRepo); } catch (GitHubException e) { //e.printStackTrace(); } try { PersonIdent caeUser = new PersonIdent(gitHubUserNewRepo, gitHubUserMailNewRepo); originRepository = RepositoryHelper.getRemoteRepository(originRepositoryName, gitHubOrganizationOrigin); newRepository = RepositoryHelper.generateNewRepository(newRepositoryName, gitHubOrganizationNewRepo, gitHubUserNewRepo, gitHubPasswordNewRepo); File originDir = originRepository.getDirectory(); // now load the TreeWalk containing the origin repository content treeWalk = RepositoryHelper.getRepositoryContent(originRepositoryName, gitHubOrganizationOrigin); //System.out.println("PATH " + treeWalk.getPathString()); System.out.println("PATH2 " + originDir.getParent()); System.out.println("PATH3 " + newRepository.getDirectory().getParent()); // treeWalk.setFilter(PathFilter.create("frontend/")); ObjectReader reader = treeWalk.getObjectReader(); // walk through the tree and retrieve the needed templates while (treeWalk.next()) { ObjectId objectId = treeWalk.getObjectId(0); ObjectLoader loader = reader.open(objectId); switch (treeWalk.getNameString()) { case "widget.xml": widget = new String(loader.getBytes(), "UTF-8"); break; } } // replace widget.xml //widget = createWidgetCode(widget, htmlElementTemplate, yjsImports, gitHubOrganization, repositoryName, frontendComponent); widget = RepositoryHelper.appendWidget(widget, gitHubOrganizationNewRepo, newRepositoryName); RepositoryHelper.copyFolder(originRepository.getDirectory().getParentFile(), newRepository.getDirectory().getParentFile()); String aopfilestring = RepositoryHelper.readFile("../GamificationGamifierService/jsfiles/aop.pack.js", Charset.forName("UTF-8")); String oidcwidgetfilestring = RepositoryHelper .readFile("../GamificationGamifierService/jsfiles/oidc-widget.js", Charset.forName("UTF-8")); String gamifierstring = RepositoryHelper.readFile("../GamificationGamifierService/jsfiles/gamifier.js", Charset.forName("UTF-8")); gamifierstring = gamifierstring.replace("$Application_Id$", appId); gamifierstring = gamifierstring.replace("$Endpoint_URL$", epURL); gamifierstring = gamifierstring.replace("$AOP_Script$", aopScript); // add files to new repository newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "", "widget.xml", widget); newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "gamification/", "aop.pack.js", aopfilestring); newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "gamification/", "oidc-widget.js", oidcwidgetfilestring); newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "gamification/", "gamifier.js", gamifierstring); // stage file Git.wrap(newRepository).add().addFilepattern(".").call(); // commit files Git.wrap(newRepository).commit().setMessage("Generated new repo ").setCommitter(caeUser).call(); // push (local) repository content to GitHub repository "gh-pages" branch RepositoryHelper.pushToRemoteRepository(newRepository, gitHubUserNewRepo, gitHubPasswordNewRepo, "master", "gh-pages"); // close all open resources } catch (GitHubException e1) { // TODO Auto-generated catch block e1.printStackTrace(); objResponse.put("message", "Cannot update repository. Github exception. " + e1.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (IOException e1) { e1.printStackTrace(); objResponse.put("message", "Cannot update repository. Github exception. " + e1.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (Exception e) { objResponse.put("message", "Cannot update repository. Github exception. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } finally { newRepository.close(); originRepository.close(); treeWalk.close(); } objResponse.put("message", "Updated"); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_10, "" + randomLong); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_22, "" + appId); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_23, "" + name); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK); }
From source file:io.fabric8.maven.AbstractFabric8Mojo.java
License:Apache License
/** * Tries to default some environment variables if they are not already defined. * * This can happen if using Jenkins Workflow which doens't seem to define BUILD_URL or GIT_URL for example * * @return the value of the environment variable name if it can be found or calculated *///from www .j a v a2 s . com protected String tryDefaultAnnotationEnvVar(String envVarName) { // only do this if enabled if (extendedMetadata != null && !extendedMetadata) { return null; } MavenProject rootProject = getRootProject(); File basedir = rootProject.getBasedir(); if (basedir == null) { basedir = getProject().getBasedir(); } if (basedir == null) { basedir = new File(System.getProperty("basedir", ".")); } ProjectConfig projectConfig = ProjectConfigs.loadFromFolder(basedir); String repoName = rootProject.getArtifactId(); String userEnvVar = "JENKINS_GOGS_USER"; String username = Systems.getEnvVarOrSystemProperty(userEnvVar); if (Objects.equal("BUILD_URL", envVarName)) { String jobUrl = projectConfig.getLink("Job"); if (Strings.isNullOrBlank(jobUrl)) { String name = projectConfig.getBuildName(); if (Strings.isNullOrBlank(name)) { // lets try deduce the jenkins build name we'll generate if (Strings.isNotBlank(repoName)) { name = repoName; if (Strings.isNotBlank(username)) { name = ProjectRepositories.createBuildName(username, repoName); } else { warnIfInCDBuild("Cannot auto-default BUILD_URL as there is no environment variable `" + userEnvVar + "` defined so we can't guess the Jenkins build URL"); } } } if (Strings.isNotBlank(name)) { try { // this requires online access to kubernetes so we should silently fail if no connection String jenkinsUrl = KubernetesHelper.getServiceURLInCurrentNamespace(getKubernetes(), ServiceNames.JENKINS, "http", null, true); jobUrl = URLUtils.pathJoin(jenkinsUrl, "/job", name); } catch (Throwable e) { Throwable cause = e; boolean notFound = false; boolean connectError = false; Iterable<Throwable> it = createExceptionIterable(e); for (Throwable t : it) { connectError = t instanceof ConnectException || "No route to host".equals(t.getMessage()); notFound = t instanceof IllegalArgumentException || t.getMessage() != null && t.getMessage().startsWith("No kubernetes service could be found for name"); if (connectError || notFound) { cause = t; break; } } if (connectError) { warnIfInCDBuild("Cannot connect to Kubernetes to find jenkins service URL: " + cause.getMessage()); } else if (notFound) { // the message from the exception is good as-is warnIfInCDBuild(cause.getMessage()); } else { warnIfInCDBuild("Cannot find jenkins service URL: " + cause, cause); } } } } if (Strings.isNotBlank(jobUrl)) { String buildId = Systems.getEnvVarOrSystemProperty("BUILD_ID"); if (Strings.isNotBlank(buildId)) { jobUrl = URLUtils.pathJoin(jobUrl, buildId); } else { warnIfInCDBuild( "Cannot find BUILD_ID to create a specific jenkins build URL. So using: " + jobUrl); } } return jobUrl; } else if (Objects.equal("GIT_URL", envVarName)) { if (Strings.isNotBlank(repoName) && Strings.isNotBlank(username)) { try { // this requires online access to kubernetes so we should silently fail if no connection String gogsUrl = KubernetesHelper.getServiceURLInCurrentNamespace(getKubernetes(), ServiceNames.GOGS, "http", null, true); String rootGitUrl = URLUtils.pathJoin(gogsUrl, username, repoName); String gitCommitId = getGitCommitId(envVarName, basedir); if (Strings.isNotBlank(gitCommitId)) { rootGitUrl = URLUtils.pathJoin(rootGitUrl, "commit", gitCommitId); } return rootGitUrl; } catch (Throwable e) { Throwable cause = e; boolean notFound = false; boolean connectError = false; Iterable<Throwable> it = createExceptionIterable(e); for (Throwable t : it) { notFound = t instanceof IllegalArgumentException || t.getMessage() != null && t.getMessage().startsWith("No kubernetes service could be found for name"); connectError = t instanceof ConnectException || "No route to host".equals(t.getMessage()); if (connectError) { cause = t; break; } } if (connectError) { warnIfInCDBuild( "Cannot connect to Kubernetes to find gogs service URL: " + cause.getMessage()); } else if (notFound) { // the message from the exception is good as-is warnIfInCDBuild(cause.getMessage()); } else { warnIfInCDBuild("Cannot find gogs service URL: " + cause, cause); } } } else { warnIfInCDBuild("Cannot auto-default GIT_URL as there is no environment variable `" + userEnvVar + "` defined so we can't guess the Gogs build URL"); } /* TODO this is the git clone url; while we could try convert from it to a browse URL its probably too flaky? try { url = GitHelpers.extractGitUrl(basedir); } catch (IOException e) { warnIfInCDBuild("Failed to find git url in directory " + basedir + ". " + e, e); } if (Strings.isNotBlank(url)) { // for gogs / github style repos we trim the .git suffix for browsing return Strings.stripSuffix(url, ".git"); } */ } else if (Objects.equal("GIT_COMMIT", envVarName)) { return getGitCommitId(envVarName, basedir); } else if (Objects.equal("GIT_BRANCH", envVarName)) { Repository repository = getGitRepository(basedir, envVarName); try { if (repository != null) { return repository.getBranch(); } } catch (IOException e) { warnIfInCDBuild("Failed to find git commit id. " + e, e); } finally { if (repository != null) { repository.close(); } } } return null; }
From source file:io.fabric8.maven.AbstractFabric8Mojo.java
License:Apache License
protected String getGitCommitId(String envVarName, File basedir) { Repository repository = getGitRepository(basedir, envVarName); try {/* w w w . j av a 2 s. co m*/ if (repository != null) { getLog().info("Looking at repo with directory " + repository.getDirectory()); Iterable<RevCommit> logs = new Git(repository).log().call(); for (RevCommit rev : logs) { return rev.getName(); } warnIfInCDBuild("Cannot default " + envVarName + " no commits could be found"); } else { warnIfInCDBuild("Cannot default " + envVarName + " as no git repository could be found"); } } catch (Exception e) { warnIfInCDBuild("Failed to find git commit id. " + e, e); } finally { if (repository != null) { try { repository.close(); } catch (Exception e) { // ignore } } } return null; }
From source file:io.fabric8.maven.enricher.standard.GitEnricher.java
License:Apache License
@Override public Map<String, String> getAnnotations(Kind kind) { Map<String, String> annotations = new HashMap<>(); Repository repository = null; try {//from ww w . j a v a 2s . c om if (kind.isController() || kind == Kind.SERVICE) { // Git annotations (if git is used as SCM) repository = GitUtil.getGitRepository(getProject()); if (repository != null) { String result; String branch = repository.getBranch(); if (branch != null) { annotations.put(Annotations.Builds.GIT_BRANCH, branch); } String id = GitUtil.getGitCommitId(repository); if (id != null) { annotations.put(Annotations.Builds.GIT_COMMIT, id); } } } return annotations; } catch (IOException | GitAPIException e) { log.error("Cannot extract Git information for adding to annotations: " + e, e); return null; } finally { if (repository != null) { try { repository.close(); } catch (Exception e) { // ignore } } } }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.agent.command.impl.CleanCommandImpl.java
License:Apache License
private void handleLongFileNames(@NotNull File rootDir, @NotNull VcsException originalError) throws VcsException { List<String> files = new ArrayList<String>(); FileUtil.listFilesRecursively(rootDir, "", true, Integer.MAX_VALUE, new Predicate<File>() { public boolean apply(File f) { return true; }//ww w.java 2s .c o m }, files); int targetDirLength = rootDir.getAbsolutePath().length(); List<String> longFileNames = new ArrayList<String>(); for (String f : files) { if (targetDirLength + 1 + f.length() >= 256) longFileNames.add(f); } if (longFileNames.isEmpty()) { Loggers.VCS.info("No files with long names found"); throw originalError; } else { Loggers.VCS.info(longFileNames.size() + " files with long names found:"); for (String f : longFileNames) { Loggers.VCS.info(f); } Loggers.VCS.info("Try removing files with long names manually"); } Repository repository = null; try { repository = new RepositoryBuilder().setWorkTree(rootDir).build(); WorkingDirStatus status = getWorkingDirStatus(repository); Set<String> untracked = status.getUntracked(); for (String f : longFileNames) { if (untracked.contains(f) || status.isIgnored(f)) { FileUtil.delete(new File(rootDir, f)); Loggers.VCS.info(f + " is removed"); } else { Loggers.VCS.info("The file " + f + " is tracked, don't remove it"); } } } catch (Exception e1) { Loggers.VCS.error("Error while cleaning files with long names", e1); } finally { if (repository != null) repository.close(); } }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.agent.UpdaterImpl.java
License:Apache License
protected void removeUrlSections() throws VcsException { Repository r = null; try {//from ww w .jav a 2 s .c o m r = new RepositoryBuilder().setWorkTree(myTargetDirectory).build(); StoredConfig config = r.getConfig(); Set<String> urlSubsections = config.getSubsections("url"); for (String subsection : urlSubsections) { config.unsetSection("url", subsection); } config.save(); } catch (IOException e) { String msg = "Error while remove url.* sections"; LOG.error(msg, e); throw new VcsException(msg, e); } finally { if (r != null) r.close(); } }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.AutoCloseRepositoryCache.java
License:Apache License
/** * Releases the repository acquired via {@link #add} or {@link #get} method. * Decrements an openCounter for the repository and if it reaches 0 repository * is closed and removed from the cache. Does nothing if repository is not * present found in the cache./*from w w w . ja v a 2s . c o m*/ * @param db repository to release */ synchronized void release(@NotNull Repository db) { RepositoryCache.FileKey key = RepositoryCache.FileKey.exact(db.getDirectory(), FS.DETECTED); CachedRepository cachedRepository = myRepositories.get(key); if (cachedRepository != null && cachedRepository.getRepository() == db && cachedRepository.dec() == 0) { myRepositories.remove(key); db.close(); } }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.GitLabelingSupportTest.java
License:Apache License
public void testLabels() throws Exception { VcsRoot root = vcsRoot().withFetchUrl(getRemoteRepositoryDir("repo.git")).build(); // ensure that all revisions reachable from master are fetched buildGit().getLabelingSupport().label("test_label", "2276eaf76a658f96b5cf3eb25f3e1fda90f6b653", root, CheckoutRules.DEFAULT);/* w w w.j a v a 2 s . co m*/ Repository r = new RepositoryBuilder().setGitDir(getRemoteRepositoryDir("repo.git")).build(); RevWalk revWalk = new RevWalk(r); try { Ref tagRef = r.getTags().get("test_label"); RevTag t = revWalk.parseTag(tagRef.getObjectId()); assertEquals(t.getObject().name(), "2276eaf76a658f96b5cf3eb25f3e1fda90f6b653"); } finally { r.close(); } }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.GitLabelingSupportTest.java
License:Apache License
@Test public void tag_with_specified_username() throws Exception { VcsRoot root = vcsRoot().withFetchUrl(GitUtils.toURL(getRemoteRepositoryDir("repo.git"))) .withUsernameForTags("John Doe <john.doe@some.org>").build(); buildGit().getLabelingSupport().label("label_with_specified_username", "465ad9f630e451b9f2b782ffb09804c6a98c4bb9", root, CheckoutRules.DEFAULT); Repository r = new RepositoryBuilder().setGitDir(getRemoteRepositoryDir("repo.git")).build(); RevWalk revWalk = new RevWalk(r); try {/* ww w .j a v a2 s . c o m*/ Ref tagRef = r.getTags().get("label_with_specified_username"); RevTag t = revWalk.parseTag(tagRef.getObjectId()); PersonIdent tagger = t.getTaggerIdent(); assertEquals(tagger.getName(), "John Doe"); assertEquals(tagger.getEmailAddress(), "john.doe@some.org"); } finally { revWalk.release(); r.close(); } }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.GitLabelingSupportTest.java
License:Apache License
@Test(dataProvider = "true,false") public void should_push_all_objects_missing_in_remote_repository(boolean usePackHeuristics) throws Exception { myConfig.setUsePackHeuristic(usePackHeuristics); GitVcsSupport git = buildGit();//w w w.jav a 2 s.c o m File remoteRepoDir = getRemoteRepositoryDir("repo_for_fetch.2"); VcsRoot root = vcsRoot().withFetchUrl(remoteRepoDir).build(); makeCloneOnServer(git, root); //erase commit in the remote repository FileUtil.delete(remoteRepoDir); remoteRepoDir.mkdirs(); FileUtil.copyDir(getRemoteRepositoryDir("repo_for_fetch.1"), remoteRepoDir); //label erased commit String erasedCommit = "d47dda159b27b9a8c4cee4ce98e4435eb5b17168"; git.getLabelingSupport().label("label", erasedCommit, root, CheckoutRules.DEFAULT); //erased commit should appear in the remote repository Repository r = new RepositoryBuilder().setGitDir(remoteRepoDir).build(); RevWalk walk = new RevWalk(r); try { walk.parseCommit(ObjectId.fromString(erasedCommit)); } catch (MissingObjectException e) { fail("Not all objects were pushed, labeled commit " + erasedCommit + " is missing"); } finally { walk.release(); r.close(); } }