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: 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 #2
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 #3
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 #4
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 #5
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 #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: 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 #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: 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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
Source File: AppYamlProjectStaging.java    From appengine-plugins-core with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
// Copies files referenced in "Class-Path" of Jar's MANIFEST.MF to the target directory. Assumes
// files are present at relative paths and that relative path should be preserved in the staged
// directory.
static void copyArtifactJarClasspath(
    AppYamlProjectStageConfiguration config, CopyService copyService) throws IOException {
  Path artifact = config.getArtifact();
  Path targetDirectory = config.getStagingDirectory();
  try (JarFile jarFile = new JarFile(artifact.toFile())) {
    String jarClassPath =
        jarFile.getManifest().getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
    if (jarClassPath == null) {
      return;
    }
    Iterable<String> classpathEntries = Splitter.onPattern("\\s+").split(jarClassPath.trim());
    for (String classpathEntry : classpathEntries) {
      // classpath entries are relative to artifact's position and relativeness should be
      // preserved
      // in the target directory
      Path jarSrc = artifact.getParent().resolve(classpathEntry);
      if (!Files.isRegularFile(jarSrc)) {
        log.warning("Could not copy 'Class-Path' jar: " + jarSrc + " referenced in MANIFEST.MF");
        continue;
      }
      Path jarTarget = targetDirectory.resolve(classpathEntry);

      if (Files.exists(jarTarget)) {
        log.fine(
            "Overwriting 'Class-Path' jar: "
                + jarTarget
                + " with "
                + jarSrc
                + " referenced in MANIFEST.MF");
      }
      copyService.copyFileAndReplace(jarSrc, jarTarget);
    }
  }
}
 
Example #23
Source File: SchemaValidator.java    From morf with Apache License 2.0 5 votes vote down vote up
@Override
public Set<String> get() {
  try {
    try (InputStream inputStream = getClass().getResourceAsStream("SQL_RESERVED_WORDS.txt")) {
      if (inputStream == null) {
        throw new RuntimeException("Could not find resource: [SQL_RESERVED_WORDS.txt] near [" + getClass() + "]");
      }
      try (InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8")) {
        HashSet<String> sqlReservedWords = Sets.newHashSet(Splitter.on("\r\n").split(CharStreams.toString(streamReader)));

        // temporary removal of words we currently have to allow
        sqlReservedWords.remove("TYPE");  // DB2
        sqlReservedWords.remove("OPERATION"); // DB2, SQL Server "future", PostGres
        sqlReservedWords.remove("METHOD"); // PostGres
        sqlReservedWords.remove("LANGUAGE"); // DB2, ODBC (?), SQL Server "future", PostGres
        sqlReservedWords.remove("LOCATION"); // PostGres
        sqlReservedWords.remove("YEAR"); // DB2, ODBC (?), SQL Server "future", PostGres
        sqlReservedWords.remove("DAY"); // DB2, ODBC (?), SQL Server "future", PostGres
        sqlReservedWords.remove("SECURITY"); // DB2, PostGres

        return ImmutableSet.copyOf(sqlReservedWords);
      }
    }
  } catch (IOException e) {
    throw new RuntimeException("Failed to load [SQL_RESERVED_WORDS.txt]", e);
  }
}
 
Example #24
Source File: TimoliaListener.java    From The-5zig-Mod with GNU General Public License v3.0 5 votes vote down vote up
private void getFriendsList(int page, final List<User> users) {
	getGameListener().sendAndIgnoreMultiple("/friends " + page, "friends.list.title", 2, "friends.list.page_not_found", new Callback<IMultiPatternResult>() {
		@Override
		public void call(IMultiPatternResult callback) {
			IPatternResult pages = callback.parseKey("friends.list.title");
			final int currentPage = pages.get(1) == null ? 1 : Integer.parseInt(pages.get(1));
			int totalPages = pages.get(2) == null ? 1 : Integer.parseInt(pages.get(2));
			if (callback.getRemainingMessageCount() == 0)
				return;
			String message = callback.getMessage(0);
			List<String> list = Splitter.on(", ").splitToList(message.substring(6));
			for (String name : list) {
				String strippedName = ChatColor.stripColor(name);
				if (name.startsWith(ChatColor.GREEN.toString())) {
					getGameListener().getOnlineFriends().add(strippedName);
				}
				if (!The5zigMod.getFriendManager().isFriend(strippedName) && !The5zigMod.getFriendManager().isSuggested(strippedName)) {
					users.add(new User(strippedName, null));
				}
			}

			if (currentPage == totalPages) {
				if (!users.isEmpty()) {
					The5zigMod.getNetworkManager().sendPacket(new PacketUserSearch(PacketUserSearch.Type.FRIEND_LIST, users.toArray(new User[users.size()])));
				}
			} else {
				The5zigMod.getScheduler().postToMainThread(new Runnable() {
					@Override
					public void run() {
						getFriendsList(currentPage + 1, users);
					}
				}, true);
			}
		}
	});
}
 
