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:eu.esdihumboldt.hale.server.security.util.ProxyOpenIDAuthenticationFilter.java

/**
 * Build a returnTo URL if behind a proxy.
 * /*from   w  w  w .j  av  a2  s  .  co m*/
 * @param returnTo the original returnTo URL
 * @param forwardedFor the X-Forwarded-For header
 * @return the proxy returnTo URL or <code>null</code> if it could not be
 *         determined
 */
public static String buildReturnToForProxy(String returnTo, String forwardedFor) {
    Iterable<String> parts = Splitter.on(',').trimResults().split(forwardedFor);
    String outwardProxy = null;
    try {
        outwardProxy = Iterables.get(parts, 1);

        // original returnTo
        URI org = URI.create(returnTo);
        // build proxy URL, assuming http as scheme
        URI uri = new URI("http", outwardProxy, org.getPath(), org.getQuery(), org.getFragment());
        return uri.toString();
    } catch (Exception e) {
        log.warn("Error building proxy return URL from X-Forwarded-For");

        // try HALE base URL system property as fall-back
        String baseUrl = System.getProperty(SYSTEM_PROPERTY_SERVER_URL);
        if (baseUrl != null) {
            try {
                // original returnTo
                URI org = URI.create(returnTo);
                // build proxy URL
                URI uri = new URI(baseUrl + org.getRawPath());
                return uri.toString();
            } catch (Exception e1) {
                log.warn("Error building proxy return URL from " + SYSTEM_PROPERTY_SERVER_URL
                        + " system property", e1);
            }
        }
    }

    return null;
}

From source file:org.jclouds.elasticstack.functions.SplitNewlines.java

@Override
public Set<String> apply(HttpResponse response) {
    return newTreeSet(Splitter.on('\n').omitEmptyStrings().split(returnStringIf200.apply(response)));
}

From source file:com.bluetrainsoftware.maven.jaxrs2typescript.model.RestMethod.java

/**
 * use string interpolation for reliability.
 *
 * @param path// w  ww.jav a  2 s.  co m
 */
public void setPath(String path) {
    String newPath = Splitter.on("/").splitToList(path).stream().map(part -> {
        if (part.startsWith("{") && part.endsWith("}")) {
            return "${" + part.substring(1);
        } else {
            return part;
        }
    }).collect(Collectors.joining("/"));

    //    if (path.startsWith("/") && !newPath.startsWith("/")) {
    //      newPath = "/" + path;
    //    }

    if (newPath.endsWith("/") && !path.endsWith("/")) {
        newPath = newPath.substring(0, newPath.length() - 2);
    }

    this.path = newPath;
}

From source file:org.jclouds.chef.predicates.CookbookVersionPredicates.java

/**
 * Note that the default recipe of a cookbook is its name. Otherwise, you
 * prefix the recipe with the name of the cookbook. ex. {@code apache2} will
 * be the default recipe where {@code apache2::mod_proxy} is a specific one
 * in the cookbook./*from w w  w.  j a  v  a 2 s  .  c om*/
 * 
 * @param recipes
 *           names of the recipes.
 * @return true if the cookbook version contains a recipe in the list.
 */
public static Predicate<CookbookVersion> containsRecipes(String... recipes) {
    checkNotNull(recipes, "recipes must be defined");
    final Multimap<String, String> search = LinkedListMultimap.create();
    for (String recipe : recipes) {
        if (recipe.indexOf("::") != -1) {
            Iterable<String> nameRecipe = Splitter.on("::").split(recipe);
            search.put(get(nameRecipe, 0), get(nameRecipe, 1) + ".rb");
        } else {
            search.put(recipe, "default.rb");
        }
    }
    return new Predicate<CookbookVersion>() {
        @Override
        public boolean apply(final CookbookVersion cookbookVersion) {
            return search.containsKey(cookbookVersion.getCookbookName())
                    && any(search.get(cookbookVersion.getCookbookName()), new Predicate<String>() {

                        @Override
                        public boolean apply(final String recipeName) {
                            return any(cookbookVersion.getRecipes(), new Predicate<Resource>() {

                                @Override
                                public boolean apply(Resource resource) {
                                    return resource.getName().equals(recipeName);
                                }

                            });
                        }

                    });
        }

        @Override
        public String toString() {
            return "containsRecipes(" + search + ")";
        }
    };
}

