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

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

Introduction

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

Prototype

public void setStringList(final String section, final String subsection, final String name,
        final List<String> values) 

Source Link

Document

Set a configuration value.

Usage

From source file:com.gitblit.AddIndexedBranch.java

License:Apache License

public static void main(String... args) {
    Params params = new Params();
    CmdLineParser parser = new CmdLineParser(params);
    try {//w ww. j  a  v a2s  .c o  m
        parser.parseArgument(args);
    } catch (CmdLineException t) {
        System.err.println(t.getMessage());
        parser.printUsage(System.out);
        return;
    }

    // create a lowercase set of excluded repositories
    Set<String> exclusions = new TreeSet<String>();
    for (String exclude : params.exclusions) {
        exclusions.add(exclude.toLowerCase());
    }

    // determine available repositories
    File folder = new File(params.folder);
    List<String> repoList = JGitUtils.getRepositoryList(folder, false, true, -1, null);

    int modCount = 0;
    int skipCount = 0;
    for (String repo : repoList) {
        boolean skip = false;
        for (String exclusion : exclusions) {
            if (StringUtils.fuzzyMatch(repo, exclusion)) {
                skip = true;
                break;
            }
        }

        if (skip) {
            System.out.println("skipping " + repo);
            skipCount++;
            continue;
        }

        try {
            // load repository config
            File gitDir = FileKey.resolve(new File(folder, repo), FS.DETECTED);
            Repository repository = new FileRepositoryBuilder().setGitDir(gitDir).build();
            StoredConfig config = repository.getConfig();
            config.load();

            Set<String> indexedBranches = new LinkedHashSet<String>();

            // add all local branches to index
            if (params.addAllLocalBranches) {
                List<RefModel> list = JGitUtils.getLocalBranches(repository, true, -1);
                for (RefModel refModel : list) {
                    System.out.println(MessageFormat.format("adding [gitblit] indexBranch={0} for {1}",
                            refModel.getName(), repo));
                    indexedBranches.add(refModel.getName());
                }
            } else {
                // add only one branch to index ('default' if not specified)
                System.out.println(
                        MessageFormat.format("adding [gitblit] indexBranch={0} for {1}", params.branch, repo));
                indexedBranches.add(params.branch);
            }

            String[] branches = config.getStringList("gitblit", null, "indexBranch");
            if (!ArrayUtils.isEmpty(branches)) {
                for (String branch : branches) {
                    indexedBranches.add(branch);
                }
            }
            config.setStringList("gitblit", null, "indexBranch", new ArrayList<String>(indexedBranches));
            config.save();
            modCount++;
        } catch (Exception e) {
            System.err.println(repo);
            e.printStackTrace();
        }
    }

    System.out.println(
            MessageFormat.format("updated {0} repository configurations, skipped {1}", modCount, skipCount));
}

From source file:com.gitblit.client.GitblitManager.java

License:Apache License

@Override
public boolean saveRegistration(String name, GitblitRegistration reg) {
    try {/*from  w  w  w.j  a  v a  2 s.  c om*/
        StoredConfig config = getConfig();
        if (!StringUtils.isEmpty(name) && !name.equals(reg.name)) {
            // delete old registration
            registrations.remove(name);
            config.unsetSection(SERVER, name);
        }

        // update registration
        config.setString(SERVER, reg.name, "url", reg.url);
        config.setString(SERVER, reg.name, "account", reg.account);
        if (reg.savePassword) {
            config.setString(SERVER, reg.name, "password",
                    Base64.encodeBytes(new String(reg.password).getBytes("UTF-8")));
        } else {
            config.setString(SERVER, reg.name, "password", "");
        }
        if (reg.lastLogin != null) {
            config.setString(SERVER, reg.name, "lastLogin", dateFormat.format(reg.lastLogin));
        }
        // serialize the feed definitions
        List<String> definitions = new ArrayList<String>();
        for (FeedModel feed : reg.feeds) {
            definitions.add(feed.toString());
        }
        if (definitions.size() > 0) {
            config.setStringList(SERVER, reg.name, FEED, definitions);
        }
        config.save();
        return true;
    } catch (Throwable t) {
        Utils.showException(GitblitManager.this, t);
    }
    return false;
}

From source file:com.gitblit.ConfigUserService.java

License:Apache License

/**
 * Writes the properties file.//  w  w  w . ja va2  s  . c  om
 *
 * @throws IOException
 */
