com.google.common.base.Splitter Java Examples

The following examples show how to use com.google.common.base.Splitter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GitRepository.java    From copybara with Apache License 2.0 6 votes vote down vote up
/**
 * Execute show-ref git command in the local repository and returns a map from reference name to
 * GitReference(SHA-1).
 */
private ImmutableMap<String, GitRevision> showRef(Iterable<String> refs)
    throws RepoException {
  ImmutableMap.Builder<String, GitRevision> result = ImmutableMap.builder();
  CommandOutput commandOutput = gitAllowNonZeroExit(NO_INPUT,
      ImmutableList.<String>builder().add("show-ref").addAll(refs).build(),
      DEFAULT_TIMEOUT);

  if (!commandOutput.getStderr().isEmpty()) {
    throw new RepoException(String.format(
        "Error executing show-ref on %s git repo:\n%s", getGitDir(), commandOutput.getStderr()));
  }

  for (String line : Splitter.on('\n').split(commandOutput.getStdout())) {
    if (line.isEmpty()) {
      continue;
    }
    List<String> strings = Splitter.on(' ').splitToList(line);
    Preconditions.checkState(strings.size() == 2
        && SHA1_PATTERN.matcher(strings.get(0)).matches(), "Cannot parse line: '%s'", line);
    // Ref -> SHA1
    result.put(strings.get(1), new GitRevision(this, strings.get(0)));
  }
  return result.build();
}
 
Example #2
Source File: ModelRegistry.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
public ModelMeta resolve(String query) {
    return Splitter.on("::") // Extract embedded Ruby classes
            .splitToList(query)
            .stream()
            .sorted(Comparator.reverseOrder()) // Give priority to descendants
            .filter(byName::containsKey)
            .map(byName::get)
            .findFirst()
            .orElseThrow(() -> new NoSuchModelException("No registered model named '" + query + "'"));
}
 
Example #3
Source File: LcovPrinterTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testPrintOneFile() throws IOException {
  coverage.add(sourceFileCoverage1);
  assertThat(LcovPrinter.print(byteOutputStream, coverage)).isTrue();
  byteOutputStream.close();
  Iterable<String> fileLines = Splitter.on('\n').split(byteOutputStream.toString());
  // Last line of the file will always be a newline.
  assertThat(fileLines).hasSize(TRACEFILE1.size() + 1);
  int lineIndex = 0;
  for (String line : fileLines) {
    if (lineIndex == TRACEFILE1.size()) {
      break;
    }
    assertThat(line).isEqualTo(TRACEFILE1.get(lineIndex++));
  }
}
 
Example #4
Source File: AaptCommandBuilderTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testParamFile() throws IOException {

  final List<String> resources =
      IntStream.range(0, 201).mapToObj(i -> "res" + i).collect(toList());
  assertThat(
          new AaptCommandBuilder(aapt)
              .addParameterableRepeated("-R", resources, workingDirectory)
              .build())
      .containsAtLeast("-R", "@" + workingDirectory.resolve("params-R"));
  assertThat(
          Files.readAllLines(workingDirectory.resolve("params-R"), StandardCharsets.UTF_8)
              .stream()
              .map(Splitter.on(' ')::split)
              .flatMap(Streams::stream)
              .collect(toList()))
      .containsAtLeastElementsIn(resources);
}
 
Example #5
Source File: AckMessageTask.java    From AvatarMQ with Apache License 2.0 6 votes vote down vote up
public Long call() throws Exception {
    for (int i = 0; i < messages.length; i++) {
        boolean error = false;
        ProducerAckMessage ack = new ProducerAckMessage();
        Object[] msg = Splitter.on(MessageSystemConfig.MessageDelimiter).trimResults().splitToList(messages[i]).toArray();
        if (msg.length == 2) {
            ack.setAck((String) msg[0]);
            ack.setMsgId((String) msg[1]);

            if (error) {
                ack.setStatus(ProducerAckMessage.FAIL);
            } else {
                ack.setStatus(ProducerAckMessage.SUCCESS);
                count.incrementAndGet();
            }

            AckTaskQueue.pushAck(ack);
            SemaphoreCache.release(MessageSystemConfig.AckTaskSemaphoreValue);
        }
    }

    barrier.await();
    return count.get();
}
 