From source file:com.github.kevints.mesos.scheduler.server.LibprocessServletUtils.java

static Optional<PID> getSenderPid(HttpServletRequest req) {
    Optional<String> libprocessFrom = Optional.fromNullable(req.getHeader("X-Libprocess-From"));
    if (libprocessFrom.isPresent()) {
        try {//from  w  w w  .java  2s  . co  m
            return Optional.of(PID.fromString(libprocessFrom.get()));
        } catch (IllegalArgumentException e) {
            return Optional.absent();
        }
    }

    Optional<String> userAgent = Optional.fromNullable(req.getHeader("User-Agent"));
    if (userAgent.isPresent()) {
        List<String> pid = Splitter.on("libprocess/").omitEmptyStrings().splitToList(userAgent.get());
        if (pid.size() != 1) {
            return Optional.absent();
        } else {
            try {
                return Optional.of(PID.fromString(pid.get(0)));
            } catch (IllegalArgumentException e) {
                return Optional.absent();
            }
        }
    }

    return Optional.absent();
}

From source file:com.google.api.codegen.util.py.PythonCommentReformatter.java

@Override
public String reformat(String comment) {
    boolean inCodeBlock = false;
    boolean first = true;
    Iterable<String> lines = Splitter.on("\n").split(comment);
    StringBuffer sb = new StringBuffer();
    for (String line : lines) {
        if (inCodeBlock) {
            // Code blocks are either empty or indented
            if (!(line.trim().isEmpty() || CommentPatterns.CODE_BLOCK_PATTERN.matcher(line).matches())) {
                inCodeBlock = false;/*  w  w  w  . j a  v  a  2  s.  c om*/
                line = transformer.transform(line);
            }

        } else if (CommentPatterns.CODE_BLOCK_PATTERN.matcher(line).matches()) {
            inCodeBlock = true;
            line = "::\n\n" + line;

        } else {
            line = transformer.transform(line);
        }

        if (!first) {
            sb.append("\n");
        }
        first = false;
        sb.append(line.replace("\"", "\\\""));
    }
    return sb.toString().trim();
}

From source file:org.graylog.plugins.metrics.core.jadconfig.PatternListConverter.java

@Override
public List<Pattern> convertFrom(String value) {
    if (value == null) {
        throw new ParameterException("Couldn't convert value \"null\" to a list of regular expressions.");
    }/*from   w  w w.  j  a v a  2 s .c  o m*/

    try {
        final Iterable<String> regexList = Splitter.on(SEPARATOR).omitEmptyStrings().trimResults().split(value);
        return StreamSupport.stream(regexList.spliterator(), false).map(Pattern::compile)
                .collect(Collectors.toList());
    } catch (Exception e) {
        throw new ParameterException(e.getMessage(), e);
    }
}

From source file:com.googlecode.blaisemath.util.xml.InsetsAdapter.java

@Override
public Insets unmarshal(String v) throws Exception {
    if (Strings.isNullOrEmpty(v)) {
        return null;
    }// w  w  w. java  2s  .  c  om
    Matcher m = Pattern.compile("insets\\[(.*)\\]").matcher(v.toLowerCase().trim());
    if (m.find()) {
        String inner = m.group(1);
        Map<String, String> kv = Splitter.on(",").trimResults().withKeyValueSeparator("=").split(inner);
        try {
            Integer t = Integer.valueOf(kv.get("t"));
            Integer l = Integer.valueOf(kv.get("l"));
            Integer b = Integer.valueOf(kv.get("b"));
            Integer r = Integer.valueOf(kv.get("r"));
            return new Insets(t, l, b, r);
        } catch (NumberFormatException x) {
            Logger.getLogger(InsetsAdapter.class.getName()).log(Level.FINEST, "Not an integer", x);
            return null;
        }
    } else {
        throw new IllegalArgumentException("Invalid insets: " + v);
    }
}

From source file:cc.gospy.core.util.UrlBundle.java

