Example usage for org.eclipse.jgit.lib StoredConfig getBoolean

List of usage examples for org.eclipse.jgit.lib StoredConfig getBoolean

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib StoredConfig getBoolean.

Prototype

public boolean getBoolean(final String section, String subsection, final String name,
        final boolean defaultValue) 

Source Link

Document

Get a boolean value from the git config

Usage

From source file:com.gitblit.ConfigUserService.java

License:Apache License

/**
 * Reads the realm file and rebuilds the in-memory lookup tables.
 *///from ww w. j a  va2  s  .c  o  m
protected synchronized void read() {
    if (realmFile.exists() && (forceReload || (realmFile.lastModified() != lastModified))) {
        forceReload = false;
        lastModified = realmFile.lastModified();
        users.clear();
        cookies.clear();
        teams.clear();

        try {
            StoredConfig config = new FileBasedConfig(realmFile, FS.detect());
            config.load();
            Set<String> usernames = config.getSubsections(USER);
            for (String username : usernames) {
                UserModel user = new UserModel(username.toLowerCase());
                user.password = config.getString(USER, username, PASSWORD);
                user.displayName = config.getString(USER, username, DISPLAYNAME);
                user.emailAddress = config.getString(USER, username, EMAILADDRESS);
                user.accountType = AccountType.fromString(config.getString(USER, username, ACCOUNTTYPE));
                user.disabled = config.getBoolean(USER, username, DISABLED, false);
                user.organizationalUnit = config.getString(USER, username, ORGANIZATIONALUNIT);
                user.organization = config.getString(USER, username, ORGANIZATION);
                user.locality = config.getString(USER, username, LOCALITY);
                user.stateProvince = config.getString(USER, username, STATEPROVINCE);
                user.countryCode = config.getString(USER, username, COUNTRYCODE);
                user.cookie = config.getString(USER, username, COOKIE);
                if (StringUtils.isEmpty(user.cookie) && !StringUtils.isEmpty(user.password)) {
                    user.cookie = user.createCookie();
                }

                // preferences
                user.getPreferences().setLocale(config.getString(USER, username, LOCALE));
                user.getPreferences().setEmailMeOnMyTicketChanges(
                        config.getBoolean(USER, username, EMAILONMYTICKETCHANGES, true));
                user.getPreferences()
                        .setTransport(Transport.fromString(config.getString(USER, username, TRANSPORT)));

                // user roles
                Set<String> roles = new HashSet<String>(
                        Arrays.asList(config.getStringList(USER, username, ROLE)));
                user.canAdmin = roles.contains(Role.ADMIN.getRole());
                user.canFork = roles.contains(Role.FORK.getRole());
                user.canCreate = roles.contains(Role.CREATE.getRole());
                user.excludeFromFederation = roles.contains(Role.NOT_FEDERATED.getRole());

                // repository memberships
                if (!user.canAdmin) {
                    // non-admin, read permissions
                    Set<String> repositories = new HashSet<String>(
                            Arrays.asList(config.getStringList(USER, username, REPOSITORY)));
                    for (String repository : repositories) {
                        user.addRepositoryPermission(repository);
                    }
                }

                // starred repositories
                Set<String> starred = new HashSet<String>(
                        Arrays.asList(config.getStringList(USER, username, STARRED)));
                for (String repository : starred) {
                    UserRepositoryPreferences prefs = user.getPreferences()
                            .getRepositoryPreferences(repository);
                    prefs.starred = true;
                }

                // update cache
                users.put(user.username, user);
                if (!StringUtils.isEmpty(user.cookie)) {
                    cookies.put(user.cookie, user);
                }
            }

            // load the teams
            Set<String> teamnames = config.getSubsections(TEAM);
            for (String teamname : teamnames) {
                TeamModel team = new TeamModel(teamname);
                Set<String> roles = new HashSet<String>(
                        Arrays.asList(config.getStringList(TEAM, teamname, ROLE)));
                team.canAdmin = roles.contains(Role.ADMIN.getRole());
                team.canFork = roles.contains(Role.FORK.getRole());
                team.canCreate = roles.contains(Role.CREATE.getRole());
                team.accountType = AccountType.fromString(config.getString(TEAM, teamname, ACCOUNTTYPE));

                if (!team.canAdmin) {
                    // non-admin team, read permissions
                    team.addRepositoryPermissions(
                            Arrays.asList(config.getStringList(TEAM, teamname, REPOSITORY)));
                }
                team.addUsers(Arrays.asList(config.getStringList(TEAM, teamname, USER)));
                team.addMailingLists(Arrays.asList(config.getStringList(TEAM, teamname, MAILINGLIST)));
                team.preReceiveScripts.addAll(Arrays.asList(config.getStringList(TEAM, teamname, PRERECEIVE)));
                team.postReceiveScripts
                        .addAll(Arrays.asList(config.getStringList(TEAM, teamname, POSTRECEIVE)));

                teams.put(team.name.toLowerCase(), team);

                // set the teams on the users
                for (String user : team.users) {
                    UserModel model = users.get(user);
                    if (model != null) {
                        model.teams.add(team);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(MessageFormat.format("Failed to read {0}", realmFile), e);
        }
    }
}

From source file:com.gitblit.manager.RepositoryManager.java

License:Apache License

/**
 * Create a repository model from the configuration and repository data.
 *
 * @param repositoryName//from www . j  ava  2s.c  om
 * @return a repositoryModel or null if the repository does not exist
 */
private RepositoryModel loadRepositoryModel(String repositoryName) {
    Repository r = getRepository(repositoryName);
    if (r == null) {
        return null;
    }
    RepositoryModel model = new RepositoryModel();
    model.isBare = r.isBare();
    File basePath = getRepositoriesFolder();
    if (model.isBare) {
        model.name = com.gitblit.utils.FileUtils.getRelativePath(basePath, r.getDirectory());
    } else {
        model.name = com.gitblit.utils.FileUtils.getRelativePath(basePath, r.getDirectory().getParentFile());
    }
    if (StringUtils.isEmpty(model.name)) {
        // Repository is NOT located relative to the base folder because it
        // is symlinked.  Use the provided repository name.
        model.name = repositoryName;
    }
    model.projectPath = StringUtils.getFirstPathElement(repositoryName);

    StoredConfig config = r.getConfig();
    boolean hasOrigin = false;

    if (config != null) {
        // Initialize description from description file
        hasOrigin = !StringUtils.isEmpty(config.getString("remote", "origin", "url"));
        if (getConfig(config, "description", null) == null) {
            File descFile = new File(r.getDirectory(), "description");
            if (descFile.exists()) {
                String desc = com.gitblit.utils.FileUtils.readContent(descFile,
                        System.getProperty("line.separator"));
                if (!desc.toLowerCase().startsWith("unnamed repository")) {
                    config.setString(Constants.CONFIG_GITBLIT, null, "description", desc);
                }
            }
        }
        model.description = getConfig(config, "description", "");
        model.originRepository = getConfig(config, "originRepository", null);
        model.addOwners(ArrayUtils.fromString(getConfig(config, "owner", "")));
        model.acceptNewPatchsets = getConfig(config, "acceptNewPatchsets", true);
        model.acceptNewTickets = getConfig(config, "acceptNewTickets", true);
        model.requireApproval = getConfig(config, "requireApproval",
                settings.getBoolean(Keys.tickets.requireApproval, false));
        model.mergeTo = getConfig(config, "mergeTo", null);
        model.mergeType = MergeType
                .fromName(getConfig(config, "mergeType", settings.getString(Keys.tickets.mergeType, null)));
        model.useIncrementalPushTags = getConfig(config, "useIncrementalPushTags", false);
        model.incrementalPushTagPrefix = getConfig(config, "incrementalPushTagPrefix", null);
        model.allowForks = getConfig(config, "allowForks", true);
        model.accessRestriction = AccessRestrictionType.fromName(getConfig(config, "accessRestriction",
                settings.getString(Keys.git.defaultAccessRestriction, "PUSH")));
        model.authorizationControl = AuthorizationControl.fromName(getConfig(config, "authorizationControl",
                settings.getString(Keys.git.defaultAuthorizationControl, null)));
        model.verifyCommitter = getConfig(config, "verifyCommitter", false);
        model.showRemoteBranches = getConfig(config, "showRemoteBranches", hasOrigin);
        model.isFrozen = getConfig(config, "isFrozen", false);
        model.skipSizeCalculation = getConfig(config, "skipSizeCalculation", false);
        model.skipSummaryMetrics = getConfig(config, "skipSummaryMetrics", false);
        model.commitMessageRenderer = CommitMessageRenderer.fromName(getConfig(config, "commitMessageRenderer",
                settings.getString(Keys.web.commitMessageRenderer, null)));
        model.federationStrategy = FederationStrategy.fromName(getConfig(config, "federationStrategy", null));
        model.federationSets = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "federationSets")));
        model.isFederated = getConfig(config, "isFederated", false);
        model.gcThreshold = getConfig(config, "gcThreshold",
                settings.getString(Keys.git.defaultGarbageCollectionThreshold, "500KB"));
        model.gcPeriod = getConfig(config, "gcPeriod",
                settings.getInteger(Keys.git.defaultGarbageCollectionPeriod, 7));
        try {
            model.lastGC = new SimpleDateFormat(Constants.ISO8601)
                    .parse(getConfig(config, "lastGC", "1970-01-01'T'00:00:00Z"));
        } catch (Exception e) {
            model.lastGC = new Date(0);
        }
        model.maxActivityCommits = getConfig(config, "maxActivityCommits",
                settings.getInteger(Keys.web.maxActivityCommits, 0));
        model.origin = config.getString("remote", "origin", "url");
        if (model.origin != null) {
            model.origin = model.origin.replace('\\', '/');
            model.isMirror = config.getBoolean("remote", "origin", "mirror", false);
        }
        model.preReceiveScripts = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "preReceiveScript")));
        model.postReceiveScripts = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "postReceiveScript")));
        model.mailingLists = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "mailingList")));
        model.indexedBranches = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "indexBranch")));
        model.metricAuthorExclusions = new ArrayList<String>(
                Arrays.asList(config.getStringList(Constants.CONFIG_GITBLIT, null, "metricAuthorExclusions")));

        // Custom defined properties
        model.customFields = new LinkedHashMap<String, String>();
        for (String aProperty : config.getNames(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS)) {
            model.customFields.put(aProperty,
                    config.getString(Constants.CONFIG_GITBLIT, Constants.CONFIG_CUSTOM_FIELDS, aProperty));
        }
    }
    model.HEAD = JGitUtils.getHEADRef(r);
    if (StringUtils.isEmpty(model.mergeTo)) {
        model.mergeTo = model.HEAD;
    }
    model.availableRefs = JGitUtils.getAvailableHeadTargets(r);
    model.sparkleshareId = JGitUtils.getSparkleshareId(r);
    model.hasCommits = JGitUtils.hasCommits(r);
    updateLastChangeFields(r, model);
    r.close();

    if (StringUtils.isEmpty(model.originRepository) && model.origin != null
            && model.origin.startsWith("file://")) {
        // repository was cloned locally... perhaps as a fork
        try {
            File folder = new File(new URI(model.origin));
            String originRepo = com.gitblit.utils.FileUtils.getRelativePath(getRepositoriesFolder(), folder);
            if (!StringUtils.isEmpty(originRepo)) {
                // ensure origin still exists
                File repoFolder = new File(getRepositoriesFolder(), originRepo);
                if (repoFolder.exists()) {
                    model.originRepository = originRepo.toLowerCase();

                    // persist the fork origin
                    updateConfiguration(r, model);
                }
            }
        } catch (URISyntaxException e) {
            logger.error("Failed to determine fork for " + model, e);
        }
    }
    return model;
}

