/* (non-Javadoc)
@see spark.protocol.parser.ResultParser#parse(spark.api.Command, java.io.InputStream, spark.protocol.ProtocolCommand.ResultType)
439177
@Override
  public Result parse(Command cmd, InputStream input, ResultType type) throws SparqlException {
    BufferedReader br = null;
    try {
      // Expected type should already be validated by ResultFactory, check anyways.
      if (type != null && type != ResultType.ASK) {
        throw new SparqlException("Unexpected result type; expected " + type + " but found ASK.");
      }
      
      char[] buf = new char[BUFFER_LEN];
      
      // TODO: Find the actual encoding from the server response, if available.
      br = new BufferedReader(new InputStreamReader(input, UTF8));
      int len = fill(buf, br);
      
      String s = new String(buf, 0, len).trim();
      logger.debug("Read '{}' from text/html ASK result", s);
      
      boolean result;
      if (s.equalsIgnoreCase("true")) {
        result = true;
      } else if (s.equalsIgnoreCase("false")) {
        result = false;
      } else {
        logger.warn("Unexpected boolean value read from text/html ASK result: '{}'", s);
        result = false;
      }
      
      if (logger.isWarnEnabled() && br.read() >= 0) {
        logger.warn("Unexpected input found after boolean value");
      }
      
      return new BooleanResultImpl(cmd, result);
    } catch (IOException e) {
      throw new SparqlException("Error reading from server input", e);
    } finally {
      try {
        if (br != null) br.close();
        else input.close();
      } catch (IOException e) {
        // Don't re-throw because that could mask another exception (or prevent an otherwise usable
        // result from being returned).
        logger.warn("Error closing server input", e);
      }
    }
  }
171803
public <T> T parse(InputStream in, Class<T> mapTo) throws ParseException, UnsupportedEncodingException {
		return getPBinStream().parse(in, JSONValue.defaultReader.getMapper(mapTo));
	}
88785
private static void parseAST(String[] srcFiles, Charset srcCharset,
            String[] classPathEntries, FileASTRequestor requestor) {
        ASTParser parser = ASTParser.newParser(AST.JLS8);
        Map<String, String> options = JavaCore.getOptions();
        JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
        parser.setCompilerOptions(options);
        parser.setKind(ASTParser.K_COMPILATION_UNIT);
        parser.setResolveBindings(true);
        parser.setBindingsRecovery(true);
        parser.setEnvironment(classPathEntries, null, null, true);
        String[] srcEncodings = new String[srcFiles.length];
        for (int i = 0; i < srcEncodings.length; i++) {
            srcEncodings[i] = srcCharset.name();
        }
        parser.createASTs(
                srcFiles, srcEncodings, new String[]{}, requestor, null);
    }
46769
public <T> T parse(byte[] in, Class<T> mapTo) throws ParseException {
		return getPBytes().parse(in, JSONValue.defaultReader.getMapper(mapTo));
	}
610594
function parseResult(text, callback) {
  var errors = [], i = 0, l, errBlock, match, match2, lines;

  text = text.replace(/\r/g, '');
  lines = text.split('\n');

  match = skippingRegex.exec(lines[i]);
  if (match) {
    i++;
  }

  match = successRegex.exec(lines[i]);
  if (match) {
    callback(null, createParseSuccessObj(match));
    return;
  }

  for (l = lines.length; i < l; i++) {
    match = fileRegex.exec(lines[i]);
    if (match) {
      match2 = errorRegex.exec(lines[++i]);
      errBlock = createFailObj(match);
      for (var j = i; match2 && j < lines.length;) {
        errBlock.errors.push(createErrorObj(match2));
        match2 = errorRegex.exec(lines[++j]);
      }
      i = --j;
      errors.push(errBlock);
    } else {
      match = abstractRegex.exec(lines[i]);
      if (match) {
        callback(createErrorGJSLintFailed(match, errors));
        return;
      }
    }
  }
  callback(createParseErrorUnknown(lines));

}
591708
@Override
  public ParseResult parse(Reader reader, AttributeSource parent)
      throws IOException {
    ParseResult res = new ParseResult();

    // get MtasUpdateRequestProcessorResult
    StringBuilder sb = new StringBuilder();
    char[] buf = new char[128];
    int cnt;
    while ((cnt = reader.read(buf)) > 0) {
      sb.append(buf, 0, cnt);
    }
    Iterator<MtasUpdateRequestProcessorResultItem> iterator;

    try (
        MtasUpdateRequestProcessorResultReader result = new MtasUpdateRequestProcessorResultReader(
            sb.toString());) {
      iterator = result.getIterator();
      if (iterator != null && iterator.hasNext()) {
        res.str = result.getStoredStringValue();
        res.bin = result.getStoredBinValue();
      } else {
        res.str = null;
        res.bin = null;
        result.close();
        return res;
      }
      parent.clearAttributes();
      while (iterator.hasNext()) {
        MtasUpdateRequestProcessorResultItem item = iterator.next();
        if (item.tokenTerm != null) {
          CharTermAttribute catt = parent.addAttribute(CharTermAttribute.class);
          catt.append(item.tokenTerm);
        }
        if (item.tokenFlags != null) {
          FlagsAttribute flags = parent.addAttribute(FlagsAttribute.class);
          flags.setFlags(item.tokenFlags);
        }
        if (item.tokenPosIncr != null) {
          PositionIncrementAttribute patt = parent
              .addAttribute(PositionIncrementAttribute.class);
          patt.setPositionIncrement(item.tokenPosIncr);
        }
        if (item.tokenPayload != null) {
          PayloadAttribute p = parent.addAttribute(PayloadAttribute.class);
          p.setPayload(new BytesRef(item.tokenPayload));
        }
        if (item.tokenOffsetStart != null && item.tokenOffsetEnd != null) {
          OffsetAttribute offset = parent.addAttribute(OffsetAttribute.class);
          offset.setOffset(item.tokenOffsetStart, item.tokenOffsetEnd);
        }
        // capture state and add to result
        State state = parent.captureState();
        res.states.add(state.clone());
        // reset for reuse
        parent.clearAttributes();
      }
    } catch (IOException e) {
      // ignore
      log.debug(e);
    }
    return res;
  }
767443
private void parseResults() {
        logger.entering();

        if (result.getStatus() == ITestResult.SUCCESS) {
            this.status = "Passed";
        } else if (result.getStatus() == ITestResult.FAILURE) {
            this.status = "Failed";
        } else if (result.getStatus() == ITestResult.SKIP) {
            this.status = "Skipped";
        } else if (result.getStatus() == ITestResult.STARTED) {
            this.status = "Running";
        }

        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(result.getStartMillis());
        this.startTime = ReporterDateFormatter.getISO8601String(c.getTime());
        c.setTimeInMillis(result.getEndMillis());
        this.endTime = ReporterDateFormatter.getISO8601String(c.getTime());

        if (result.getMethod().getDescription() != null) {
            this.description = result.getMethod().getDescription();
        }

        if (result.getThrowable() != null) {
            this.exception = result.getThrowable().getClass().toString() + ":"
                    + result.getThrowable().getLocalizedMessage();
            this.stacktrace = getStackTraceInfo(result.getThrowable());
        }

        loadMethodInfo(result);

        logger.exiting();
    }
1052859
public QueryResult parse(final InputStream is) {
    MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(is);
    return parse(unpacker);
  }
1257712
@Override
	protected void parse(Node node) {
		NamedNodeMap attributes = node.getAttributes();
		width = getValueRecursiveAsInteger(attributes.getNamedItem("width"));
		height = getValueRecursiveAsInteger(attributes.getNamedItem("height"));
		mimeType = getValueRecursive(attributes.getNamedItem("mime-type"));
		extension = getValueRecursive(attributes.getNamedItem("extension"));
		setParsed(true);
	}
1187
@Override
    public ParseResult parse(final Source source) {
        return Util.execute(new ExceptionAction<ParseResult>() {
            @Override
            public ParseResult doAction() throws Throwable {
                logger.fine("Parsing " + source.getSrcInfo());
                final BufferedReader reader = source.createReader();
                try {
                    final ParserImpl impl = factory.create(source.getSrcInfo(),
                            reader);
                    final Doc doc = impl.doc();
                    return new ParseResult(doc, impl.errors());
                } finally {
                    reader.close();
                }
            }
        });
    }
157027
public Collection parse(InputStream stream) throws IOException {
        return parse(new BufferedReader(new InputStreamReader(stream, Charsets.UTF_8)));
    }
545908
public Object parseObject(String source) throws ParseException
    {

        ParsePosition pos = new ParsePosition(0);
        Object result = parseObject(source, pos);
        if (pos.getErrorIndex() >= 0)
        {
            throw new ParseException("Format.parseObject(String) failed", pos.getErrorIndex());
        }
        return result;
    }
283535
@Override
	public <E> E parse(byte[] source, Class<E> objectClazz) {
		try (ParserWrapper parserWrapper = createParser(source)) {
			E result = mapperFor(objectClazz).parse(this, parserWrapper);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			throw new KriptonRuntimeException(e);
		}
	}
836145
protected <T> T parse(JsonReaderI<T> mapper) throws ParseException {
		this.pos = -1;
		T result;
		try {
			read();
			result = readFirst(mapper);
			if (checkTaillingData) {
				if (!checkTaillingSpace)
					skipSpace();
				if (c != EOI)
					throw new ParseException(pos - 1, ERROR_UNEXPECTED_TOKEN, c);
			}
		} catch (IOException e) {
			throw new ParseException(pos, e);
		}
		xs = null;
		xo = null;
		return result;
	}
129736
public static Parse parseParse(final String parse, final GapLabeler gl) {
    final StringBuilder text = new StringBuilder();
    int offset = 0;
    final Stack<Constituent> stack = new Stack<Constituent>();
    final List<Constituent> cons = new LinkedList<Constituent>();
    for (int ci = 0, cl = parse.length(); ci < cl; ci++) {
      final char c = parse.charAt(ci);
      if (c == '(') {
        final String rest = parse.substring(ci + 1);
        final String type = getType(rest);
        if (type == null) {
          System.err.println("null type for: " + rest);
        }
        final String token = getToken(rest);
        stack.push(new Constituent(type, new Span(offset, offset)));
        if (token != null) {
          if (type.equals("-NONE-") && gl != null) {
            // System.err.println("stack.size="+stack.size());
            gl.labelGaps(stack);
          } else {
            cons.add(new Constituent(ShiftReduceParser.TOK_NODE,
                new Span(offset, offset + token.length())));
            text.append(token).append(" ");
            offset += token.length() + 1;
          }
        }
      } else if (c == ')') {
        final Constituent con = stack.pop();
        final int start = con.getSpan().getStart();
        if (start < offset) {
          cons.add(
              new Constituent(con.getLabel(), new Span(start, offset - 1)));
        }
      }
    }
    final String txt = text.toString();
    int tokenIndex = -1;
    final Parse p = new Parse(txt, new Span(0, txt.length()),
        ShiftReduceParser.TOP_NODE, 1, 0);
    for (int ci = 0; ci < cons.size(); ci++) {
      final Constituent con = cons.get(ci);
      final String type = con.getLabel();
      if (!type.equals(ShiftReduceParser.TOP_NODE)) {
        if (type == ShiftReduceParser.TOK_NODE) {
          tokenIndex++;
        }
        final Parse c = new Parse(txt, con.getSpan(), type, 1, tokenIndex);
        // System.err.println("insert["+ci+"] "+type+" "+c.toString()+"
        // "+c.hashCode());
        p.insert(c);
        // codeTree(p);
      }
    }
    return p;
  }
1290896
private static Result createResults(Command cmd, InputStream stream, ResultType type) throws SparqlException {
    XMLInputFactory xmlStreamFactory = XMLInputFactory.newInstance();
    
    // Tell the factory to combine adjacent character blocks into a single event, so we don't have to do it ourselves.
    xmlStreamFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
    
    // Tell the factory to create a reader that will close the underlying stream when done.
    xmlStreamFactory.setProperty(XMLInputFactory2.P_AUTO_CLOSE_INPUT, true);
    
    XMLStreamReader rdr;
    try {
      rdr = xmlStreamFactory.createXMLStreamReader(stream, "UTF-8");
    } catch (XMLStreamException e) {
      throw new SparqlException("Unable to open XML data", e);
    }
    List<String> cols = new ArrayList<String>();
    List<String> md = new ArrayList<String>();

    try {
      if (rdr.nextTag() != START_ELEMENT || !nameIs(rdr, SPARQL)) {
        throw new SparqlException("Result is not a SPARQL XML result document");
      }
      
      // Initialize the base URI to the 
      String base = null;
      if (cmd != null) {
        base = ((ProtocolDataSource)cmd.getConnection().getDataSource()).getUrl().toString();
      }
      
      // read the header information
      parseHeader(base, rdr, cols, md);
      
      // move the cursor into the results, and read in the first row
      if (rdr.nextTag() != START_ELEMENT) throw new SparqlException("No body to result document");
      
      String typeName = rdr.getLocalName();
      if (typeName.equalsIgnoreCase(RESULTS.toString())) {
        if (type != null && type != ResultType.SELECT) {
          throw new SparqlException("Unexpected result type; expected " + type + " but found SELECT.");
        }
        return new XMLSelectResults(cmd, rdr, cols, md);
      }
      if (typeName.equalsIgnoreCase(BOOLEAN.toString())) {
        if (type != null && type != ResultType.ASK) {
          throw new SparqlException("Unexpected result type; expected " + type + " but found ASK.");
        }
        if (!cols.isEmpty()) {
          logger.warn("Boolean result contained column definitions in head: {}", cols);
        }
        return parseBooleanResult(cmd, rdr, md);
      }

      throw new SparqlException("Unknown element type in result document. Expected <results> or <boolean> but got <" + typeName + ">");
    } catch (XMLStreamException e) {
      throw new SparqlException("Error reading the XML stream", e);
    }
  }
1275351
@Override
    public ParseResult parse(Source source) {
        if (!testSrcInfo.equals(source.getSrcInfo())) {
            throw new RuntimeException("testSrcInfo and source.getSrcInfo were not equal. testSrcInfo = " + testSrcInfo + ", source.getSrcInfo = " + source.getSrcInfo());
        }
        try {
            BufferedReader reader = source.createReader();
            try {
                if (!testString.equals(reader.readLine())) {
                    throw new RuntimeException("testString and reader.readLine() were not equal");
                }
                final String secondLine = reader.readLine();
                if (secondLine != null) {
                    throw new RuntimeException("got a second line '" + secondLine + "' from the reader");
                }
            } finally {
                reader.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return testResult;
    }