@Test
  public void testFromSystem_containsListValues() throws Exception {
    AbstractConfiguration.setDefaultListDelimiter('|');
    Map<String, String> properties = Maps.newHashMap();
    properties.put("testProperty", "b,bee");

    for (Entry<String, String> entry : properties.entrySet()) {
      System.setProperty(entry.getKey(), entry.getValue());
    }

    Splitter splitter = Splitter.on(',');
    Configuration systemConfiguration = configurationHelper.fromSystem();
    for (Entry<String, String> entry : properties.entrySet()) {
      String[] actualValues = systemConfiguration.getStringArray(entry.getKey());
      String[] expectedValues;
      if ("line.separator".equals(entry.getKey())) {
        expectedValues = new String[] {SystemUtils.LINE_SEPARATOR};
      } else {
        expectedValues = splitter.splitToList(entry.getValue()).toArray(new String[0]);
      }
      assertArrayEquals(
          String.format("Values for key %s do not match", entry.getKey()),
          expectedValues,
          actualValues);
    }
  }
예제 #2
0
  /**
   * Convert a {@code stringKey} produced using {@link StateNamespace#stringKey} on one of the
   * namespaces produced by this class into the original {@link StateNamespace}.
   */
  public static <W extends BoundedWindow> StateNamespace fromString(
      String stringKey, Coder<W> windowCoder) {
    if (!stringKey.startsWith("/") || !stringKey.endsWith("/")) {
      throw new RuntimeException("Invalid namespace string: '" + stringKey + "'");
    }

    if (GlobalNamespace.GLOBAL_STRING.equals(stringKey)) {
      return global();
    }

    List<String> parts = SLASH_SPLITTER.splitToList(stringKey);
    if (parts.size() != 3 && parts.size() != 4) {
      throw new RuntimeException("Invalid namespace string: '" + stringKey + "'");
    }
    // Ends should be empty (we start and end with /)
    if (!parts.get(0).isEmpty() || !parts.get(parts.size() - 1).isEmpty()) {
      throw new RuntimeException("Invalid namespace string: '" + stringKey + "'");
    }

    try {
      W window = CoderUtils.decodeFromBase64(windowCoder, parts.get(1));
      if (parts.size() > 3) {
        int index = Integer.parseInt(parts.get(2), WindowAndTriggerNamespace.TRIGGER_RADIX);
        return windowAndTrigger(windowCoder, window, index);
      } else {
        return window(windowCoder, window);
      }
    } catch (Exception e) {
      throw new RuntimeException("Invalid namespace string: '" + stringKey + "'", e);
    }
  }
예제 #3
0
  public Map<String, Path> buildMultipleAndReturnOutputs(String... args) throws IOException {
    // Add in `--show-output` to the build, so we can parse the output paths after the fact.
    ImmutableList<String> buildArgs =
        ImmutableList.<String>builder().add("--show-output").add(args).build();
    ProjectWorkspace.ProcessResult buildResult =
        runBuckBuild(buildArgs.toArray(new String[buildArgs.size()]));
    buildResult.assertSuccess();

    // Grab the stdout lines, which have the build outputs.
    List<String> lines =
        Splitter.on(CharMatcher.anyOf(System.lineSeparator()))
            .trimResults()
            .omitEmptyStrings()
            .splitToList(buildResult.getStdout());

    // Skip the first line, which is just "The outputs are:".
    assertThat(lines.get(0), Matchers.equalTo("The outputs are:"));
    lines = lines.subList(1, lines.size());

    Splitter lineSplitter = Splitter.on(' ').trimResults();
    ImmutableMap.Builder<String, Path> builder = ImmutableMap.builder();
    for (String line : lines) {
      List<String> fields = lineSplitter.splitToList(line);
      assertThat(fields, Matchers.hasSize(2));
      builder.put(fields.get(0), getPath(fields.get(1)));
    }

    return builder.build();
  }