From source file:org.eclipse.oomph.gitbash.decorators.BranchDecorator.java

License:Open Source License

private String getDecoration(org.eclipse.egit.ui.internal.repository.tree.RefNode node) {
    String branchName = Repository.shortenRefName(node.getObject().getName());
    Repository repository = node.getRepository();
    StoredConfig config = repository.getConfig();

    String branch = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
            ConfigConstants.CONFIG_KEY_MERGE);

    if (branch != null) {
        String remote = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                ConfigConstants.CONFIG_KEY_REMOTE);

        boolean rebaseFlag = config.getBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                ConfigConstants.CONFIG_KEY_REBASE, false);

        if (branch.startsWith(DEFAULT_PATH)) {
            branch = branch.substring(DEFAULT_PATH.length());
        }/*from  w  w  w.j  a  v  a 2  s.  c  o m*/

        String prefix = ".".equals(remote) ? "" : remote + "/";
        String result = (rebaseFlag ? "REBASE" : "MERGE") + ": " + prefix + branch;

        try {
            BranchTrackingStatus trackingStatus = BranchTrackingStatus.of(repository, branchName);
            if (trackingStatus != null
                    && (trackingStatus.getAheadCount() != 0 || trackingStatus.getBehindCount() != 0)) {
                result += " " + formatBranchTrackingStatus(trackingStatus);
            }
        } catch (Throwable t) {
            //$FALL-THROUGH$
        }

        return result;
    }

    return null;
}

