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

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

Introduction

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

Prototype

@CheckReturnValue
@GwtIncompatible("java.util.regex")
public static Splitter on(final Pattern separatorPattern) 

Source Link

Document

Returns a splitter that considers any subsequence matching pattern to be a separator.

Usage

From source file:org.openmhealth.schema.domain.omh.AdditionalPropertySupport.java

/**
 * Sets an additional property. This method supports dot-separated paths by creating nested maps when necessary.
 *
 * @param path  the path of the property to set
 * @param value the value of the property to set
 *//*w ww  . j a v  a 2s  .  c o  m*/
@SuppressWarnings("unchecked")
@JsonAnySetter
default void setAdditionalProperty(String path, Object value) {

    checkNotNull(path, "A path hasn't been specified.");
    checkArgument(!path.isEmpty(), "An empty path has been specified.");

    Iterator<String> names = Splitter.on(".").omitEmptyStrings().split(path).iterator();
    Map<String, Object> currentCollection = getAdditionalProperties();

    while (names.hasNext()) {
        String currentName = names.next();

        // set the value, potentially overriding an existing value
        if (!names.hasNext()) {
            currentCollection.put(currentName, value);
            break;
        }

        // traverse into a collection if one exists
        if (currentCollection.get(currentName) instanceof Map) {
            currentCollection = (Map<String, Object>) currentCollection.get(currentName);
            continue;
        }

        // create a new collection, potentially overriding an existing value
        Map<String, Object> map = new HashMap<>();
        currentCollection.put(currentName, map);
        currentCollection = map;
    }
}

From source file:com.intel.rsa.common.types.helpers.ConvertableEnumListHolder.java

public ConvertableEnumListHolder(Class<T> enumType, String text) {
    this.enumType = enumType;
    if (Strings.isNullOrEmpty(text)) {
        this.elements = unmodifiableList(new LinkedList<>());
    } else {/*from   w  w  w.ja  v  a 2 s .  co  m*/
        List<String> elementsStringList = Splitter.on(ELEMENT_SEPARATOR).trimResults().splitToList(text);

        List<T> elements = new LinkedList<>();
        for (String element : elementsStringList) {
            elements.add(ConvertableEnumHelper.fromString(this.enumType, element));
        }

        this.elements = unmodifiableList(elements);
    }
}

From source file:org.kududb.util.NetUtil.java

/**
 * Parse a comma separated list of "host:port" pairs into a list of
 * {@link HostAndPort} objects. If no port is specified for an entry in
 * the comma separated list, then a default port is used.
 * The inverse of {@link #hostsAndPortsToString(List)}.
 *
 * @param commaSepAddrs The comma separated list of "host:port" pairs.
 * @param defaultPort   The default port to use if no port is specified.
 * @return A list of HostAndPort objects constructed from commaSepAddrs.
 *///ww  w .j  av a2  s . c om
public static List<HostAndPort> parseStrings(final String commaSepAddrs, int defaultPort) {
    Iterable<String> addrStrings = Splitter.on(',').trimResults().split(commaSepAddrs);
    List<HostAndPort> hostsAndPorts = Lists.newArrayListWithCapacity(Iterables.size(addrStrings));
    for (String addrString : addrStrings) {
        HostAndPort hostAndPort = parseString(addrString, defaultPort);
        hostsAndPorts.add(hostAndPort);
    }
    return hostsAndPorts;
}

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);//  ww w .  j  a  va  2s  .com
        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:com.google.devtools.build.lib.syntax.GlobList.java

/**
 * Parses a GlobInfo from its {@link #toExpression} representation.
 *//*  w ww. j  av a2s. com*/
public static GlobList<String> parse(String text) {
    List<GlobCriteria> criteria = new ArrayList<>();
    Iterable<String> globs = Splitter.on(" + ").split(text);
    for (String glob : globs) {
        criteria.add(GlobCriteria.parse(glob));
    }
    return new GlobList<>(criteria, ImmutableList.<String>of());
}

From source file:org.apache.gobblin.service.validator.TemplateUriValidator.java

@Override
public void validate(ValidatorContext ctx) {
    DataElement element = ctx.dataElement();
    Object value = element.getValue();
    String str = String.valueOf(value);
    boolean valid = true;

    try {//from  w ww  .ja va  2s  .c om
        Iterable<String> uriStrings = Splitter.on(",").omitEmptyStrings().trimResults().split(str);

        for (String uriString : uriStrings) {
            URI uri = new URI(uriString);

            if (!uri.getScheme().equalsIgnoreCase(FS_SCHEME)) {
                throw new URISyntaxException(uriString, "Scheme is not FS");
            }
        }
    } catch (URISyntaxException e) {
        valid = false;
    }

    if (!valid) {
        ctx.addResult(
                new Message(element.path(), "\"%1$s\" is not a well-formed comma-separated list of URIs", str));
    }
}

