Пример #1
0
    @Override
    public ParserState onComplete() {
      if (getHasArgument() && values.isEmpty()) {
        throw new CommandLineArgumentException(
            String.format("No argument was provided for command-line option '%s'.", optionString));
      }

      ParsedCommandLineOption parsedOption = commandLine.addOption(optionString.option, option);
      if (values.size() + parsedOption.getValues().size() > 1
          && !option.getAllowsMultipleArguments()) {
        throw new CommandLineArgumentException(
            String.format(
                "Multiple arguments were provided for command-line option '%s'.", optionString));
      }
      for (String value : values) {
        parsedOption.addArgument(value);
      }
      if (option.getDeprecationWarning() != null) {
        new PrintStream(CommandLineParser.this.deprecationPrinter)
            .println(
                "The "
                    + optionString
                    + " option is deprecated - "
                    + option.getDeprecationWarning());
      }
      if (option.getSubcommand() != null) {
        return state.onNonOption(option.getSubcommand());
      }

      return state;
    }
Пример #2
0
  /**
   * Parses the given command-line.
   *
   * @param commandLine The command-line.
   * @return The parsed command line.
   * @throws org.gradle.CommandLineArgumentException On parse failure.
   */
  public ParsedCommandLine parse(Iterable<String> commandLine) {
    ParsedCommandLine parsedCommandLine =
        new ParsedCommandLine(new HashSet<CommandLineOption>(optionsByString.values()));
    ParserState parseState = new BeforeFirstSubCommand(parsedCommandLine);
    for (String arg : commandLine) {
      if (parseState.maybeStartOption(arg)) {
        if (arg.equals("--")) {
          parseState = new AfterOptions(parsedCommandLine);
        } else if (arg.matches("--[^=]+")) {
          OptionParserState parsedOption = parseState.onStartOption(arg, arg.substring(2));
          parseState = parsedOption.onStartNextArg();
        } else if (arg.matches("--[^=]+=.*")) {
          int endArg = arg.indexOf('=');
          OptionParserState parsedOption = parseState.onStartOption(arg, arg.substring(2, endArg));
          parseState = parsedOption.onArgument(arg.substring(endArg + 1));
        } else if (arg.matches("-[^=]=.*")) {
          OptionParserState parsedOption = parseState.onStartOption(arg, arg.substring(1, 2));
          parseState = parsedOption.onArgument(arg.substring(3));
        } else {
          assert arg.matches("-[^-].*");
          String option = arg.substring(1);
          if (optionsByString.containsKey(option)) {
            OptionParserState parsedOption = parseState.onStartOption(arg, option);
            parseState = parsedOption.onStartNextArg();
          } else {
            String option1 = arg.substring(1, 2);
            OptionParserState parsedOption = parseState.onStartOption("-" + option1, option1);
            if (parsedOption.getHasArgument()) {
              parseState = parsedOption.onArgument(arg.substring(2));
            } else {
              parseState = parsedOption.onComplete();
              for (int i = 2; i < arg.length(); i++) {
                String optionStr = arg.substring(i, i + 1);
                parsedOption = parseState.onStartOption("-" + optionStr, optionStr);
                parseState = parsedOption.onComplete();
              }
            }
          }
        }
      } else {
        parseState = parseState.onNonOption(arg);
      }
    }

    parseState.onCommandLineEnd();
    return parsedCommandLine;
  }
Пример #3
0
  /**
   * Parses custom packet serialized by hessian marshaller.
   *
   * @param ses Session.
   * @param buf Buffer containing not parsed bytes.
   * @param state Parser state.
   * @return Parsed message.
   * @throws IOException If packet parsing or deserialization failed.
   */
  @Nullable
  private GridClientMessage parseCustomPacket(GridNioSession ses, ByteBuffer buf, ParserState state)
      throws IOException {
    assert state.packetType() == PacketType.GRIDGAIN;
    assert state.packet() == null;

    ByteArrayOutputStream tmp = state.buffer();

    int len = state.index();

    while (buf.remaining() > 0) {
      byte b = buf.get();

      if (len == 0) {
        tmp.write(b);

        if (tmp.size() == 4) {
          len = U.bytesToInt(tmp.toByteArray(), 0);

          tmp.reset();

          if (len == 0) return PING_MESSAGE;
          else if (len < 0)
            throw new IOException(
                "Failed to parse incoming packet (invalid packet length) [ses="
                    + ses
                    + ", len="
                    + len
                    + ']');

          state.index(len);
        }
      } else {
        tmp.write(b);

        if (tmp.size() == len) return marshaller.unmarshal(tmp.toByteArray());
      }
    }

    return null;
  }