Example #6
Source File: ClassWrapperRenderer.java    From otroslogviewer with Apache License 2.0 6 votes vote down vote up
public String abbreviatePackagesToSingleLetter(String abbreviatePackage, int availableWidth, FontMetrics fm) {
  String result = abbreviatePackage;
  if (fm.stringWidth(result) > availableWidth) {
    final java.util.List<String> split = Splitter.on('.').splitToList(result);
    int index = 0;
    while (fm.stringWidth(result) > availableWidth && index < split.size() - 1) {
      java.util.List<String> list = new ArrayList<>(split.size());
      for (int i = 0; i < split.size(); i++) {
        final String s = split.get(i);
        list.add(i <= index && s.length() > 0 ? s.substring(0, 1) : s);
      }
      result = Joiner.on(".").join(list);
      index++;
    }
  }
  return result;
}
 
Example #7
Source File: PublicSectionMetadataScrubber.java    From MOE with Apache License 2.0 6 votes vote down vote up
@Override
public RevisionMetadata execute(RevisionMetadata rm, MetadataScrubberConfig unused) {
  List<String> lines = Splitter.on('\n').splitToList(rm.description());
  int startPublicSection = -1;
  int endPublicSection = -1;
  int currentLine = 0;
  for (String line : lines) {
    if (PUBLIC_SECTION_PATTERN.matcher(line).matches()) {
      startPublicSection = currentLine;
      endPublicSection = lines.size();
    } else if (startPublicSection >= 0 && END_PUBLIC_SECTION_PATTERN.matcher(line).matches()) {
      endPublicSection = currentLine;
    }
    ++currentLine;
  }

  String newDesc =
      (startPublicSection >= 0)
          ? Joiner.on("\n").join(lines.subList(startPublicSection + 1, endPublicSection))
          : rm.description();
  return rm.toBuilder().description(newDesc).build();
}
 
Example #8
Source File: PropertyFileDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void run(@NonNull Context context) {
    String contents = context.getContents();
    if (contents == null) {
        return;
    }
    int offset = 0;
    Iterator<String> iterator = Splitter.on('\n').split(contents).iterator();
    String line;
    for (; iterator.hasNext(); offset += line.length() + 1) {
        line = iterator.next();
        if (line.startsWith("#") || line.startsWith(" ")) {
            continue;
        }
        if (line.indexOf('\\') == -1 && line.indexOf(':') == -1) {
            continue;
        }
        int valueStart = line.indexOf('=') + 1;
        if (valueStart == 0) {
            continue;
        }
        checkLine(context, contents, line, offset, valueStart);
    }
}
 
