Example usage for com.google.common.base Splitter split

List of usage examples for com.google.common.base Splitter split

Introduction

In this page you can find the example usage for com.google.common.base Splitter split.

Prototype

@CheckReturnValue
public Iterable<String> split(final CharSequence sequence) 

Source Link

Document

Splits sequence into string components and makes them available through an Iterator , which may be lazily evaluated.

Usage

From source file:org.apache.blur.doc.JsonPropertyFormatter.java

private String pretty(String s) {
    Splitter splitter = Splitter.on('.');
    StringBuilder builder = new StringBuilder();
    for (String split : splitter.split(s)) {
        if (builder.length() == 0 && split.equals(BLUR)) {
            // skip
        } else {//from  w  w  w.ja v a  2s  .c  o  m
            if (builder.length() != 0) {
                builder.append(' ');
            }
            builder.append(split.substring(0, 1).toUpperCase()).append(split.substring(1));
        }
    }
    return builder.toString();
}

From source file:com.android.tools.lint.checks.GradleDetector.java

@VisibleForTesting
@Nullable/* w w  w. ja v a 2s .  c o m*/
static String getNamedDependency(@NonNull String expression) {
    //if (value.startsWith("group: 'com.android.support', name: 'support-v4', version: '21.0.+'"))
    if (expression.indexOf(',') != -1 && expression.contains("version:")) {
        String artifact = null;
        String group = null;
        String version = null;
        Splitter splitter = Splitter.on(',').omitEmptyStrings().trimResults();
        for (String property : splitter.split(expression)) {
            int colon = property.indexOf(':');
            if (colon == -1) {
                return null;
            }
            char quote = '\'';
            int valueStart = property.indexOf(quote, colon + 1);
            if (valueStart == -1) {
                quote = '"';
                valueStart = property.indexOf(quote, colon + 1);
            }
            if (valueStart == -1) {
                // For example, "transitive: false"
                continue;
            }
            valueStart++;
            int valueEnd = property.indexOf(quote, valueStart);
            if (valueEnd == -1) {
                return null;
            }
            String value = property.substring(valueStart, valueEnd);
            if (property.startsWith("group:")) {
                group = value;
            } else if (property.startsWith("name:")) {
                artifact = value;
            } else if (property.startsWith("version:")) {
                version = value;
            }
        }

        if (artifact != null && group != null && version != null) {
            return group + ':' + artifact + ':' + version;
        }
    }

    return null;
}

From source file:nl.knaw.huygens.security.server.BasicAuthFilter.java

private Map<String, Collection<String>> readRoles() {
    final Map<String, Collection<String>> authRoles = Maps.newHashMap();

    log.debug("Reading authorization roles");
    final Properties authProperties = PropertiesHelper.getAuthProperties();
    final Splitter commaSplitter = Splitter.on(',').trimResults().omitEmptyStrings();
    for (String profile : commaSplitter.split(authProperties.getProperty("profiles"))) {
        final String authProp = authProperties.getProperty(profile + ".auth");
        final String rolesProp = authProperties.getProperty(profile + ".roles");
        final ImmutableSet<String> roles = ImmutableSet.copyOf(commaSplitter.split(rolesProp));
        log.debug("Auth profile [{}] has roles: {}", profile, roles);
        authRoles.put(authProp, roles);// w w w .ja v a  2  s  .c om
    }

    return authRoles;
}

From source file:gobblin.qualitychecker.task.TaskLevelPolicyCheckerBuilder.java

@SuppressWarnings("unchecked")
private List<TaskLevelPolicy> createPolicyList() throws Exception {
    List<TaskLevelPolicy> list = new ArrayList<>();
    String taskLevelPoliciesKey = ForkOperatorUtils
            .getPropertyNameForBranch(ConfigurationKeys.TASK_LEVEL_POLICY_LIST, this.index);
    String taskLevelPolicyTypesKey = ForkOperatorUtils
            .getPropertyNameForBranch(ConfigurationKeys.TASK_LEVEL_POLICY_LIST_TYPE, this.index);
    if (this.state.contains(taskLevelPoliciesKey) && this.state.contains(taskLevelPolicyTypesKey)) {
        Splitter splitter = Splitter.on(",").omitEmptyStrings().trimResults();
        List<String> policies = Lists.newArrayList(splitter.split(this.state.getProp(taskLevelPoliciesKey)));
        List<String> types = Lists.newArrayList(splitter.split(this.state.getProp(taskLevelPolicyTypesKey)));
        if (policies.size() != types.size()) {
            throw new Exception("TaskLevelPolicy list and TaskLevelPolicies type list are not the same length");
        }//  ww  w  .j  a  va2 s  . c o  m
        for (int i = 0; i < policies.size(); i++) {
            try {
                Class<? extends TaskLevelPolicy> policyClass = (Class<? extends TaskLevelPolicy>) Class
                        .forName(policies.get(i));
                Constructor<? extends TaskLevelPolicy> policyConstructor = policyClass
                        .getConstructor(State.class, TaskLevelPolicy.Type.class);
                TaskLevelPolicy policy = policyConstructor.newInstance(this.state,
                        TaskLevelPolicy.Type.valueOf(types.get(i)));
                list.add(policy);
            } catch (Exception e) {
                LOG.error(taskLevelPoliciesKey + " contains a class " + policies.get(i)
                        + " which doesn't extend Policy.", e);
                throw e;
            }
        }
    }
    return list;
}