Пример #4
0
  /** {@inheritDoc} */
  @Nullable
  @Override
  public GridClientMessage decode(GridNioSession ses, ByteBuffer buf)
      throws IOException, GridException {
    ParserState state = ses.removeMeta(PARSER_STATE_META_NAME);

    if (state == null) state = new ParserState();

    PacketType type = state.packetType();

    if (type == null) {
      byte hdr = buf.get(buf.position());

      switch (hdr) {
        case MEMCACHE_REQ_FLAG:
          state.packet(new GridTcpRestPacket());
          state.packetType(PacketType.MEMCACHE);

          break;
        case GRIDGAIN_REQ_FLAG:
          // Skip header.
          buf.get();

          state.packetType(PacketType.GRIDGAIN);

          break;

        default:
          throw new IOException(
              "Failed to parse incoming packet (invalid packet start) [ses="
                  + ses
                  + ", b="
                  + Integer.toHexString(hdr & 0xFF)
                  + ']');
      }
    }

    GridClientMessage result = null;

    switch (state.packetType()) {
      case MEMCACHE:
        result = parseMemcachePacket(ses, buf, state);

        break;
      case GRIDGAIN:
        result = parseCustomPacket(ses, buf, state);

        break;
    }

    if (result == null)
      // Packet was not fully parsed yet.
      ses.addMeta(PARSER_STATE_META_NAME, state);

    return result;
  }
  /**
   * Parses the given command-line.
   *
   * @param commandLine The command-line.
   * @return The parsed command line.
   * @throws org.gradle.cli.CommandLineArgumentException On parse failure.
   */
  public ParsedCommandLine parse(Iterable<String> commandLine) throws CommandLineArgumentException {
    ParsedCommandLine parsedCommandLine =
        new ParsedCommandLine(new HashSet<CommandLineOption>(optionsByString.values()));
    ParserState parseState = new BeforeFirstSubCommand(parsedCommandLine);
    for (String arg : commandLine) {
      if (parseState.maybeStartOption(arg)) {
        if (arg.equals("--")) {
          parseState = new AfterOptions(parsedCommandLine);
        } else if (arg.matches("--[^=]+")) {
          OptionParserState parsedOption = parseState.onStartOption(arg, arg.substring(2));
          parseState = parsedOption.onStartNextArg();
        } else if (arg.matches("--[^=]+=.*")) {
          int endArg = arg.indexOf('=');
          OptionParserState parsedOption = parseState.onStartOption(arg, arg.substring(2, endArg));
          parseState = parsedOption.onArgument(arg.substring(endArg + 1));
        } else if (arg.matches("-[^=]=.*")) {
          OptionParserState parsedOption = parseState.onStartOption(arg, arg.substring(1, 2));
          parseState = parsedOption.onArgument(arg.substring(3));
        } else {
          assert arg.matches("-[^-].*");
          String option = arg.substring(1);
          if (optionsByString.containsKey(option)) {
            OptionParserState parsedOption = parseState.onStartOption(arg, option);
            parseState = parsedOption.onStartNextArg();
          } else {
            String option1 = arg.substring(1, 2);
            OptionParserState parsedOption;
            if (optionsByString.containsKey(option1)) {
              parsedOption = parseState.onStartOption("-" + option1, option1);
              if (parsedOption.getHasArgument()) {
                parseState = parsedOption.onArgument(arg.substring(2));
              } else {
                parseState = parsedOption.onComplete();
                for (int i = 2; i < arg.length(); i++) {
                  String optionStr = arg.substring(i, i + 1);
                  parsedOption = parseState.onStartOption("-" + optionStr, optionStr);
                  parseState = parsedOption.onComplete();
                }
              }
            } else {
              if (allowUnknownOptions) {
                // if we are allowing unknowns, just pass through the whole arg
                parsedOption = parseState.onStartOption(arg, option);
                parseState = parsedOption.onComplete();
              } else {
                // We are going to throw a CommandLineArgumentException below, but want the message
                // to reflect that we didn't recognise the first char (i.e. the option specifier)
                parsedOption = parseState.onStartOption("-" + option1, option1);
                parseState = parsedOption.onComplete();
              }
            }
          }
        }
      } else {
        parseState = parseState.onNonOption(arg);
      }
    }

    parseState.onCommandLineEnd();
    return parsedCommandLine;
  }