From source file:org.flowerplatform.web.git.GitService.java

License:Open Source License

@RemoteInvocation
public ConfigBranchPageDto getConfigBranchData(ServiceInvocationContext context, List<PathFragment> path) {
    try {//from  w w  w. ja va  2  s  .  c om
        RefNode node = (RefNode) GenericTreeStatefulService.getNodeByPathFor(path, null);
        Repository repository = node.getRepository();

        StoredConfig config = repository.getConfig();

        ConfigBranchPageDto dto = new ConfigBranchPageDto();

        Ref branch = (Ref) node.getRef();
        dto.setRef(new GitRef(branch.getName(), Repository.shortenRefName(branch.getName())));

        List<RemoteConfig> remotes = getAllRemotes(context, path);

        String branchName = branch.getName().substring(Constants.R_HEADS.length());
        String branchConfig = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                ConfigConstants.CONFIG_KEY_MERGE);

        String remoteConfig = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                ConfigConstants.CONFIG_KEY_REMOTE);
        if (remoteConfig == null) {
            remoteConfig = "";
        }
        if (remotes != null) {
            dto.setRemotes(remotes);

            for (RemoteConfig remote : remotes) {
                if (remote.getName().equals(remoteConfig)) {
                    List<Object> branches = getBranches(context, remote.getUri());
                    if (branches != null) {
                        @SuppressWarnings("unchecked")
                        List<GitRef> refs = (List<GitRef>) branches.get(0);
                        for (GitRef ref : refs) {
                            if (ref.getName().equals(branchConfig)) {
                                dto.setSelectedRef(ref);
                                break;
                            }
                        }
                        dto.setRefs(refs);
                    }
                    dto.setSelectedRemote(remote);
                    break;
                }
            }
        }

        boolean rebaseFlag = config.getBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                ConfigConstants.CONFIG_KEY_REBASE, false);
        dto.setRebase(rebaseFlag);

        return dto;
    } catch (Exception e) {
        logger.debug(CommonPlugin.getInstance().getMessage("error"), path, e);
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR));
        return null;
    }
}

