List of usage examples for org.eclipse.jgit.storage.file FileBasedConfig getString
public String getString(final String section, String subsection, final String name)
From source file:com.gitblit.LuceneExecutor.java
License:Apache License
/** * Updates a repository index incrementally from the last indexed commits. * //from ww w . j a v a 2 s . com * @param model * @param repository * @return IndexResult */ private IndexResult updateIndex(RepositoryModel model, Repository repository) { IndexResult result = new IndexResult(); try { FileBasedConfig config = getConfig(repository); config.load(); // build a quick lookup of annotated tags Map<String, List<String>> tags = new HashMap<String, List<String>>(); for (RefModel tag : JGitUtils.getTags(repository, false, -1)) { if (!tag.isAnnotatedTag()) { // skip non-annotated tags continue; } if (!tags.containsKey(tag.getObjectId())) { tags.put(tag.getReferencedObjectId().getName(), new ArrayList<String>()); } tags.get(tag.getReferencedObjectId().getName()).add(tag.displayName); } // detect branch deletion // first assume all branches are deleted and then remove each // existing branch from deletedBranches during indexing Set<String> deletedBranches = new TreeSet<String>(); for (String alias : config.getNames(CONF_ALIAS)) { String branch = config.getString(CONF_ALIAS, null, alias); deletedBranches.add(branch); } // get the local branches List<RefModel> branches = JGitUtils.getLocalBranches(repository, true, -1); // sort them by most recently updated Collections.sort(branches, new Comparator<RefModel>() { @Override public int compare(RefModel ref1, RefModel ref2) { return ref2.getDate().compareTo(ref1.getDate()); } }); // reorder default branch to first position RefModel defaultBranch = null; ObjectId defaultBranchId = JGitUtils.getDefaultBranch(repository); for (RefModel branch : branches) { if (branch.getObjectId().equals(defaultBranchId)) { defaultBranch = branch; break; } } branches.remove(defaultBranch); branches.add(0, defaultBranch); // walk through each branches for (RefModel branch : branches) { String branchName = branch.getName(); boolean indexBranch = false; if (model.indexedBranches.contains(com.gitblit.Constants.DEFAULT_BRANCH) && branch.equals(defaultBranch)) { // indexing "default" branch indexBranch = true; } else if (IssueUtils.GB_ISSUES.equals(branch)) { // update issues modified on the GB_ISSUES branch // note: this is different than reindex indexBranch = true; } else { // normal explicit branch check indexBranch = model.indexedBranches.contains(branch.getName()); } // if this branch is not specifically indexed then skip if (!indexBranch) { continue; } // remove this branch from the deletedBranches set deletedBranches.remove(branchName); // determine last commit String keyName = getBranchKey(branchName); String lastCommit = config.getString(CONF_BRANCH, null, keyName); List<RevCommit> revs; if (StringUtils.isEmpty(lastCommit)) { // new branch/unindexed branch, get all commits on branch revs = JGitUtils.getRevLog(repository, branchName, 0, -1); } else { // pre-existing branch, get changes since last commit revs = JGitUtils.getRevLog(repository, lastCommit, branchName); } if (revs.size() > 0) { result.branchCount += 1; } // track the issue ids that we have already indexed Set<String> indexedIssues = new TreeSet<String>(); // reverse the list of commits so we start with the first commit Collections.reverse(revs); for (RevCommit commit : revs) { if (IssueUtils.GB_ISSUES.equals(branch)) { // only index an issue once during updateIndex String issueId = commit.getShortMessage().substring(2).trim(); if (indexedIssues.contains(issueId)) { continue; } indexedIssues.add(issueId); IssueModel issue = IssueUtils.getIssue(repository, issueId); if (issue == null) { // issue was deleted, remove from index if (!deleteIssue(model.name, issueId)) { logger.error(MessageFormat.format("Failed to delete issue {0} from Lucene index!", issueId)); } } else { // issue was updated index(model.name, issue); result.issueCount++; } } else { // index a commit result.add(index(model.name, repository, branchName, commit)); } } // update the config config.setInt(CONF_INDEX, null, CONF_VERSION, INDEX_VERSION); config.setString(CONF_ALIAS, null, keyName, branchName); config.setString(CONF_BRANCH, null, keyName, branch.getObjectId().getName()); config.save(); } // the deletedBranches set will normally be empty by this point // unless a branch really was deleted and no longer exists if (deletedBranches.size() > 0) { for (String branch : deletedBranches) { IndexWriter writer = getIndexWriter(model.name); writer.deleteDocuments(new Term(FIELD_BRANCH, branch)); writer.commit(); } } result.success = true; } catch (Throwable t) { logger.error(MessageFormat.format("Exception while updating {0} Lucene index", model.name), t); } return result; }
From source file:com.gitblit.service.LuceneService.java
License:Apache License
/** * Updates a repository index incrementally from the last indexed commits. * * @param model//from w w w . j a v a 2 s.co m * @param repository * @return IndexResult */ private IndexResult updateIndex(RepositoryModel model, Repository repository) { IndexResult result = new IndexResult(); try { FileBasedConfig config = getConfig(repository); config.load(); // build a quick lookup of annotated tags Map<String, List<String>> tags = new HashMap<String, List<String>>(); for (RefModel tag : JGitUtils.getTags(repository, false, -1)) { if (!tag.isAnnotatedTag()) { // skip non-annotated tags continue; } if (!tags.containsKey(tag.getObjectId().getName())) { tags.put(tag.getReferencedObjectId().getName(), new ArrayList<String>()); } tags.get(tag.getReferencedObjectId().getName()).add(tag.displayName); } // detect branch deletion // first assume all branches are deleted and then remove each // existing branch from deletedBranches during indexing Set<String> deletedBranches = new TreeSet<String>(); for (String alias : config.getNames(CONF_ALIAS)) { String branch = config.getString(CONF_ALIAS, null, alias); deletedBranches.add(branch); } // get the local branches List<RefModel> branches = JGitUtils.getLocalBranches(repository, true, -1); // sort them by most recently updated Collections.sort(branches, new Comparator<RefModel>() { @Override public int compare(RefModel ref1, RefModel ref2) { return ref2.getDate().compareTo(ref1.getDate()); } }); // reorder default branch to first position RefModel defaultBranch = null; ObjectId defaultBranchId = JGitUtils.getDefaultBranch(repository); for (RefModel branch : branches) { if (branch.getObjectId().equals(defaultBranchId)) { defaultBranch = branch; break; } } branches.remove(defaultBranch); branches.add(0, defaultBranch); // walk through each branches for (RefModel branch : branches) { String branchName = branch.getName(); boolean indexBranch = false; if (model.indexedBranches.contains(com.gitblit.Constants.DEFAULT_BRANCH) && branch.equals(defaultBranch)) { // indexing "default" branch indexBranch = true; } else if (branch.getName().startsWith(com.gitblit.Constants.R_META)) { // ignore internal meta branches indexBranch = false; } else { // normal explicit branch check indexBranch = model.indexedBranches.contains(branch.getName()); } // if this branch is not specifically indexed then skip if (!indexBranch) { continue; } // remove this branch from the deletedBranches set deletedBranches.remove(branchName); // determine last commit String keyName = getBranchKey(branchName); String lastCommit = config.getString(CONF_BRANCH, null, keyName); List<RevCommit> revs; if (StringUtils.isEmpty(lastCommit)) { // new branch/unindexed branch, get all commits on branch revs = JGitUtils.getRevLog(repository, branchName, 0, -1); } else { // pre-existing branch, get changes since last commit revs = JGitUtils.getRevLog(repository, lastCommit, branchName); } if (revs.size() > 0) { result.branchCount += 1; } // reverse the list of commits so we start with the first commit Collections.reverse(revs); for (RevCommit commit : revs) { // index a commit result.add(index(model.name, repository, branchName, commit)); } // update the config config.setString(CONF_ALIAS, null, keyName, branchName); config.setString(CONF_BRANCH, null, keyName, branch.getObjectId().getName()); config.save(); } // the deletedBranches set will normally be empty by this point // unless a branch really was deleted and no longer exists if (deletedBranches.size() > 0) { for (String branch : deletedBranches) { IndexWriter writer = getIndexWriter(model.name); writer.deleteDocuments(new Term(FIELD_BRANCH, branch)); writer.commit(); } } result.success = true; } catch (Throwable t) { logger.error(MessageFormat.format("Exception while updating {0} Lucene index", model.name), t); } return result; }
From source file:com.google.gerrit.pgm.init.UpgradeFrom2_0_xTest.java
License:Apache License
@Test public void testUpgrade() throws IOException, ConfigInvalidException { final Path p = newSitePath(); final SitePaths site = new SitePaths(p); assertTrue(site.isNew);/*w w w .j a va2 s . c o m*/ FileUtil.mkdirsOrDie(site.etc_dir, "Failed to create"); for (String n : UpgradeFrom2_0_x.etcFiles) { Files.write(p.resolve(n), ("# " + n + "\n").getBytes(UTF_8)); } FileBasedConfig old = new FileBasedConfig(p.resolve("gerrit.config").toFile(), FS.DETECTED); old.setString("ldap", null, "username", "ldap.user"); old.setString("ldap", null, "password", "ldap.s3kr3t"); old.setString("sendemail", null, "smtpUser", "email.user"); old.setString("sendemail", null, "smtpPass", "email.s3kr3t"); old.save(); final InMemorySecureStore secureStore = new InMemorySecureStore(); final InitFlags flags = new InitFlags(site, secureStore, Collections.<String>emptyList()); final ConsoleUI ui = createStrictMock(ConsoleUI.class); Section.Factory sections = new Section.Factory() { @Override public Section get(String name, String subsection) { return new Section(flags, site, secureStore, ui, name, subsection); } }; expect(ui.yesno(eq(true), eq("Upgrade '%s'"), eq(p.toAbsolutePath().normalize()))).andReturn(true); replay(ui); UpgradeFrom2_0_x u = new UpgradeFrom2_0_x(site, flags, ui, sections); assertTrue(u.isNeedUpgrade()); u.run(); assertFalse(u.isNeedUpgrade()); verify(ui); for (String n : UpgradeFrom2_0_x.etcFiles) { if ("gerrit.config".equals(n) || "secure.config".equals(n)) { continue; } try (InputStream in = Files.newInputStream(site.etc_dir.resolve(n))) { assertEquals("# " + n + "\n", new String(ByteStreams.toByteArray(in), UTF_8)); } } FileBasedConfig cfg = new FileBasedConfig(site.gerrit_config.toFile(), FS.DETECTED); cfg.load(); assertEquals("email.user", cfg.getString("sendemail", null, "smtpUser")); assertNull(cfg.getString("sendemail", null, "smtpPass")); assertEquals("email.s3kr3t", secureStore.get("sendemail", null, "smtpPass")); assertEquals("ldap.user", cfg.getString("ldap", null, "username")); assertNull(cfg.getString("ldap", null, "password")); assertEquals("ldap.s3kr3t", secureStore.get("ldap", null, "password")); u.run(); }
From source file:com.google.gerrit.pgm.SwitchSecureStore.java
License:Apache License
private static String getSecureStoreClassFromGerritConfig(SitePaths sitePaths) { FileBasedConfig cfg = new FileBasedConfig(sitePaths.gerrit_config.toFile(), FS.DETECTED); try {/*from w w w. ja va 2s . co m*/ cfg.load(); } catch (IOException | ConfigInvalidException e) { throw new RuntimeException("Cannot read gerrit.config file", e); } return cfg.getString("gerrit", null, "secureStoreClass"); }
From source file:com.google.gerrit.server.config.GerritServerConfigModule.java
License:Apache License
private static String getSecureStoreFromGerritConfig(final Path sitePath) { AbstractModule m = new AbstractModule() { @Override/*from w w w. j a va 2 s . c o m*/ protected void configure() { bind(Path.class).annotatedWith(SitePath.class).toInstance(sitePath); bind(SitePaths.class); } }; Injector injector = Guice.createInjector(m); SitePaths site = injector.getInstance(SitePaths.class); FileBasedConfig cfg = new FileBasedConfig(site.gerrit_config.toFile(), FS.DETECTED); if (!cfg.getFile().exists()) { return DefaultSecureStore.class.getName(); } try { cfg.load(); String className = cfg.getString("gerrit", null, "secureStoreClass"); return nullToDefault(className); } catch (IOException | ConfigInvalidException e) { throw new ProvisionException(e.getMessage(), e); } }
From source file:com.google.gitiles.GitilesFilter.java
License:Open Source License
private void setDefaultFields(FilterConfig config) throws ServletException { if (renderer != null && urls != null && accessFactory != null && resolver != null && visibilityCache != null) { return;//from w ww . ja v a 2 s . c o m } String configPath = config.getInitParameter(CONFIG_PATH_PARAM); if (configPath == null) { throw new ServletException("Missing required parameter " + configPath); } FileBasedConfig jgitConfig = new FileBasedConfig(new File(configPath), FS.DETECTED); try { jgitConfig.load(); } catch (IOException e) { throw new ServletException(e); } catch (ConfigInvalidException e) { throw new ServletException(e); } if (renderer == null) { String staticPrefix = config.getServletContext().getContextPath() + STATIC_PREFIX; String customTemplates = jgitConfig.getString("gitiles", null, "customTemplates"); // TODO(dborowitz): Automatically set to true when run with mvn jetty:run. if (jgitConfig.getBoolean("gitiles", null, "reloadTemplates", false)) { renderer = new DebugRenderer(staticPrefix, customTemplates, Joiner.on(File.separatorChar).join(System.getProperty("user.dir"), "gitiles-servlet", "src", "main", "resources", "com", "google", "gitiles", "templates")); } else { renderer = new DefaultRenderer(staticPrefix, Renderer.toFileURL(customTemplates)); } } if (urls == null) { try { urls = new DefaultUrls(jgitConfig.getString("gitiles", null, "canonicalHostName"), getBaseGitUrl(jgitConfig), getGerritUrl(jgitConfig)); } catch (UnknownHostException e) { throw new ServletException(e); } } linkifier = new Linkifier(urls); if (accessFactory == null || resolver == null) { String basePath = jgitConfig.getString("gitiles", null, "basePath"); if (basePath == null) { throw new ServletException("gitiles.basePath not set"); } boolean exportAll = jgitConfig.getBoolean("gitiles", null, "exportAll", false); FileResolver<HttpServletRequest> fileResolver; if (resolver == null) { fileResolver = new FileResolver<HttpServletRequest>(new File(basePath), exportAll); resolver = wrapResolver(fileResolver); } else if (resolver instanceof FileResolver) { fileResolver = (FileResolver<HttpServletRequest>) resolver; } else { fileResolver = null; } if (accessFactory == null) { checkState(fileResolver != null, "need a FileResolver when GitilesAccess.Factory not set"); try { accessFactory = new DefaultAccess.Factory(new File(basePath), getBaseGitUrl(jgitConfig), fileResolver); } catch (IOException e) { throw new ServletException(e); } } } if (visibilityCache == null) { if (jgitConfig.getSubsections("cache").contains("visibility")) { visibilityCache = new VisibilityCache(false, ConfigUtil.getCacheBuilder(jgitConfig, "visibility")); } else { visibilityCache = new VisibilityCache(false); } } }
From source file:com.googlesource.gerrit.plugins.github.oauth.OAuthWebFilter.java
License:Apache License
private boolean updateConfigSection(FileBasedConfig config, String section, String user, String password) { String configUser = config.getString("remote", section, "username"); String configPassword = config.getString("remote", section, "password"); if (!StringUtils.equals(configUser, user) || StringUtils.equals(configPassword, password)) { return false; }//from w ww . j a v a 2 s. co m config.setString("remote", section, "username", user); config.setString("remote", section, "password", password); return true; }
From source file:com.googlesource.gerrit.plugins.hooks.workflow.GerritHookFilterChangeState.java
License:Apache License
private List<Transition> loadTransitions() { File configFile = new File(sitePath, "etc/issue-state-transition.config"); FileBasedConfig cfg = new FileBasedConfig(configFile, FS.DETECTED); try {//from w w w . j a v a 2 s . co m cfg.load(); } catch (IOException e) { log.error("Cannot load transitions configuration file " + cfg, e); return Collections.emptyList(); } catch (ConfigInvalidException e) { log.error("Invalid transitions configuration file" + cfg, e); return Collections.emptyList(); } List<Transition> transitions = new ArrayList<Transition>(); Set<String> sections = cfg.getSubsections("action"); for (String section : sections) { List<Condition> conditions = new ArrayList<Condition>(); Set<String> keys = cfg.getNames("action", section); for (String key : keys) { String val = cfg.getString("action", section, key); conditions.add(new Condition(key.trim(), val.trim().split(","))); } transitions.add(new Transition(toAction(section), conditions)); } return transitions; }
From source file:com.googlesource.gerrit.plugins.motd.SubnetConfig.java
License:Apache License
public SubnetConfig(final FileBasedConfig c, final String name) { this.motd = c.getString("subnet", name, "motd"); if (this.motd == null) { this.motd = ""; }//from w w w .j a v a 2s .co m this.subnet = name; }
From source file:com.palantir.gerrit.gerritci.servlets.ConfigServlet.java
License:Apache License
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { if (currentUser.get().getCapabilities().canAdministrateServer() == false) { res.setStatus(403);/* w ww . j a v a 2 s . c om*/ return; } FileBasedConfig cfg = new FileBasedConfig(new File(sitePaths.etc_dir, "gerrit-ci.config"), FS.DETECTED); try { cfg.load(); } catch (ConfigInvalidException e) { logger.error("Received GET Request. Error loading gerrit-ci.config file:", e); } JsonObject params = new JsonObject(); params.addProperty("jenkinsURL", cfg.getString("Settings", "Jenkins", "jenkinsURL")); params.addProperty("jenkinsUser", cfg.getString("Settings", "Jenkins", "jenkinsUser")); params.addProperty("jenkinsPassword", cfg.getString("Settings", "Jenkins", "jenkinsPassword")); params.addProperty("gerritUser", cfg.getString("Settings", "Jenkins", "gerritUser")); params.addProperty("credentialsId", cfg.getString("Settings", "Jenkins", "credentialsId")); res.setContentType("application/json"); res.setCharacterEncoding("UTF-8"); res.getWriter().write(params.toString()); }