From source file:org.trnltk.tokenizer.TextTokenizerTrainer.java

public static TokenizationGraph buildDefaultTokenizationGraph(boolean recordExamples) throws IOException {
    final Splitter lineSplitter = Splitter.on(CharMatcher.anyOf("\n\r")).trimResults().omitEmptyStrings();

    final TokenizerTrainingData defaultTrainingData = TokenizerTrainingData.createDefaultTrainingData();
    final TextTokenizerTrainer trainer = new TextTokenizerTrainer(2, recordExamples);
    for (TokenizerTrainingEntry tokenizerTrainingEntry : defaultTrainingData.getEntries()) {
        try {/*from  w  w  w.jav  a  2  s  .  c om*/
            // train with text block
            Validate.isTrue(StringUtils.isNotEmpty(tokenizerTrainingEntry.getText()),
                    "text is empty " + tokenizerTrainingEntry.getText()); //could be blank
            Validate.isTrue(StringUtils.isNotEmpty(tokenizerTrainingEntry.getTknz()),
                    "tknz is empty " + tokenizerTrainingEntry.getTknz()); //could be blank
            trainer.train(tokenizerTrainingEntry.getText(), tokenizerTrainingEntry.getTknz());

            // split text block to lines and train with them
            final Iterable<String> textLines = lineSplitter.split(tokenizerTrainingEntry.getText());
            final Iterable<String> tknzLines = lineSplitter.split(tokenizerTrainingEntry.getTknz());
            final Iterator<String> textLinesIterator = textLines.iterator();
            final Iterator<String> tknzLinesIterator = tknzLines.iterator();
            while (textLinesIterator.hasNext() && tknzLinesIterator.hasNext()) {
                final String textLine = textLinesIterator.next();
                final String tknzLine = tknzLinesIterator.next();
                trainer.train(textLine, tknzLine);
            }
        } catch (RuntimeException e) {
            String msg = "Error training with entry: \n  - text: " + tokenizerTrainingEntry.getText()
                    + "\n    tknz: " + tokenizerTrainingEntry.getTknz();
            throw new RuntimeException(msg, e);
        }
    }
    return trainer.build();
}

From source file:com.shopwiki.vaadin.UrlParams.java

public UrlParams(String queryString) {
    if (queryString == null) {
        return;/*from   w  ww  . j a va  2 s  .  c  o  m*/
    }

    Splitter kvSplitter = Splitter.on('=');

    for (String param : Splitter.on('&').split(queryString)) {
        List<String> kv = Lists.newArrayList(kvSplitter.split(param));
        if (kv.size() >= 2) {
            add(kv.get(0), kv.get(1));
        }
    }
}

From source file:uk.q3c.krail.core.navigate.sitemap.MapLineReader.java

public MapLineRecord processLine(DefaultFileSitemapLoader loader, String source, int lineIndex, String line,
        int currentIndent, String attributeSeparator) {
    log.debug("processing line {}", line);
    this.line = line;
    lineRecord = new MapLineRecord();

    // split columns on segmentSeparator
    Splitter splitter = Splitter.on(attributeSeparator).trimResults();
    Iterable<String> attributes = splitter.split(line);
    Iterator<String> iterator = attributes.iterator();
    // split first column into indentation and uri segment
    boolean indentOk = indentAndSegment(loader, source, iterator.next(), lineIndex);

    if (indentOk) {
        String viewAttribute = (iterator.hasNext()) ? iterator.next() : "";
        view(viewAttribute);// w  w w  . ja v a  2  s  .c  o  m
        String labelKeyAttribute = (iterator.hasNext()) ? iterator.next() : "";
        labelKey(labelKeyAttribute);
        String permissionAttribute = (iterator.hasNext()) ? iterator.next() : "";
        roles(permissionAttribute);
        if (lineRecord.getIndentLevel() > currentIndent + 1) {
            loader.addWarning(source, FileSitemapLoader.LINE_FORMAT_INDENTATION_INCORRECT,
                    lineRecord.getSegment(), lineIndex);
        }
    }
    return lineRecord;
}

From source file:ru.codeinside.adm.parser.EmployeeFixtureParser.java

private Set<Role> parseRoles(Splitter groupSplitter, int lineNumber, String rolesString) {
    Set<String> roleNames = Sets.newTreeSet(groupSplitter.split(rolesString));
    Set<Role> roles = EnumSet.noneOf(Role.class);
    for (String roleName : roleNames) {
        try {/* w ww.j  a v  a  2  s  .co  m*/
            roles.add(Role.valueOf(roleName));
        } catch (Exception e) {
            throw new IllegalStateException(
                    "???  ( ?:" + lineNumber + "):" + roleName);
        }
    }

    return roles;
}