private synchronized void write() throws IOException {
    // Write a temporary copy of the users file
    File realmFileCopy = new File(realmFile.getAbsolutePath() + ".tmp");

    StoredConfig config = new FileBasedConfig(realmFileCopy, FS.detect());

    // write users
    for (UserModel model : users.values()) {
        if (!StringUtils.isEmpty(model.password)) {
            config.setString(USER, model.username, PASSWORD, model.password);
        }
        if (!StringUtils.isEmpty(model.cookie)) {
            config.setString(USER, model.username, COOKIE, model.cookie);
        }
        if (!StringUtils.isEmpty(model.displayName)) {
            config.setString(USER, model.username, DISPLAYNAME, model.displayName);
        }
        if (!StringUtils.isEmpty(model.emailAddress)) {
            config.setString(USER, model.username, EMAILADDRESS, model.emailAddress);
        }
        if (model.accountType != null) {
            config.setString(USER, model.username, ACCOUNTTYPE, model.accountType.name());
        }
        if (!StringUtils.isEmpty(model.organizationalUnit)) {
            config.setString(USER, model.username, ORGANIZATIONALUNIT, model.organizationalUnit);
        }
        if (!StringUtils.isEmpty(model.organization)) {
            config.setString(USER, model.username, ORGANIZATION, model.organization);
        }
        if (!StringUtils.isEmpty(model.locality)) {
            config.setString(USER, model.username, LOCALITY, model.locality);
        }
        if (!StringUtils.isEmpty(model.stateProvince)) {
            config.setString(USER, model.username, STATEPROVINCE, model.stateProvince);
        }
        if (!StringUtils.isEmpty(model.countryCode)) {
            config.setString(USER, model.username, COUNTRYCODE, model.countryCode);
        }
        if (model.disabled) {
            config.setBoolean(USER, model.username, DISABLED, true);
        }
        if (model.getPreferences() != null) {
            Locale locale = model.getPreferences().getLocale();
            if (locale != null) {
                String val;
                if (StringUtils.isEmpty(locale.getCountry())) {
                    val = locale.getLanguage();
                } else {
                    val = locale.getLanguage() + "_" + locale.getCountry();
                }
                config.setString(USER, model.username, LOCALE, val);
            }

            config.setBoolean(USER, model.username, EMAILONMYTICKETCHANGES,
                    model.getPreferences().isEmailMeOnMyTicketChanges());

            if (model.getPreferences().getTransport() != null) {
                config.setString(USER, model.username, TRANSPORT, model.getPreferences().getTransport().name());
            }
        }

        // user roles
        List<String> roles = new ArrayList<String>();
        if (model.canAdmin) {
            roles.add(Role.ADMIN.getRole());
        }
        if (model.canFork) {
            roles.add(Role.FORK.getRole());
        }
        if (model.canCreate) {
            roles.add(Role.CREATE.getRole());
        }
        if (model.excludeFromFederation) {
            roles.add(Role.NOT_FEDERATED.getRole());
        }
        if (roles.size() == 0) {
            // we do this to ensure that user record with no password
            // is written.  otherwise, StoredConfig optimizes that account
            // away. :(
            roles.add(Role.NONE.getRole());
        }
        config.setStringList(USER, model.username, ROLE, roles);

        // discrete repository permissions
        if (model.permissions != null && !model.canAdmin) {
            List<String> permissions = new ArrayList<String>();
            for (Map.Entry<String, AccessPermission> entry : model.permissions.entrySet()) {
                if (entry.getValue().exceeds(AccessPermission.NONE)) {
                    permissions.add(entry.getValue().asRole(entry.getKey()));
                }
            }
            config.setStringList(USER, model.username, REPOSITORY, permissions);
        }

        // user preferences
        if (model.getPreferences() != null) {
            List<String> starred = model.getPreferences().getStarredRepositories();
            if (starred.size() > 0) {
                config.setStringList(USER, model.username, STARRED, starred);
            }
        }
    }

    // write teams
    for (TeamModel model : teams.values()) {
        // team roles
        List<String> roles = new ArrayList<String>();
        if (model.canAdmin) {
            roles.add(Role.ADMIN.getRole());
        }
        if (model.canFork) {
            roles.add(Role.FORK.getRole());
        }
        if (model.canCreate) {
            roles.add(Role.CREATE.getRole());
        }
        if (roles.size() == 0) {
            // we do this to ensure that team record is written.
            // Otherwise, StoredConfig might optimizes that record away.
            roles.add(Role.NONE.getRole());
        }
        config.setStringList(TEAM, model.name, ROLE, roles);
        if (model.accountType != null) {
            config.setString(TEAM, model.name, ACCOUNTTYPE, model.accountType.name());
        }

        if (!model.canAdmin) {
            // write team permission for non-admin teams
            if (model.permissions == null) {
                // null check on "final" repositories because JSON-sourced TeamModel
                // can have a null repositories object
                if (!ArrayUtils.isEmpty(model.repositories)) {
                    config.setStringList(TEAM, model.name, REPOSITORY,
                            new ArrayList<String>(model.repositories));
                }
            } else {
                // discrete repository permissions
                List<String> permissions = new ArrayList<String>();
                for (Map.Entry<String, AccessPermission> entry : model.permissions.entrySet()) {
                    if (entry.getValue().exceeds(AccessPermission.NONE)) {
                        // code:repository (e.g. RW+:~james/myrepo.git
                        permissions.add(entry.getValue().asRole(entry.getKey()));
                    }
                }
                config.setStringList(TEAM, model.name, REPOSITORY, permissions);
            }
        }

        // null check on "final" users because JSON-sourced TeamModel
        // can have a null users object
        if (!ArrayUtils.isEmpty(model.users)) {
            config.setStringList(TEAM, model.name, USER, new ArrayList<String>(model.users));
        }

        // null check on "final" mailing lists because JSON-sourced
        // TeamModel can have a null users object
        if (!ArrayUtils.isEmpty(model.mailingLists)) {
            config.setStringList(TEAM, model.name, MAILINGLIST, new ArrayList<String>(model.mailingLists));
        }

        // null check on "final" preReceiveScripts because JSON-sourced
        // TeamModel can have a null preReceiveScripts object
        if (!ArrayUtils.isEmpty(model.preReceiveScripts)) {
            config.setStringList(TEAM, model.name, PRERECEIVE, model.preReceiveScripts);
        }

        // null check on "final" postReceiveScripts because JSON-sourced
        // TeamModel can have a null postReceiveScripts object
        if (!ArrayUtils.isEmpty(model.postReceiveScripts)) {
            config.setStringList(TEAM, model.name, POSTRECEIVE, model.postReceiveScripts);
        }
    }

    config.save();
    // manually set the forceReload flag because not all JVMs support real
    // millisecond resolution of lastModified. (issue-55)
    forceReload = true;

    // If the write is successful, delete the current file and rename
    // the temporary copy to the original filename.
    if (realmFileCopy.exists() && realmFileCopy.length() > 0) {
        if (realmFile.exists()) {
            if (!realmFile.delete()) {
                throw new IOException(
                        MessageFormat.format("Failed to delete {0}!", realmFile.getAbsolutePath()));
            }
        }
        if (!realmFileCopy.renameTo(realmFile)) {
            throw new IOException(MessageFormat.format("Failed to rename {0} to {1}!",
                    realmFileCopy.getAbsolutePath(), realmFile.getAbsolutePath()));
        }
    } else {
        throw new IOException(MessageFormat.format("Failed to save {0}!", realmFileCopy.getAbsolutePath()));
    }
}