From source file:org.uberfire.java.nio.fs.jgit.JGitCloneTest.java

License:Apache License

@Test
public void cloneNotMirrorRepoConfigTest() throws IOException {
    final File parentFolder = createTempDirectory();

    final File gitSource = new File(parentFolder, SOURCE_GIT + ".git");

    final File gitTarget = new File(parentFolder, TARGET_GIT + ".git");

    final Git origin = setupGitRepo(gitSource, null);

    boolean isMirror = false;
    boolean sslVerify = true;
    final Git clonedNotMirror = new Clone(gitTarget, gitSource.getAbsolutePath(), isMirror, null,
            CredentialsProvider.getDefault(), null, null, sslVerify).execute().get();

    assertThat(clonedNotMirror).isNotNull();

    StoredConfig config = clonedNotMirror.getRepository().getConfig();

    assertNotEquals(Clone.REFS_MIRRORED, config.getString("remote", "origin", "fetch"));
    assertNull(config.getString("remote", "origin", "mirror"));
    assertEquals(gitSource.getAbsolutePath(), config.getString("remote", "origin", "url"));

    boolean missingDefaultValue = true;
    assertEquals(missingDefaultValue, config.getBoolean("http", null, "sslVerify", missingDefaultValue));
}

From source file:org.uberfire.java.nio.fs.jgit.JGitCloneTest.java

License:Apache License

@Test
public void cloneMirrorRepoNoSSLVerifyConfigTest() throws IOException {
    final File parentFolder = createTempDirectory();

    final File gitSource = new File(parentFolder, SOURCE_GIT + ".git");

    final File gitTarget = new File(parentFolder, TARGET_GIT + ".git");

    final Git origin = setupGitRepo(gitSource, null);

    assertTrue(provider.config.isSslVerify());

    boolean isMirror = true;
    boolean sslVerify = false;
    final Git clonedMirror = new Clone(gitTarget, gitSource.getAbsolutePath(), isMirror, null,
            CredentialsProvider.getDefault(), null, null, sslVerify).execute().get();

    assertThat(clonedMirror).isNotNull();

    StoredConfig config = clonedMirror.getRepository().getConfig();

    assertEquals(Clone.REFS_MIRRORED, config.getString("remote", "origin", "fetch"));
    assertNull(config.getString("remote", "origin", "mirror"));
    assertEquals(gitSource.getAbsolutePath(), config.getString("remote", "origin", "url"));
    assertEquals(sslVerify, config.getBoolean("http", null, "sslVerify", !sslVerify));

}