Example #9
Source File: PageCategoryService.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
private void notifyPageUpdated(PageCategory pageCategory) {
    CategoryUpdatedMessage message = new CategoryUpdatedMessage();
    message.id = pageCategory.id;
    message.parentId = pageCategory.parentId;
    message.parentIds = pageCategory.parentIds == null ? Lists.newArrayList() : Splitter.on(";").splitToList(pageCategory.parentIds);
    message.displayName = pageCategory.displayName;
    message.description = pageCategory.description;
    message.imageURL = pageCategory.imageURL;
    message.displayOrder = pageCategory.displayOrder;
    message.keywords = pageCategory.keywords == null ? ImmutableList.of() : Splitter.on(";").splitToList(pageCategory.keywords);
    message.tags = pageCategory.tags == null ? ImmutableList.of() : Splitter.on(";").splitToList(pageCategory.tags);
    message.fields = pageCategory.fields == null ? ImmutableMap.of() : JSON.fromJSON(pageCategory.fields, Map.class);
    message.status = pageCategory.status;
    message.ownerId = pageCategory.ownerId;
    message.ownerRoles = pageCategory.ownerRoles == null ? ImmutableList.of() : Splitter.on(";").splitToList(pageCategory.ownerRoles);
    message.groupId = pageCategory.groupId;
    message.groupRoles = pageCategory.groupRoles == null ? ImmutableList.of() : Splitter.on(";").splitToList(pageCategory.groupRoles);
    message.othersRoles = pageCategory.othersRoles == null ? ImmutableList.of() : Splitter.on(";").splitToList(pageCategory.othersRoles);
    message.updatedTime = OffsetDateTime.now();
    message.updatedBy = pageCategory.updatedBy;
    message.createdTime = OffsetDateTime.now();
    message.createdBy = pageCategory.createdBy;
    categoryUpdatedMessageMessagePublisher.publish(message);
}
 
Example #10
Source File: EtcdClient.java    From caravan with Apache License 2.0 6 votes vote down vote up
private String generateRequestUrl(String key, Map<String, String> params) {
    List<String> keyParts = Splitter.on('/').trimResults().omitEmptyStrings().splitToList(key);
    if (CollectionValues.isNullOrEmpty(keyParts))
        throw new IllegalArgumentException("key format is invalid: " + key);

    String rawUrl = _serviceUrlPrefix;
    try {
        for (String part : keyParts) {
            rawUrl = StringValues.concatPathParts(rawUrl, URLEncoder.encode(part, Charsets.UTF_8.name()));
        }
    } catch (Exception ex) {
        throw new IllegalArgumentException("Cannot url encode the key: " + key, ex);
    }

    if (MapValues.isNullOrEmpty(params))
        return rawUrl;

    StringBuffer rawUrlBuf = new StringBuffer(rawUrl).append("?");

    for (String paramKey : params.keySet()) {
        rawUrlBuf.append(paramKey).append("=").append(params.get(paramKey)).append("&");
    }

    return StringValues.trimEnd(rawUrlBuf.toString(), '&');
}
 