From source file:com.gitblit.GitBlit.java

License:Apache License

private void updateList(StoredConfig config, String field, List<String> list) {
    // a null list is skipped, not cleared
    // this is for RPC administration where an older manager might be used
    if (list == null) {
        return;//from  w  w w. jav  a  2 s.c  o m
    }
    if (ArrayUtils.isEmpty(list)) {
        config.unset(Constants.CONFIG_GITBLIT, null, field);
    } else {
        config.setStringList(Constants.CONFIG_GITBLIT, null, field, list);
    }
}

From source file:com.gitblit.utils.JGitUtils.java

License:Apache License

/**
 * Automatic repair of (some) invalid refspecs.  These are the result of a
 * bug in JGit cloning where a double forward-slash was injected.  :(
 *
 * @param repository/*from w  w  w.j  ava 2  s . c o m*/
 * @return true, if the refspecs were repaired
 */
public static boolean repairFetchSpecs(Repository repository) {
    StoredConfig rc = repository.getConfig();

    // auto-repair broken fetch ref specs
    for (String name : rc.getSubsections("remote")) {
        int invalidSpecs = 0;
        int repairedSpecs = 0;
        List<String> specs = new ArrayList<String>();
        for (String spec : rc.getStringList("remote", name, "fetch")) {
            try {
                RefSpec rs = new RefSpec(spec);
                // valid spec
                specs.add(spec);
            } catch (IllegalArgumentException e) {
                // invalid spec
                invalidSpecs++;
                if (spec.contains("//")) {
                    // auto-repair this known spec bug
                    spec = spec.replace("//", "/");
                    specs.add(spec);
                    repairedSpecs++;
                }
            }
        }

        if (invalidSpecs == repairedSpecs && repairedSpecs > 0) {
            // the fetch specs were automatically repaired
            rc.setStringList("remote", name, "fetch", specs);
            try {
                rc.save();
                rc.load();
                LOGGER.debug("repaired {} invalid fetch refspecs for {}", repairedSpecs,
                        repository.getDirectory());
                return true;
            } catch (Exception e) {
                LOGGER.error(null, e);
            }
        } else if (invalidSpecs > 0) {
            LOGGER.error("mirror executor found {} invalid fetch refspecs for {}", invalidSpecs,
                    repository.getDirectory());
        }
    }
    return false;
}