예제 #4
0
  /**
   * Input constructor.
   *
   * @param text the input text
   * @throws FormatterException if the input cannot be parsed
   */
  public JavaInput(String filename, String text) throws FormatterException {
    this.filename = filename;
    this.text = text;
    char[] chars = text.toCharArray();
    List<String> lines = NEWLINE_SPLITTER.splitToList(text);
    setLines(ImmutableList.copyOf(lines));
    ImmutableList<Tok> toks = buildToks(text, chars);
    positionToColumnMap = makePositionToColumnMap(toks);
    tokens = buildTokens(toks);
    ImmutableSortedMap.Builder<Integer, Token> locationTokenMap = ImmutableSortedMap.naturalOrder();
    for (Token token : tokens) {
      locationTokenMap.put(JavaOutput.startTok(token).getPosition(), token);
    }
    positionTokenMap = locationTokenMap.build();

    // adjust kN for EOF
    kToToken = new Token[kN + 1];
    for (Token token : tokens) {
      for (Input.Tok tok : token.getToksBefore()) {
        if (tok.getIndex() < 0) {
          continue;
        }
        kToToken[tok.getIndex()] = token;
      }
      kToToken[token.getTok().getIndex()] = token;
      for (Input.Tok tok : token.getToksAfter()) {
        if (tok.getIndex() < 0) {
          continue;
        }
        kToToken[tok.getIndex()] = token;
      }
    }
  }
  @Override
  public Collection<Either<JobSpec, URI>> parseJobSpec(byte[] message) throws IOException {
    try {
      String messageString = new String(message, Charsets.UTF_8);
      List<Either<JobSpec, URI>> jobSpecs = Lists.newArrayList();

      for (String oneInstruction : SPLITTER_COMMA.split(messageString)) {

        List<String> tokens = SPLITTER_COLON.splitToList(oneInstruction);

        if (tokens.get(0).equals(REMOVE)) {
          URI uri = new URI(tokens.get(1));
          jobSpecs.add(Either.<JobSpec, URI>right(uri));
        } else {
          URI uri = new URI(tokens.get(0));
          String version = tokens.get(1);
          JobSpec jobSpec =
              new JobSpec.Builder(uri)
                  .withConfig(ConfigFactory.empty())
                  .withVersion(version)
                  .build();
          jobSpecs.add(Either.<JobSpec, URI>left(jobSpec));
        }
      }
      return jobSpecs;
    } catch (URISyntaxException use) {
      throw new IOException(use);
    }
  }
예제 #6
0
  @Override
  public boolean advanceNextPosition() {
    if (!lines.hasNext()) {
      return false;
    }
    String line = lines.next();
    fields = LINE_SPLITTER.splitToList(line);

    return true;
  }
예제 #7
0
  @VisibleForTesting
  static Optional<PackageInfo> parsePathAndPackageInfo(String packageName, String rawOutput) {
    Iterable<String> lines = Splitter.on(LINE_ENDING).omitEmptyStrings().split(rawOutput);
    Iterator<String> lineIter = lines.iterator();
    String pmPathPrefix = "package:";

    String pmPath = null;
    if (lineIter.hasNext()) {
      pmPath = lineIter.next();
      if (pmPath.startsWith("WARNING: linker: ")) {
        // Ignore silly linker warnings about non-PIC code on emulators
        pmPath = lineIter.hasNext() ? lineIter.next() : null;
      }
    }

    if (pmPath == null || !pmPath.startsWith(pmPathPrefix)) {
      LOG.warn("unable to locate package path for [" + packageName + "]");
      return Optional.absent();
    }

    final String packagePrefix = "  Package [" + packageName + "] (";
    final String otherPrefix = "  Package [";
    boolean sawPackageLine = false;
    final Splitter splitter = Splitter.on('=').limit(2);

    String codePath = null;
    String resourcePath = null;
    String nativeLibPath = null;
    String versionCode = null;

    for (String line : lines) {
      // Just ignore everything until we see the line that says we are in the right package.
      if (line.startsWith(packagePrefix)) {
        sawPackageLine = true;
        continue;
      }
      // This should never happen, but if we do see a different package, stop parsing.
      if (line.startsWith(otherPrefix)) {
        break;
      }
      // Ignore lines before our package.
      if (!sawPackageLine) {
        continue;
      }
      // Parse key-value pairs.
      List<String> parts = splitter.splitToList(line.trim());
      if (parts.size() != 2) {
        continue;
      }
      switch (parts.get(0)) {
        case "codePath":
          codePath = parts.get(1);
          break;
        case "resourcePath":
          resourcePath = parts.get(1);
          break;
        case "nativeLibraryPath":
          nativeLibPath = parts.get(1);
          break;
          // Lollipop uses this name.  Not sure what's "legacy" about it yet.
          // Maybe something to do with 64-bit?
          // Might need to update if people report failures.
        case "legacyNativeLibraryDir":
          nativeLibPath = parts.get(1);
          break;
        case "versionCode":
          // Extra split to get rid of the SDK thing.
          versionCode = parts.get(1).split(" ", 2)[0];
          break;
        default:
          break;
      }
    }

    if (!sawPackageLine) {
      return Optional.absent();
    }

    Preconditions.checkNotNull(codePath, "Could not find codePath");
    Preconditions.checkNotNull(resourcePath, "Could not find resourcePath");
    Preconditions.checkNotNull(nativeLibPath, "Could not find nativeLibraryPath");
    Preconditions.checkNotNull(versionCode, "Could not find versionCode");
    if (!codePath.equals(resourcePath)) {
      throw new IllegalStateException("Code and resource path do not match");
    }

    // Lollipop doesn't give the full path to the apk anymore.  Not sure why it's "base.apk".
    if (!codePath.endsWith(".apk")) {
      codePath += "/base.apk";
    }

    return Optional.of(new PackageInfo(codePath, nativeLibPath, versionCode));
  }