private static List<String> parseFirstGroup(List<String> urls) {
    int startPos, endPos;
    Iterator<String> parents = urls.iterator();
    List<String> children = Lists.newArrayList();
    while (parents.hasNext()) {
        String rule = parents.next();
        if ((startPos = rule.indexOf('{')) == -1 || (endPos = rule.indexOf('}')) == -1) {
            return urls;
        }/*w ww.j  a v a2 s  . c o  m*/
        if (startPos > endPos) {
            throw new RuntimeException("invalid bound, '}' matched '{': " + rule);
        }
        String firstGroup = rule.substring(startPos + 1, endPos);
        if (firstGroup.contains("&")) {
            for (String subRule : firstGroup.split("&")) {
                children.add(String.format("%s{%s}%s", rule.substring(0, startPos), subRule,
                        rule.substring(endPos + 1)));
            }
        } else {
            String[] params = Iterables.toArray(Splitter.on('~').trimResults().split(firstGroup), String.class);
            if (params.length < 2 || params.length > 3) {
                throw new RuntimeException(
                        String.format("invalid param size %d, in '%s'", params.length, firstGroup));
            }
            if (params[0].length() == 1 && params[1].length() == 1 && Character.isLetter(params[0].charAt(0))
                    && Character.isLetter(params[1].charAt(0))) {
                String lowercase = "abcdefghijklmnopqrstuvwxyz";
                String uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                boolean isLowercase;
                if (lowercase.contains(params[0]) && lowercase.contains(params[1])) {
                    isLowercase = true;
                } else if (uppercase.contains(params[0]) && uppercase.contains(params[1])) {
                    isLowercase = false;
                } else {
                    throw new RuntimeException("letter case crashed, in group " + firstGroup);
                }
                int startChar = isLowercase ? lowercase.indexOf(params[0]) : uppercase.indexOf(params[0]);
                int endChar = isLowercase ? lowercase.indexOf(params[1]) : uppercase.indexOf(params[1]);
                boolean upward = startChar < endChar;
                try {
                    int step = params.length == 3 ? Integer.parseInt(params[2]) : (upward ? 1 : -1);
                    if (step == 0 || step > 0 && !upward || step < 0 && upward) {
                        throw new RuntimeException(
                                "infinite iteration, please check the 'step', in group: " + firstGroup);
                    }
                    for (int i = startChar; upward ? i <= endChar : i >= endChar; i = i + step) {
                        children.add(rule.substring(0, startPos)
                                + (isLowercase ? lowercase.charAt(i) : uppercase.charAt(i))
                                + rule.substring(endPos + 1));
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage());
                }
            } else {
                int startValue;
                int endValue;
                try {
                    startValue = Integer.parseInt(params[0]);
                    endValue = Integer.parseInt(params[1]);
                    boolean upward = startValue <= endValue;
                    int step = params.length == 3 ? Integer.parseInt(params[2]) : (upward ? 1 : -1);
                    if (step == 0 || step > 0 && !upward || step < 0 && upward) {
                        throw new RuntimeException(
                                "infinite iteration, please check 'step', in group: " + firstGroup);
                    }
                    for (int i = startValue; upward ? i <= endValue : i >= endValue; i = i + step) {
                        children.add(rule.substring(0, startPos) + i + rule.substring(endPos + 1));
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage());
                }
            }
        }
    }
    return parseFirstGroup(children);
}

From source file:org.kitesdk.data.hbase.impl.Loader.java

@VisibleForTesting
public static String[] parseHostsAndPort(String zkQuorum) {
    List<String> hosts = Lists.newArrayList();
    String port = null;//from  www .  j  a  v  a 2s . c o m
    for (String hostPort : Splitter.on(',').split(zkQuorum)) {
        Iterator<String> split = Splitter.on(':').split(hostPort).iterator();
        hosts.add(split.next());
        if (split.hasNext()) {
            String p = split.next();
            if (port == null) {
                port = p;
            } else if (!port.equals(p)) {
                throw new IllegalArgumentException("Mismatched ports in " + zkQuorum);
            }
        }
    }
    return new String[] { Joiner.on(',').join(hosts), port };
}