From source file:org.eclipse.oomph.setup.git.impl.GitCloneTaskImpl.java

License:Open Source License

private static void configureRepository(SetupTaskContext context, Repository repository, String checkoutBranch,
        String remoteName, String remoteURI, String pushURI, List<? extends ConfigSection> configSections)
        throws Exception, IOException {
    StoredConfig config = repository.getConfig();

    Map<String, Map<String, Map<String, List<String>>>> properties = new LinkedHashMap<String, Map<String, Map<String, List<String>>>>();

    for (ConfigSection section : configSections) {
        String sectionName = section.getName();
        if (!StringUtil.isEmpty(sectionName)) {
            for (ConfigProperty property : section.getProperties()) {
                handleProperty(properties, sectionName, null, property);
            }/*from   w w w  .ja  v a  2 s. c  o  m*/

            for (ConfigSubsection subsection : section.getSubsections()) {
                String subsectionName = subsection.getName();
                if (subsectionName != null) {
                    for (ConfigProperty property : subsection.getProperties()) {
                        handleProperty(properties, sectionName, subsectionName, property);
                    }
                }
            }
        }
    }

    boolean changed = false;
    boolean hasAutoCRLFProperty = false;

    for (Map.Entry<String, Map<String, Map<String, List<String>>>> sectionEntry : properties.entrySet()) {
        String sectionName = sectionEntry.getKey();
        for (Map.Entry<String, Map<String, List<String>>> subsectionEntry : sectionEntry.getValue()
                .entrySet()) {
            String subsectionName = subsectionEntry.getKey();
            for (Map.Entry<String, List<String>> propertyEntry : subsectionEntry.getValue().entrySet()) {
                String key = propertyEntry.getKey();
                if ("core".equals(sectionName) && subsectionName == null && "autocrlf".equals(key)) {
                    hasAutoCRLFProperty = true;
                }

                List<String> value = propertyEntry.getValue();
                String[] oldValue = config.getStringList(sectionName, subsectionName, key);
                if (value.isEmpty()) {
                    config.unset(sectionName, subsectionName, key);
                    changed |= oldValue.length != 0;
                } else {
                    config.setStringList(sectionName, subsectionName, key, value);
                    changed |= !Arrays.asList(oldValue).equals(value);
                }
            }
        }
    }

    if (!hasAutoCRLFProperty) {
        changed |= configureLineEndingConversion(context, config);
    }

    Set<String> gerritPatterns = new HashSet<String>();
    for (Object key : context.keySet()) {
        if (key instanceof String) {
            if (key.toString().endsWith(".gerrit.uri.pattern")) {
                Object value = context.get(key);
                if (value instanceof String) {
                    gerritPatterns.add(value.toString());
                }
            }
        }
    }

    if (!gerritPatterns.isEmpty()) {
        URI uri = URI.createURI(remoteURI);
        String uriString = uri.toString();
        for (String gerritPattern : gerritPatterns) {
            if (uriString.matches(gerritPattern)) {
                changed |= addGerritPullRefSpec(context, config, remoteName);
                changed |= addGerritPushRefSpec(context, config, checkoutBranch, remoteName);
                break;
            }
        }
    }

    changed |= addPushURI(context, config, remoteName, pushURI);
    if (changed) {
        config.save();
    }
}