예제 #8
0
  /** Draws the hover event specified by the given chat component */
  protected void handleComponentHover(
      IChatComponent p_175272_1_, int p_175272_2_, int p_175272_3_) {
    if (p_175272_1_ != null && p_175272_1_.getChatStyle().getChatHoverEvent() != null) {
      HoverEvent hoverevent = p_175272_1_.getChatStyle().getChatHoverEvent();

      if (hoverevent.getAction() == HoverEvent.Action.SHOW_ITEM) {
        ItemStack itemstack = null;

        try {
          NBTBase nbtbase = JsonToNBT.getTagFromJson(hoverevent.getValue().getUnformattedText());

          if (nbtbase instanceof NBTTagCompound) {
            itemstack = ItemStack.loadItemStackFromNBT((NBTTagCompound) nbtbase);
          }
        } catch (NBTException var11) {;
        }

        if (itemstack != null) {
          this.renderToolTip(itemstack, p_175272_2_, p_175272_3_);
        } else {
          this.drawCreativeTabHoveringText(
              EnumChatFormatting.RED + "Invalid Item!", p_175272_2_, p_175272_3_);
        }
      } else if (hoverevent.getAction() == HoverEvent.Action.SHOW_ENTITY) {
        if (this.mc.gameSettings.advancedItemTooltips) {
          try {
            NBTBase nbtbase1 = JsonToNBT.getTagFromJson(hoverevent.getValue().getUnformattedText());

            if (nbtbase1 instanceof NBTTagCompound) {
              List<String> list1 = Lists.<String>newArrayList();
              NBTTagCompound nbttagcompound = (NBTTagCompound) nbtbase1;
              list1.add(nbttagcompound.getString("name"));

              if (nbttagcompound.hasKey("type", 8)) {
                String s = nbttagcompound.getString("type");
                list1.add("Type: " + s + " (" + EntityList.getIDFromString(s) + ")");
              }

              list1.add(nbttagcompound.getString("id"));
              this.drawHoveringText(list1, p_175272_2_, p_175272_3_);
            } else {
              this.drawCreativeTabHoveringText(
                  EnumChatFormatting.RED + "Invalid Entity!", p_175272_2_, p_175272_3_);
            }
          } catch (NBTException var10) {
            this.drawCreativeTabHoveringText(
                EnumChatFormatting.RED + "Invalid Entity!", p_175272_2_, p_175272_3_);
          }
        }
      } else if (hoverevent.getAction() == HoverEvent.Action.SHOW_TEXT) {
        this.drawHoveringText(
            NEWLINE_SPLITTER.splitToList(hoverevent.getValue().getFormattedText()),
            p_175272_2_,
            p_175272_3_);
      } else if (hoverevent.getAction() == HoverEvent.Action.SHOW_ACHIEVEMENT) {
        StatBase statbase = StatList.getOneShotStat(hoverevent.getValue().getUnformattedText());

        if (statbase != null) {
          IChatComponent ichatcomponent = statbase.getStatName();
          IChatComponent ichatcomponent1 =
              new ChatComponentTranslation(
                  "stats.tooltip.type." + (statbase.isAchievement() ? "achievement" : "statistic"),
                  new Object[0]);
          ichatcomponent1.getChatStyle().setItalic(Boolean.valueOf(true));
          String s1 =
              statbase instanceof Achievement ? ((Achievement) statbase).getDescription() : null;
          List<String> list =
              Lists.newArrayList(
                  new String[] {
                    ichatcomponent.getFormattedText(), ichatcomponent1.getFormattedText()
                  });

          if (s1 != null) {
            list.addAll(this.fontRendererObj.listFormattedStringToWidth(s1, 150));
          }

          this.drawHoveringText(list, p_175272_2_, p_175272_3_);
        } else {
          this.drawCreativeTabHoveringText(
              EnumChatFormatting.RED + "Invalid statistic/achievement!", p_175272_2_, p_175272_3_);
        }
      }

      GlStateManager.disableLighting();
    }
  }