From source file:com.android.builder.internal.SymbolWriter.java

public void write() throws IOException {
    Splitter splitter = Splitter.on('.');
    Iterable<String> folders = splitter.split(mPackageName);
    File file = new File(mOutFolder);
    for (String folder : folders) {
        file = new File(file, folder);
    }//from www .ja va2s .c  o  m
    file.mkdirs();
    file = new File(file, SdkConstants.FN_RESOURCE_CLASS);

    Closer closer = Closer.create();
    try {
        BufferedWriter writer = closer.register(Files.newWriter(file, Charsets.UTF_8));

        writer.write("/* AUTO-GENERATED FILE.  DO NOT MODIFY.\n");
        writer.write(" *\n");
        writer.write(" * This class was automatically generated by the\n");
        writer.write(" * aapt tool from the resource data it found.  It\n");
        writer.write(" * should not be modified by hand.\n");
        writer.write(" */\n");

        writer.write("package ");
        writer.write(mPackageName);
        writer.write(";\n\npublic final class R {\n");

        Table<String, String, SymbolEntry> symbols = getAllSymbols();
        Table<String, String, SymbolEntry> values = mValues.getSymbols();

        Set<String> rowSet = symbols.rowKeySet();
        List<String> rowList = Lists.newArrayList(rowSet);
        Collections.sort(rowList);

        for (String row : rowList) {
            writer.write("\tpublic static final class ");
            writer.write(row);
            writer.write(" {\n");

            Map<String, SymbolEntry> rowMap = symbols.row(row);
            Set<String> symbolSet = rowMap.keySet();
            ArrayList<String> symbolList = Lists.newArrayList(symbolSet);
            Collections.sort(symbolList);

            for (String symbolName : symbolList) {
                // get the matching SymbolEntry from the values Table.
                SymbolEntry value = values.get(row, symbolName);
                if (value != null) {
                    writer.write("\t\tpublic static final ");
                    writer.write(value.getType());
                    writer.write(" ");
                    writer.write(value.getName());
                    writer.write(" = ");
                    writer.write(value.getValue());
                    writer.write(";\n");
                }
            }

            writer.write("\t}\n");
        }

        writer.write("}\n");
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:org.lilyproject.tools.scanner.cli.ScannerCli.java

@Override
public int run(CommandLine cmd) throws Exception {
    int result = super.run(cmd);
    if (result != 0) {
        return result;
    }/* ww w  . ja  v  a  2 s  .c o  m*/

    if (!cmd.hasOption(printOption.getOpt()) && !cmd.hasOption(countOption.getOpt())) {
        printHelp();
        return 0;
    }

    String startId = cmd.hasOption(startOption.getLongOpt()) ? cmd.getOptionValue(startOption.getLongOpt())
            : null;
    String stopId = cmd.hasOption(stopOption.getLongOpt()) ? cmd.getOptionValue(stopOption.getLongOpt()) : null;
    String recordTypeFilter = cmd.hasOption(recordTypeOption.getOpt())
            ? cmd.getOptionValue(recordTypeOption.getOpt())
            : null;
    File configFile = cmd.hasOption(configOption.getLongOpt())
            ? new File(cmd.getOptionValue(configOption.getLongOpt()))
            : null;
    long limit = cmd.hasOption(limitOption.getLongOpt())
            ? Long.parseLong(cmd.getOptionValue(limitOption.getLongOpt()))
            : -1;
    String repositoryName = OptionUtil.getStringOption(cmd, repositoryOption,
            RepoAndTableUtil.DEFAULT_REPOSITORY);
    String tableName = OptionUtil.getStringOption(cmd, tableOption, Table.RECORD.name);

    if (cmd.hasOption(rolesOption.getLongOpt())) {
        Set<String> roles = new HashSet<String>();
        Splitter splitter = Splitter.on(",").trimResults().omitEmptyStrings();
        for (String role : splitter.split(cmd.getOptionValue(rolesOption.getLongOpt()))) {
            roles.add(role);
        }
        AuthorizationContextHolder
                .setCurrentContext(new AuthorizationContext("lily-scan-records", repositoryName, roles));
    }

    lilyClient = new LilyClient(zkConnectionString, zkSessionTimeout);
    LRepository repository = lilyClient.getRepository(repositoryName);
    LTable table = repository.getTable(tableName);
    if (cmd.hasOption(countOption.getOpt())) {
        RecordScanTool.count(repository, table, startId, stopId, recordTypeFilter, configFile);
    } else if (cmd.hasOption(printOption.getOpt())) {
        RecordScanTool.print(repository, table, startId, stopId, limit, recordTypeFilter, configFile);
    }

    return 0;
}