List of usage examples for com.google.common.base Splitter split
@CheckReturnValue public Iterable<String> split(final CharSequence sequence)
From source file:fr.letroll.ttorrentandroid.tracker.TrackerService.java
@Nonnull @VisibleForTesting//from w ww .j a va2s.co m public static Multimap<String, String> parseQuery(String query) { Multimap<String, String> params = ArrayListMultimap.create(); Splitter ampersand = Splitter.on('&').omitEmptyStrings(); // Splitter equals = Splitter.on('=').limit(2); try { for (String pair : ampersand.split(query)) { String[] keyval = pair.split("[=]", 2); if (keyval.length == 1) { parseParam(params, keyval[0], null); } else { parseParam(params, keyval[0], keyval[1]); } } } catch (ArrayIndexOutOfBoundsException e) { params.clear(); } return params; }
From source file:org.opendaylight.netvirt.elan.internal.ElanBridgeManager.java
private static Map<String, String> extractMultiKeyValueToMap(String multiKeyValueStr) { if (Strings.isNullOrEmpty(multiKeyValueStr)) { return Collections.emptyMap(); }//from www. j a v a 2 s . c o m Map<String, String> valueMap = new HashMap<>(); Splitter splitter = Splitter.on(OTHER_CONFIG_PARAMETERS_DELIMITER); for (String keyValue : splitter.split(multiKeyValueStr)) { String[] split = keyValue.split(OTHER_CONFIG_KEY_VALUE_DELIMITER, 2); if (split.length == 2) { valueMap.put(split[0], split[1]); } } return valueMap; }
From source file:com.facebook.buck.apple.AbstractAppleNativeTargetBuildRuleDescriptions.java
private static SymlinkTree createSymlinkTree(BuildRuleParams params, SourcePathResolver pathResolver, ImmutableSortedMap<SourcePath, String> perFileFlags, boolean useBuckHeaderMaps) { // Note that the set of headersToCopy may be empty. If so, the returned rule will be a no-op. // TODO(mbolin): Make headersToCopy an ImmutableSortedMap once we clean up the iOS codebase and // can guarantee that the keys are unique. Map<Path, SourcePath> headersToCopy; if (useBuckHeaderMaps) { // No need to copy headers because header maps are used. headersToCopy = ImmutableSortedMap.of(); } else {/*from www.j a v a2 s. c o m*/ // This is a heuristic to get the right header path prefix. Note that ProjectGenerator uses a // slightly different heuristic, which is buildTarget.getShortNameOnly(), though that is only // a fallback when an apple_library() does not specify a header_path_prefix when // use_buck_header_maps is True. Path headerPathPrefix = params.getBuildTarget().getBasePath().getFileName(); headersToCopy = Maps.newHashMap(); Splitter spaceSplitter = Splitter.on(' ').trimResults().omitEmptyStrings(); Predicate<String> isPublicHeaderFlag = Predicates.equalTo("public"); for (Map.Entry<SourcePath, String> entry : perFileFlags.entrySet()) { String flags = entry.getValue(); if (Iterables.any(spaceSplitter.split(flags), isPublicHeaderFlag)) { SourcePath sourcePath = entry.getKey(); Path sourcePathName = pathResolver.getPath(sourcePath).getFileName(); headersToCopy.put(headerPathPrefix.resolve(sourcePathName), sourcePath); } } } BuildRuleParams headerParams = params.copyWithDeps(/* declaredDeps */ ImmutableSortedSet.<BuildRule>of(), params.getExtraDeps()); Path root = getPathToHeaders(params.getBuildTarget()); return new SymlinkTree(headerParams, pathResolver, root, ImmutableMap.copyOf(headersToCopy)); }
From source file:com.b2international.index.compat.Highlighting.java
public static String[] getSuffixes(final String queryExpression, final String label) { final Splitter tokenSplitter = Splitter.on(TextConstants.WHITESPACE_OR_DELIMITER_MATCHER) .omitEmptyStrings();/*from w w w . j a va 2s . c o m*/ final List<String> filterTokens = tokenSplitter.splitToList(queryExpression.toLowerCase()); final boolean spaceAtTheEnd = !queryExpression.isEmpty() && Character.isWhitespace(queryExpression.charAt(queryExpression.length() - 1)); final String lowerCaseLabel = label.toLowerCase(); final Iterable<String> labelTokens = tokenSplitter.split(lowerCaseLabel); final List<String> elementSuffixes = Lists.newArrayList(); for (final String labelToken : labelTokens) { final Iterator<String> itr = filterTokens.iterator(); while (itr.hasNext()) { final String filterToken = itr.next(); if (labelToken.startsWith(filterToken)) { // Last filter token? Also add suffix, unless it is already present in the filter and there's no whitespace at the end of it if (!itr.hasNext() && !filterTokens.contains(labelToken) && !spaceAtTheEnd) { elementSuffixes.add(labelToken.substring(filterToken.length())); } } } // If there's whitespace at the end, add complete word suggestions as well if (shouldSuggest(filterTokens, labelToken) && spaceAtTheEnd) { elementSuffixes.add(labelToken); } } return Iterables.toArray(elementSuffixes, String.class); }
From source file:net.awairo.mcmod.spawnchecker.client.common.MultiServerWorldSeedConfig.java
private static ImmutableTable<String, Integer, Long> load(String[] worldSeeds) { final Pattern pattern = Pattern.compile("^\"([^\"]+)\"$"); final Splitter keyValue = Splitter.on('='); final Splitter hostPort = Splitter.on(':'); final ImmutableTable.Builder<String, Integer, Long> builder = ImmutableTable.builder(); for (String seedConfig : worldSeeds) { final Matcher m = pattern.matcher(seedConfig); if (!m.matches()) { LOGGER.warn("removed {} from world seed configurations. (illegal format)", seedConfig); continue; }/* w ww . j a va 2 s. co m*/ final Iterator<String> kv = keyValue.split(m.group(1)).iterator(); if (!kv.hasNext()) { LOGGER.warn("removed {} from world seed configurations. (illegal address)", seedConfig); continue; } final Iterator<String> hp = hostPort.split(kv.next()).iterator(); if (!kv.hasNext()) { LOGGER.warn("removed {} from world seed configurations. (illegal seed)", seedConfig); continue; } if (!hp.hasNext()) { LOGGER.warn("removed {} from world seed configurations. (illegal address)", seedConfig); continue; } final Long seed = Longs.tryParse(kv.next()); if (seed == null) { LOGGER.warn("removed {} from world seed configurations. (illegal seed value)", seedConfig); continue; } final String host = hp.next(); final Integer port = hp.hasNext() ? Ints.tryParse(hp.next()) : DEFAULT_PORT; builder.put(host, port, seed); } return builder.build(); }
From source file:com.google.caliper.Arguments.java
public static Arguments parse(String[] argsArray) { Arguments result = new Arguments(); Iterator<String> args = Iterators.forArray(argsArray); String delimiter = defaultDelimiter; Map<String, String> userParameterStrings = Maps.newLinkedHashMap(); Map<String, String> vmParameterStrings = Maps.newLinkedHashMap(); String vmString = null;/*from www . ja v a2s. c o m*/ boolean standardRun = false; while (args.hasNext()) { String arg = args.next(); if ("--help".equals(arg)) { throw new DisplayUsageException(); } if (arg.startsWith("-D") || arg.startsWith("-J")) { /* * Handle user parameters (-D) and VM parameters (-J) of these forms: * * -Dlength=100 * -Jmemory=-Xmx1024M * -Dlength=100,200 * -Jmemory=-Xmx1024M,-Xmx2048M * -Dlength 100 * -Jmemory -Xmx1024M * -Dlength 100,200 * -Jmemory -Xmx1024M,-Xmx2048M */ String name; String value; int equalsSign = arg.indexOf('='); if (equalsSign == -1) { name = arg.substring(2); value = args.next(); } else { name = arg.substring(2, equalsSign); value = arg.substring(equalsSign + 1); } String previousValue; if (arg.startsWith("-D")) { previousValue = userParameterStrings.put(name, value); } else { previousValue = vmParameterStrings.put(name, value); } if (previousValue != null) { throw new UserException.DuplicateParameterException(arg); } standardRun = true; // TODO: move warmup/run to caliperrc } else if ("--captureVmLog".equals(arg)) { result.captureVmLog = true; standardRun = true; } else if ("--warmupMillis".equals(arg)) { result.warmupMillis = Long.parseLong(args.next()); standardRun = true; } else if ("--runMillis".equals(arg)) { result.runMillis = Long.parseLong(args.next()); standardRun = true; } else if ("--trials".equals(arg)) { String value = args.next(); try { result.trials = Integer.parseInt(value); if (result.trials < 1) { throw new UserException.InvalidTrialsException(value); } } catch (NumberFormatException e) { throw new UserException.InvalidTrialsException(value); } standardRun = true; } else if ("--vm".equals(arg)) { if (vmString != null) { throw new UserException.DuplicateParameterException(arg); } vmString = args.next(); standardRun = true; } else if ("--delimiter".equals(arg)) { delimiter = args.next(); standardRun = true; } else if ("--timeUnit".equals(arg)) { result.timeUnit = args.next(); standardRun = true; } else if ("--instanceUnit".equals(arg)) { result.instanceUnit = args.next(); standardRun = true; } else if ("--memoryUnit".equals(arg)) { result.memoryUnit = args.next(); standardRun = true; } else if ("--saveResults".equals(arg) || "--xmlSave".equals(arg)) { // TODO: unsupport legacy --xmlSave result.saveResultsFile = new File(args.next()); standardRun = true; } else if ("--uploadResults".equals(arg)) { result.uploadResultsFile = new File(args.next()); } else if ("--printScore".equals(arg)) { result.printScore = true; standardRun = true; } else if ("--measureMemory".equals(arg)) { result.measureMemory = true; standardRun = true; } else if ("--debug".equals(arg)) { result.debug = true; } else if ("--debug-reps".equals(arg)) { String value = args.next(); try { result.debugReps = Integer.parseInt(value); if (result.debugReps < 1) { throw new UserException.InvalidDebugRepsException(value); } } catch (NumberFormatException e) { throw new UserException.InvalidDebugRepsException(value); } } else if ("--marker".equals(arg)) { result.marker = args.next(); } else if ("--measurementType".equals(arg)) { String measurementType = args.next(); try { result.measurementType = MeasurementType.valueOf(measurementType); } catch (Exception e) { throw new InvalidParameterValueException(arg, measurementType); } standardRun = true; } else if ("--primaryMeasurementType".equals(arg)) { String measurementType = args.next().toUpperCase(); try { result.primaryMeasurementType = MeasurementType.valueOf(measurementType); } catch (Exception e) { throw new InvalidParameterValueException(arg, measurementType); } standardRun = true; } else if (arg.startsWith("-")) { throw new UnrecognizedOptionException(arg); } else { if (result.suiteClassName != null) { throw new MultipleBenchmarkClassesException(result.suiteClassName, arg); } result.suiteClassName = arg; } } Splitter delimiterSplitter = Splitter.on(delimiter); if (vmString != null) { Iterables.addAll(result.userVms, delimiterSplitter.split(vmString)); } Set<String> duplicates = Sets.intersection(userParameterStrings.keySet(), vmParameterStrings.keySet()); if (!duplicates.isEmpty()) { throw new UserException.DuplicateParameterException(duplicates); } for (Map.Entry<String, String> entry : userParameterStrings.entrySet()) { result.userParameters.putAll(entry.getKey(), delimiterSplitter.split(entry.getValue())); } for (Map.Entry<String, String> entry : vmParameterStrings.entrySet()) { result.vmParameters.putAll(entry.getKey(), delimiterSplitter.split(entry.getValue())); } if (standardRun && result.uploadResultsFile != null) { throw new IncompatibleArgumentsException("--uploadResults"); } if (result.suiteClassName == null && result.uploadResultsFile == null) { throw new NoBenchmarkClassException(); } if (result.primaryMeasurementType != null && result.primaryMeasurementType != MeasurementType.TIME && !result.measureMemory) { throw new IncompatibleArgumentsException( "--primaryMeasurementType " + result.primaryMeasurementType.toString().toLowerCase()); } return result; }
From source file:eu.esdihumboldt.hale.io.gml.geometry.GMLGeometryUtil.java
/** * Parse a tuple in a GML CoordinatesType string. * //from w w w.java2 s . com * @param tuple the tuple * @param coordinateSplitter the coordinate splitter * @param format the number format * @return the coordinate or <code>null</code> * @throws ParseException if parsing the coordinates fails */ private static Coordinate parseTuple(String tuple, Splitter coordinateSplitter, NumberFormat format) throws ParseException { if (tuple == null || tuple.isEmpty()) { return null; } double x = Double.NaN; double y = Double.NaN; double z = Double.NaN; Iterable<String> coordinates = coordinateSplitter.split(tuple); Iterator<String> itCoordinates = coordinates.iterator(); int index = 0; while (index <= 2 && itCoordinates.hasNext()) { String coord = itCoordinates.next(); // parse coordinate value Number value = format.parse(coord); switch (index) { case 0: x = value.doubleValue(); break; case 1: y = value.doubleValue(); break; case 2: z = value.doubleValue(); break; } index++; } return new Coordinate(x, y, z); }
From source file:com.google.caliper.util.CommandLineParser.java
/** * * @param argsArray/*www .j a v a 2 s . com*/ * @return */ public static CommandLineParser parse(String[] argsArray) { CommandLineParser result = new CommandLineParser(); Iterator<String> args = Iterators.forArray(argsArray); String delimiter = defaultDelimiter; Map<String, String> userParameterStrings = Maps.newLinkedHashMap(); Map<String, String> vmParameterStrings = Maps.newLinkedHashMap(); String vmString = null; boolean standardRun = false; while (args.hasNext()) { String arg = args.next(); if ("--help".equals(arg)) { throw new DisplayUsageException(); } if (arg.startsWith("-D") || arg.startsWith("-J")) { /* * Handle user parameters (-D) and VM parameters (-J) of these forms: * * -Dlength=100 * -Jmemory=-Xmx1024M * -Dlength=100,200 * -Jmemory=-Xmx1024M,-Xmx2048M * -Dlength 100 * -Jmemory -Xmx1024M * -Dlength 100,200 * -Jmemory -Xmx1024M,-Xmx2048M */ String name; String value; int equalsSign = arg.indexOf('='); if (equalsSign == -1) { name = arg.substring(2); value = args.next(); } else { name = arg.substring(2, equalsSign); value = arg.substring(equalsSign + 1); } String previousValue; if (arg.startsWith("-D")) { previousValue = userParameterStrings.put(name, value); } else { previousValue = vmParameterStrings.put(name, value); } if (previousValue != null) { throw new UserException.DuplicateParameterException(arg); } standardRun = true; // TODO: move warmup/run to caliperrc } else if ("--captureVmLog".equals(arg)) { result.captureVmLog = true; standardRun = true; } else if ("--warmupMillis".equals(arg)) { result.warmupMillis = Long.parseLong(args.next()); standardRun = true; } else if ("--runMillis".equals(arg)) { result.runMillis = Long.parseLong(args.next()); standardRun = true; } else if ("--trials".equals(arg)) { String value = args.next(); try { result.trials = Integer.parseInt(value); if (result.trials < 1) { throw new UserException.InvalidTrialsException(value); } } catch (NumberFormatException e) { throw new UserException.InvalidTrialsException(value); } standardRun = true; } else if ("--vm".equals(arg)) { if (vmString != null) { throw new UserException.DuplicateParameterException(arg); } vmString = args.next(); standardRun = true; } else if ("--delimiter".equals(arg)) { delimiter = args.next(); standardRun = true; } else if ("--useBenchmarkName".equals(arg)) { result.useBenchmarkName = true; standardRun = true; } else if ("--timeUnit".equals(arg)) { result.timeUnit = args.next(); standardRun = true; } else if ("--instanceUnit".equals(arg)) { result.instanceUnit = args.next(); standardRun = true; } else if ("--memoryUnit".equals(arg)) { result.memoryUnit = args.next(); standardRun = true; } else if ("--reportType".equals(arg)) { result.reportType = args.next(); System.out.println("Report type: " + result.reportType); } else if ("--pluginFolder".equals(arg)) { result.pluginFolder = new File(args.next()); } else if ("--saveResults".equals(arg) || "--xmlSave".equals(arg)) { // TODO: unsupport legacy --xmlSave result.outputFile = new File(args.next()); standardRun = true; } else if ("--printScore".equals(arg)) { result.printScore = true; standardRun = true; } else if ("--measureMemory".equals(arg)) { result.measureMemory = true; standardRun = true; } else if ("--debug".equals(arg)) { result.debug = true; } else if ("--debug-reps".equals(arg)) { String value = args.next(); try { result.debugReps = Integer.parseInt(value); if (result.debugReps < 1) { throw new UserException.InvalidDebugRepsException(value); } } catch (NumberFormatException e) { throw new UserException.InvalidDebugRepsException(value); } } else if ("--marker".equals(arg)) { result.marker = args.next(); } else if ("--measurementType".equals(arg)) { String measurementType = args.next(); try { result.measurementType = MeasurementType.valueOf(measurementType); } catch (Exception e) { throw new InvalidParameterValueException(arg, measurementType); } standardRun = true; } else if ("--primaryMeasurementType".equals(arg)) { String measurementType = args.next().toUpperCase(); try { result.primaryMeasurementType = MeasurementType.valueOf(measurementType); } catch (Exception e) { throw new InvalidParameterValueException(arg, measurementType); } standardRun = true; } else if (arg.startsWith("-")) { throw new UnrecognizedOptionException(arg); } else { if (result.suiteClassName != null) { throw new MultipleBenchmarkClassesException(result.suiteClassName, arg); } result.suiteClassName = arg; } } Splitter delimiterSplitter = Splitter.on(delimiter); if (vmString != null) { Iterables.addAll(result.userVms, delimiterSplitter.split(vmString)); } Set<String> duplicates = Sets.intersection(userParameterStrings.keySet(), vmParameterStrings.keySet()); if (!duplicates.isEmpty()) { throw new UserException.DuplicateParameterException(duplicates); } for (Map.Entry<String, String> entry : userParameterStrings.entrySet()) { result.userParameters.putAll(entry.getKey(), delimiterSplitter.split(entry.getValue())); } for (Map.Entry<String, String> entry : vmParameterStrings.entrySet()) { result.vmParameters.putAll(entry.getKey(), delimiterSplitter.split(entry.getValue())); } if (result.suiteClassName == null) { throw new NoBenchmarkClassException(); } if (result.primaryMeasurementType != null && result.primaryMeasurementType != MeasurementType.TIME && !result.measureMemory) { throw new IncompatibleArgumentsException( "--primaryMeasurementType " + result.primaryMeasurementType.toString().toLowerCase()); } return result; }
From source file:gobblin.util.AvroUtils.java
/** * Given a GenericRecord, this method will return the schema of the field specified by the path parameter. The * fieldLocation parameter is an ordered string specifying the location of the nested field to retrieve. For example, * field1.nestedField1 takes the the schema of the field "field1", and retrieves the schema "nestedField1" from it. * @param schema is the record to retrieve the schema from * @param fieldLocation is the location of the field * @return the schema of the field/*from w w w . j av a 2s .c o m*/ */ public static Optional<Schema> getFieldSchema(Schema schema, String fieldLocation) { Preconditions.checkNotNull(schema); Preconditions.checkArgument(!Strings.isNullOrEmpty(fieldLocation)); Splitter splitter = Splitter.on(FIELD_LOCATION_DELIMITER).omitEmptyStrings().trimResults(); List<String> pathList = Lists.newArrayList(splitter.split(fieldLocation)); if (pathList.size() == 0) { return Optional.absent(); } return AvroUtils.getFieldSchemaHelper(schema, pathList, 0); }
From source file:gobblin.util.AvroUtils.java
/** * Given a GenericRecord, this method will return the field specified by the path parameter. The * fieldLocation parameter is an ordered string specifying the location of the nested field to retrieve. For example, * field1.nestedField1 takes field "field1", and retrieves "nestedField1" from it. * @param schema is the record to retrieve the schema from * @param fieldLocation is the location of the field * @return the field// w w w.java2 s .c om */ public static Optional<Field> getField(Schema schema, String fieldLocation) { Preconditions.checkNotNull(schema); Preconditions.checkArgument(!Strings.isNullOrEmpty(fieldLocation)); Splitter splitter = Splitter.on(FIELD_LOCATION_DELIMITER).omitEmptyStrings().trimResults(); List<String> pathList = Lists.newArrayList(splitter.split(fieldLocation)); if (pathList.size() == 0) { return Optional.absent(); } return AvroUtils.getFieldHelper(schema, pathList, 0); }