Пример #6
0
  /**
   * Parses memcache protocol message.
   *
   * @param ses Session.
   * @param buf Buffer containing not parsed bytes.
   * @param state Current parser state.
   * @return Parsed packet.s
   * @throws IOException If packet cannot be parsed.
   * @throws GridException If deserialization error occurred.
   */
  @Nullable
  private GridClientMessage parseMemcachePacket(
      GridNioSession ses, ByteBuffer buf, ParserState state) throws IOException, GridException {
    assert state.packetType() == PacketType.MEMCACHE;
    assert state.packet() != null;
    assert state.packet() instanceof GridTcpRestPacket;

    GridTcpRestPacket req = (GridTcpRestPacket) state.packet();
    ByteArrayOutputStream tmp = state.buffer();
    int i = state.index();

    while (buf.remaining() > 0) {
      byte b = buf.get();

      if (i == 0) req.requestFlag(b);
      else if (i == 1) req.operationCode(b);
      else if (i == 2 || i == 3) {
        tmp.write(b);

        if (i == 3) {
          req.keyLength(U.bytesToShort(tmp.toByteArray(), 0));

          tmp.reset();
        }
      } else if (i == 4) req.extrasLength(b);
      else if (i >= 8 && i <= 11) {
        tmp.write(b);

        if (i == 11) {
          req.totalLength(U.bytesToInt(tmp.toByteArray(), 0));

          tmp.reset();
        }
      } else if (i >= 12 && i <= 15) {
        tmp.write(b);

        if (i == 15) {
          req.opaque(tmp.toByteArray());

          tmp.reset();
        }
      } else if (i >= HDR_LEN && i < HDR_LEN + req.extrasLength()) {
        tmp.write(b);

        if (i == HDR_LEN + req.extrasLength() - 1) {
          req.extras(tmp.toByteArray());

          tmp.reset();
        }
      } else if (i >= HDR_LEN + req.extrasLength()
          && i < HDR_LEN + req.extrasLength() + req.keyLength()) {
        tmp.write(b);

        if (i == HDR_LEN + req.extrasLength() + req.keyLength() - 1) {
          req.key(tmp.toByteArray());

          tmp.reset();
        }
      } else if (i >= HDR_LEN + req.extrasLength() + req.keyLength()
          && i < HDR_LEN + req.totalLength()) {
        tmp.write(b);

        if (i == HDR_LEN + req.totalLength() - 1) {
          req.value(tmp.toByteArray());

          tmp.reset();
        }
      }

      if (i == HDR_LEN + req.totalLength() - 1)
        // Assembled the packet.
        return assemble(ses, req);

      i++;
    }

    state.index(i);

    return null;
  }
Пример #7
0
  private void parseLine(String line) {
    if (parserState.equals(ParserState.EXPECTED)) {
      expectedResults.add(line); // just remember for future use
      return;
    }

    Matcher m = pattern.matcher(line);
    if (m.matches()) {

      String zone = m.group(1);
      String nickname = m.group(2);

      if (nickname.equals("ComputerA") || nickname.equals("ComputerB")) {
        List<Card> cards = null;
        List<PermanentCard> perms = null;
        Zone gameZone;
        if ("hand".equalsIgnoreCase(zone)) {
          gameZone = Zone.HAND;
          cards = nickname.equals("ComputerA") ? handCardsA : handCardsB;
        } else if ("battlefield".equalsIgnoreCase(zone)) {
          gameZone = Zone.BATTLEFIELD;
          perms = nickname.equals("ComputerA") ? battlefieldCardsA : battlefieldCardsB;
        } else if ("graveyard".equalsIgnoreCase(zone)) {
          gameZone = Zone.GRAVEYARD;
          cards = nickname.equals("ComputerA") ? graveyardCardsA : graveyardCardsB;
        } else if ("library".equalsIgnoreCase(zone)) {
          gameZone = Zone.LIBRARY;
          cards = nickname.equals("ComputerA") ? libraryCardsA : libraryCardsB;
        } else if ("player".equalsIgnoreCase(zone)) {
          String command = m.group(3);
          if ("life".equals(command)) {
            if (nickname.equals("ComputerA")) {
              commandsA.put(Zone.OUTSIDE, "life:" + m.group(4));
            } else {
              commandsB.put(Zone.OUTSIDE, "life:" + m.group(4));
            }
          }
          return;
        } else {
          return; // go parse next line
        }

        String cardName = m.group(3);
        Integer amount = Integer.parseInt(m.group(4));
        boolean tapped = m.group(5) != null && m.group(5).equals(":{tapped}");

        if (cardName.equals("clear")) {
          if (nickname.equals("ComputerA")) {
            commandsA.put(gameZone, "clear");
          } else {
            commandsB.put(gameZone, "clear");
          }
        } else {
          for (int i = 0; i < amount; i++) {
            CardInfo cardInfo = CardRepository.instance.findCard(cardName);
            Card card = cardInfo != null ? cardInfo.getCard() : null;
            if (card != null) {
              if (gameZone.equals(Zone.BATTLEFIELD)) {
                PermanentCard p = new PermanentCard(card, null);
                p.setTapped(tapped);
                perms.add(p);
              } else {
                cards.add(card);
              }
            } else {
              logger.fatal("Couldn't find a card: " + cardName);
              logger.fatal("line: " + line);
            }
          }
        }
      } else {
        logger.warn("Unknown player: " + nickname);
      }
    } else {
      logger.warn("Init string wasn't parsed: " + line);
    }
  }