From source file:com.google.testing.security.firingrange.tests.reverseclickjacking.UniversalReverseClickjackingMultiPage.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String headerOptions, parameterLocation, template;

    try {/*ww  w .  j av  a2s .c o m*/
        parameterLocation = Splitter.on('/').splitToList(request.getPathInfo()).get(2);
        headerOptions = Splitter.on('/').splitToList(request.getPathInfo()).get(3);
    } catch (IndexOutOfBoundsException e) {
        // Either the parameter location or the X-Frame-Options is not set.
        Responses.sendError(response,
                "Please specify the location of the vulnerable parameter and the preference for the"
                        + " X-Frame-Option header.",
                400);
        return;
    }

    String vulnerableParameter = Strings.nullToEmpty(request.getParameter(VULNERABLE_PARAMETER));
    // Encode URL to prevent XSS
    vulnerableParameter = urlFormParameterEscaper().escape(vulnerableParameter);

    switch (parameterLocation) {
    case "ParameterInQuery":
        template = Templates.getTemplate("jsonly_in_query.tmpl", getClass());
        template = Templates.replacePayload(template, vulnerableParameter);
        break;
    case "ParameterInFragment":
        template = Templates.getTemplate("jsonly_in_fragment.tmpl", getClass());
        break;
    default:
        Responses.sendError(response, "Invalid location of the vulnerable parameter.", 400);
        return;
    }

    switch (headerOptions) {
    case "WithXFO":
        response.setHeader(HttpHeaders.X_FRAME_OPTIONS, "DENY");
        break;
    case "WithoutXFO":
        break;
    default:
        Responses.sendError(response, "Invalid preference for the X-Frame-Option header.", 400);
        return;
    }

    Responses.sendXssed(response, template);
}

From source file:com.google.cloud.genomics.utils.Contig.java

/**
 * Parse the list of Contigs expressed in the string argument.
 *
 * The common use case is to parse the value of a command line parameter.
 *
 * @param contigsArgument - a string expressing the specified contiguous region(s) of the genome.
 *                          The format is chromosome:start:end[,chromosome:start:end]
 * @return a list of Contig objects// w ww .j a v a 2  s.  com
 */
public static Iterable<Contig> parseContigsFromCommandLine(String contigsArgument) {
    return Iterables.transform(Splitter.on(",").split(contigsArgument), new Function<String, Contig>() {
        @Override
        public Contig apply(String contigString) {
            ArrayList<String> contigInfo = newArrayList(Splitter.on(":").split(contigString));
            Long start = Long.valueOf(contigInfo.get(1));
            Long end = Long.valueOf(contigInfo.get(2));
            Preconditions.checkArgument(start <= end, "Contig coordinates are incorrectly specified: start "
                    + start + " is greater than end " + end);
            return new Contig(contigInfo.get(0), start, end);
        }
    });
}

From source file:io.scigraph.lucene.SynonymMapSupplier.java

@Override
public SynonymMap get() {
    try {/*from w w  w. j a  v  a 2s .c  o m*/
        return Resources.readLines(Resources.getResource("lemmatization.txt"), Charsets.UTF_8,
                new LineProcessor<SynonymMap>() {

                    SynonymMap.Builder builder = new SynonymMap.Builder(true);

                    @Override
                    public boolean processLine(String line) throws IOException {
                        List<String> synonyms = newArrayList(Splitter.on(',').trimResults().split(line));
                        for (String term : synonyms) {
                            for (String synonym : synonyms) {
                                if (!term.equals(synonym)) {
                                    builder.add(new CharsRef(term), new CharsRef(synonym), true);
                                }
                            }
                        }
                        return true;
                    }

                    @Override
                    public SynonymMap getResult() {
                        try {
                            return builder.build();
                        } catch (IOException e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                });
    } catch (Exception e) {
        logger.log(Level.WARNING, "Failed to build synonym map", e);
        return null;
    }
}

From source file:io.prestosql.decoder.json.JsonRowDecoder.java

private static JsonNode locateNode(JsonNode tree, DecoderColumnHandle columnHandle) {
    String mapping = columnHandle.getMapping();
    checkState(mapping != null, "No mapping for %s", columnHandle.getName());

    JsonNode currentNode = tree;// ww w  .  ja  va  2  s  .c  o m
    for (String pathElement : Splitter.on('/').omitEmptyStrings().split(mapping)) {
        if (!currentNode.has(pathElement)) {
            return MissingNode.getInstance();
        }
        currentNode = currentNode.path(pathElement);
    }
    return currentNode;
}