Example #11
Source File: MetamodelUtil.java    From javaee-lab with Apache License 2.0 6 votes vote down vote up
public List<Attribute<?, ?>> toAttributes(String path, Class<?> from) {
    try {
        List<Attribute<?, ?>> attributes = newArrayList();
        Class<?> current = from;
        for (String pathItem : Splitter.on(".").split(path)) {
            Class<?> metamodelClass = getCachedClass(current);
            Field field = metamodelClass.getField(pathItem);
            Attribute<?, ?> attribute = (Attribute<?, ?>) field.get(null);
            attributes.add(attribute);
            if (attribute instanceof PluralAttribute) {
                current = ((PluralAttribute<?, ?, ?>) attribute).getElementType().getJavaType();
            } else {
                current = attribute.getJavaType();
            }
        }
        return attributes;
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #12
Source File: LogSearchConfigZKHelper.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
/**
 * Get ACLs from a property (get the value then parse and transform it as ACL objects)
 * @param properties key/value pairs that needs to be parsed as ACLs
 * @return list of ACLs
 */
public static List<ACL> getAcls(Map<String, String> properties) {
  String aclStr = properties.get(ZK_ACLS_PROPERTY);
  if (StringUtils.isBlank(aclStr)) {
    return ZooDefs.Ids.OPEN_ACL_UNSAFE;
  }

  List<ACL> acls = new ArrayList<>();
  List<String> aclStrList = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(aclStr);
  for (String unparcedAcl : aclStrList) {
    String[] parts = unparcedAcl.split(":");
    if (parts.length == 3) {
      acls.add(new ACL(parsePermission(parts[2]), new Id(parts[0], parts[1])));
    }
  }
  return acls;
}
 
Example #13
Source File: EndToEndTest.java    From js-dossier with Apache License 2.0 6 votes vote down vote up
private static String normalizeLines(String in) {
  Iterable<String> lines = Splitter.on('\n').split(in);
  lines =
      StreamSupport.stream(lines.spliterator(), false)
          .filter(Objects::nonNull)
          .map(
              input -> {
                int end = input.length();
                while (end > 0 && input.charAt(end - 1) <= ' ') {
                  end -= 1;
                }
                return input.substring(0, end);
              })
          .collect(Collectors.toList());
  return Joiner.on('\n').join(lines).trim();
}
 
Example #14
Source File: CsvConfigFileWriter.java    From oodt with Apache License 2.0 6 votes vote down vote up
@Override
public File generateFile(String filePath, Metadata metadata, Logger logger,
      Object... customArgs) throws IOException {
   checkArgument(customArgs.length > 0,
         CsvConfigFileWriter.class.getCanonicalName()
               + " has no args specified");
   List<String> header = checkNotNull(
         Lists.newArrayList(Splitter.on(",").split(
               (String) customArgs[HEADER_INDEX])),
         "Must specify CSV header in args at index = '" + HEADER_INDEX + "'");
   String delim = DEFAULT_DELIM;
   if (customArgs.length > DELIM_INDEX) {
      delim = (String) customArgs[DELIM_INDEX];
   }

   return writeCsvFile(filePath, header, generateRows(header, metadata),
         delim);
}
 
Example #15
Source File: DotTest.java    From buck with Apache License 2.0 6 votes vote down vote up
private static void assertOutput(
    String dotGraph, ImmutableSet<String> expectedEdges, boolean colors) {
  List<String> lines =
      Lists.newArrayList(Splitter.on(System.lineSeparator()).omitEmptyStrings().split(dotGraph));

  assertEquals("digraph the_graph {", lines.get(0));

  // remove attributes because we are not interested what styles and colors are default
  if (!colors) {
    lines = lines.stream().map(p -> p.replaceAll(" \\[.*]", "")).collect(Collectors.toList());
  }

  List<String> edges = lines.subList(1, lines.size() - 1);
  edges.sort(Ordering.natural());
  assertEquals(edges, ImmutableList.copyOf(ImmutableSortedSet.copyOf(expectedEdges)));

  assertEquals("}", lines.get(lines.size() - 1));
}
 
Example #16
Source File: StringEL.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@ElFunction(
    prefix = "str",
    name = "splitKV",
    description = "Splits key value pairs into a map"
)
public static Map<String, Field> splitKV(
    @ElParam("string") String string,
    @ElParam("pairSeparator") String separator,
    @ElParam("kvSeparator") String kvSeparator) {
  if (Strings.isNullOrEmpty(string)) {
    return Collections.emptyMap();
  }

  Splitter.MapSplitter splitter = Splitter.on(separator).trimResults().omitEmptyStrings().withKeyValueSeparator(Splitter.on(kvSeparator).limit(2));

  return splitter.split(string).entrySet().stream()
      .collect(Collectors.toMap(Map.Entry::getKey, e -> Field.create(e.getValue())));
}
 
Example #17
Source File: ZKUtil.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Parse a comma-separated list of authentication mechanisms. Each
 * such mechanism should be of the form 'scheme:auth' -- the same
 * syntax used for the 'addAuth' command in the ZK CLI.
 * 
 * @param authString the comma-separated auth mechanisms
 * @return a list of parsed authentications
 * @throws {@link BadAuthFormatException} if the auth format is invalid
 */
public static List<ZKAuthInfo> parseAuth(String authString) throws
    BadAuthFormatException{
  List<ZKAuthInfo> ret = Lists.newArrayList();
  if (authString == null) {
    return ret;
  }
  
  List<String> authComps = Lists.newArrayList(
      Splitter.on(',').omitEmptyStrings().trimResults()
      .split(authString));
  
  for (String comp : authComps) {
    String parts[] = comp.split(":", 2);
    if (parts.length != 2) {
      throw new BadAuthFormatException(
          "Auth '" + comp + "' not of expected form scheme:auth");
    }
    ret.add(new ZKAuthInfo(parts[0],
        parts[1].getBytes(Charsets.UTF_8)));
  }
  return ret;
}
 
Example #18
Source File: CsvToKeyValueMapper.java    From phoenix with Apache License 2.0 6 votes vote down vote up
/**
 * Build the list of ColumnInfos for the import based on information in the configuration.
 */
@VisibleForTesting
static List<ColumnInfo> buildColumnInfoList(Configuration conf) {

    return Lists.newArrayList(
            Iterables.transform(
                    Splitter.on("|").split(conf.get(COLUMN_INFO_CONFKEY)),
                    new Function<String, ColumnInfo>() {
                        @Nullable
                        @Override
                        public ColumnInfo apply(@Nullable String input) {
                            if (input.isEmpty()) {
                                // An empty string represents a null that was passed in to
                                // the configuration, which corresponds to an input column
                                // which is to be skipped
                                return null;
                            }
                            return ColumnInfo.fromString(input);
                        }
                    }));
}
 
Example #19
Source File: I18nUtils.java    From I18nUpdateMod with MIT License 6 votes vote down vote up
/**
 * 依据等号切分字符串,将 list 处理成 Map
 *
 * @param listIn 想要处理的字符串 list
 * @return 处理好的 Map
 */
public static Map<String, String> listToMap(List<String> listIn) {
    HashMap<String, String> mapOut = new HashMap<>();

    // 抄袭原版加载方式
    Splitter I18N_SPLITTER = Splitter.on('=').limit(2);

    // 遍历拆分
    for (String s : listIn) {
        if (!s.isEmpty() && s.charAt(0) != '#') {
            String[] splitString = Iterables.toArray(I18N_SPLITTER.split(s), String.class);

            if (splitString != null && splitString.length == 2) {
                String s1 = splitString[0];
                String s2 = splitString[1];
                mapOut.put(s1, s2);
            }
        }
    }
    return mapOut;
}
 
Example #20
Source File: Experiment.java    From science-journal with Apache License 2.0 6 votes vote down vote up
/** Returns a path that starts after the experiment id. Probably starts with "assets". */
private String getPathRelativeToExperiment(String path) {
  if (Strings.isNullOrEmpty(path)) {
    return path;
  }
  if (path.startsWith(EXPERIMENTS)) {
    List<String> splitList = Splitter.on('/').splitToList(path);
    StringBuilder experimentPath = new StringBuilder();
    String delimiter = "";
    for (int i = 2; i < splitList.size(); i++) {
      experimentPath.append(delimiter).append(splitList.get(i));
      delimiter = "/";
    }
    return experimentPath.toString();
  }
  return path;
}
 
Example #21
Source File: MapreduceTestCase.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private static Map<String, String> decodeParameters(String requestBody)
    throws UnsupportedEncodingException {
  Map<String, String> result = new HashMap<>();

  Iterable<String> params = Splitter.on('&').split(requestBody);
  for (String param : params) {
    List<String> pair = Splitter.on('=').splitToList(param);
    String name = pair.get(0);
    String value = URLDecoder.decode(pair.get(1), "UTF-8");
    if (result.containsKey(name)) {
      throw new IllegalArgumentException("Duplicate parameter: " + requestBody);
    }
    result.put(name, value);
  }

  return result;
}
 
Example #22
Source File: TyposquattingStrategiesTest.java    From metron with Apache License 2.0 5 votes vote down vote up
@BeforeAll
public static void setup() throws Exception {
  for(Map.Entry<String, EnumMap<TyposquattingStrategies, Set<String>>> kv : expected.entrySet()) {
    try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/typosquat/" + kv.getKey() + ".csv"), StandardCharsets.UTF_8) ) )
    {
      for(String line = null;(line = br.readLine()) != null;) {
        if(line.startsWith("#")) {
          continue;
        }
        Iterable<String> tokens = Splitter.on(",").split(line);
        String name = Iterables.get(tokens, 0);
        String domain = Iterables.get(tokens, 1);
        domain = domain.replaceAll(".com", "");
        EnumMap<TyposquattingStrategies, Set<String>> expectedValues = kv.getValue();
        if(typesToSkip.contains(name)) {
          continue;
        }
        TyposquattingStrategies strategy = TyposquattingStrategies.byName(name);
        assertNotNull(strategy, "Couldn't find " + name);
        Set<String> s = expectedValues.get(strategy);
        if(s == null) {
          s = new HashSet<>();
          expectedValues.put(strategy, s);
        }
        s.add(domain);
      }
    }
  }
}
 
Example #23
Source File: TreeView.java    From LuckPerms with MIT License 5 votes vote down vote up
/**
 * Finds the root of the tree node at the given position
 *
 * @param source the node source
 * @return the root, if it exists
 */
private static Optional<TreeNode> findRoot(String rootPosition, PermissionRegistry source) {
    // get the root of the permission vault
    TreeNode root = source.getRootNode();

    // just return the root
    if (rootPosition.equals(".")) {
        return Optional.of(root);
    }

    // get the parts of the node
    List<String> parts = Splitter.on('.').omitEmptyStrings().splitToList(rootPosition);

    // for each part
    for (String part : parts) {

        // check the current root has some children
        if (!root.getChildren().isPresent()) {
            return Optional.empty();
        }

        // get the current roots children
        Map<String, TreeNode> branch = root.getChildren().get();

        // get the new root
        root = branch.get(part);
        if (root == null) {
            return Optional.empty();
        }
    }

    return Optional.of(root);
}
 
Example #24
Source File: FilterOptions.java    From mojito with Apache License 2.0 5 votes vote down vote up
public FilterOptions(List<String> options) {
    if (options != null) {
        for (String option : options) {
            List<String> optionKeyAndValue = Splitter.on("=").limit(2).splitToList(option);
            if (optionKeyAndValue.size() == 2) {
                this.options.put(optionKeyAndValue.get(0), optionKeyAndValue.get(1));
            }
        }
    }
}
 
Example #25
Source File: ManagedHiveSchema.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public ManagedHiveSchema(final JobConf jobConf, final HiveReaderProto.HiveTableXattr tableXattr) {
  final java.util.Properties tableProperties = new java.util.Properties();
  HiveUtilities.addProperties(jobConf, tableProperties, HiveReaderProtoUtil.getTableProperties(tableXattr));
  final String fieldNameProp = Optional.ofNullable(tableProperties.getProperty("columns")).orElse("");
  final String fieldTypeProp = Optional.ofNullable(tableProperties.getProperty("columns.types")).orElse("");
  varcharTruncationEnabled = HiveDatasetOptions
      .enforceVarcharWidth(HiveReaderProtoUtil.convertValuesToNonProtoAttributeValues(tableXattr.getDatasetOptionMap()));

  final Iterator<String> fieldNames = Splitter.on(",").trimResults().split(fieldNameProp).iterator();
  final Iterator<TypeInfo> fieldTypes = TypeInfoUtils.getTypeInfosFromTypeString(fieldTypeProp).iterator();

  final Map<String, ManagedSchemaField> schemaFieldMap = new HashMap<>();
  final Map<String, TypeInfo> typeInfoMap = new HashMap<>();
  while (fieldNames.hasNext() && fieldTypes.hasNext()) {
    final String fieldName = fieldNames.next();
    final TypeInfo fieldType = fieldTypes.next();
    ManagedSchemaField field;
    if (fieldType instanceof DecimalTypeInfo) {
      field = ManagedSchemaField.newFixedLenField(fieldName, fieldType.getTypeName(),
        ((DecimalTypeInfo) fieldType).getPrecision(), ((DecimalTypeInfo) fieldType).getScale());
      typeInfoMap.put(fieldName, fieldType);
    } else if (fieldType instanceof BaseCharTypeInfo) {
      if (varcharTruncationEnabled) {
        field = ManagedSchemaField.newFixedLenField(fieldName, fieldType.getTypeName(),
            ((BaseCharTypeInfo) fieldType).getLength(), 0);
        typeInfoMap.put(fieldName, fieldType);
      } else {
        field = ManagedSchemaField.newUnboundedLenField(fieldName, fieldType.getTypeName());
      }
    } else {
      // Extend ManagedSchemaField.java in case granular information has to be stored.
      // No mention of len and scale means it is unbounded. So, we store max values.
      field = ManagedSchemaField.newUnboundedLenField(fieldName, fieldType.getTypeName());
      typeInfoMap.put(fieldName, fieldType);
    }
    schemaFieldMap.put(fieldName, field);
  }
  fieldInfo = CaseInsensitiveMap.newImmutableMap(schemaFieldMap);
  typeInfo = CaseInsensitiveMap.newImmutableMap(typeInfoMap);
}
 
Example #26
Source File: JsonRowDecoder.java    From presto with Apache License 2.0 5 votes vote down vote up
private static JsonNode locateNode(JsonNode tree, DecoderColumnHandle columnHandle)
{
    String mapping = columnHandle.getMapping();
    checkState(mapping != null, "No mapping for %s", columnHandle.getName());

    JsonNode currentNode = tree;
    for (String pathElement : Splitter.on('/').omitEmptyStrings().split(mapping)) {
        if (!currentNode.has(pathElement)) {
            return MissingNode.getInstance();
        }
        currentNode = currentNode.path(pathElement);
    }
    return currentNode;
}
 
Example #27
Source File: BungeeCordImpl.java    From helper with MIT License 5 votes vote down vote up
@Override
public boolean acceptResponse(Player receiver, ByteArrayDataInput in) {
    String csv = in.readUTF();

    if (csv.isEmpty()) {
        this.callback.supply(ImmutableList.of());
        return true;
    }

    this.callback.supply(ImmutableList.copyOf(Splitter.on(", ").splitToList(csv)));
    return true;
}
 
Example #28
Source File: RoutePattern.java    From minnal with Apache License 2.0 5 votes vote down vote up
/**
 * Splits the pattern by '/' into route elements
 * 
 * @return the elements
 */
public List<RouteElement> getElements() {
	List<RouteElement> elements = new ArrayList<RoutePattern.RouteElement>();
	for (String element : Splitter.on("/").split(pathPattern)) {
		elements.add(new RouteElement(element, PLACEHOLDER_PATTERN.matcher(element).matches()));
	}
	if (elements.isEmpty()) {
		System.out.println("");
	}
	elements.remove(0); // Remove the root
	return elements;
}
 
Example #29
Source File: CountersMap.java    From otroslogviewer with Apache License 2.0 5 votes vote down vote up
public static Deserializer<CountersMap, String> deserializer() {
  return (String value) -> {
    final Map<String, String> split = Splitter.on("\n").withKeyValueSeparator(SPERATOR).split(value);
    final Map<String, Long> collect = split
      .entrySet()
      .stream()
      .collect(Collectors.toMap(Map.Entry::getKey, entry -> new Long(entry.getValue())));
    return Optional.of(new CountersMap(collect));
  };
}
 
Example #30
Source File: TemplateUriValidator.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(ValidatorContext ctx)
{
  DataElement element = ctx.dataElement();
  Object value = element.getValue();
  String str = String.valueOf(value);
  boolean valid = true;

  try {
    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));
  }
}