Example #25
Source File: Scenario.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
static Collection<Scenario.Type> getScenarios(EnvStore envStore) {
  Collection<String> rawVals = Splitter.on(',').trimResults().splitToList(
      envStore.getOptional(SCENARIOS_ENV_KEY, Scenario.Type.YAML.toString()));
  Collection<Scenario.Type> scenarios = new ArrayList<>();
  for (String rawVal : rawVals) {
    try {
      scenarios.add(Scenario.Type.valueOf(rawVal.toUpperCase()));
    } catch (Exception e) { // SUPPRESS CHECKSTYLE IllegalCatch
      throw new IllegalArgumentException(String.format(
          "Unable to parse %s value '%s'. Expected one of: %s",
          SCENARIOS_ENV_KEY, rawVal, Arrays.asList(Scenario.Type.values())));
    }
  }
  return scenarios;
}
 
Example #26
Source File: GherkinCheckVerifier.java    From sonar-gherkin-plugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void addSecondaryLines(TestIssue issue, String value) {
  List<Integer> secondaryLines = new ArrayList<>();
  if (!"".equals(value)) {
    for (String secondary : Splitter.on(',').split(value)) {
      secondaryLines.add(lineValue(issue.line(), secondary));
    }
  }
  issue.secondary(secondaryLines);
}
 
Example #27
Source File: CComment.java    From binnavi with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new comment object
 *
 * @param id The id of the comment.
 * @param user The user of the comment.
 * @param parent The id of a potential parent comment, can be null.
 * @param comment The actual comment string.
 */
public CComment(final Integer id, final IUser user, final IComment parent, final String comment) {
  Preconditions.checkArgument(((id == null) || (id > 0)),
      "Error: id can only be larger then zero or null");
  this.id = id;
  this.user = Preconditions.checkNotNull(user, "IE02631: user argument can not be null");
  this.parent = parent;
  this.comment = Preconditions.checkNotNull(comment, "IE02632: comment argument can not be null");
  Preconditions.checkArgument(!comment.isEmpty(), "Error: comment must be a non empty string");
  List<String> linesList = Splitter.on('\n').splitToList(comment);
  lines = linesList.toArray(new String[linesList.size()]);
 }
 
Example #28
Source File: ForTagTest.java    From jinjava with Apache License 2.0 5 votes vote down vote up
@Test
public void forLoopNestedFor() {
  TagNode tagNode = (TagNode) fixture("nested-fors");
  assertThat(
      Splitter
        .on("\n")
        .trimResults()
        .omitEmptyStrings()
        .split(tag.interpret(tagNode, interpreter))
    )
    .contains("02", "03", "12", "13");
}
 
Example #29
Source File: SortConverter.java    From james-project with Apache License 2.0 5 votes vote down vote up
private static Sort toSort(String jmapSort) {
    Preconditions.checkNotNull(jmapSort);
    List<String> splitToList = Splitter.on(SEPARATOR).splitToList(jmapSort);
    checkField(splitToList);
    return new SearchQuery.Sort(getSortClause(splitToList.get(0)),
        isReverse(splitToList));
}
 
Example #30
Source File: SelectColumn.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public String getColumnName() {
    String fullNameToken = getNameToken().image;

    List<String> parts = Splitter.on('.').splitToList(fullNameToken);
    if (parts.size() == 2) {
        return parts.get(1);
    }

    return parts.get(0);
}