query reply parsing

<pre><code>
["reply", {headers}, "from", qid, value]
</code></pre>

@param hIn the hessian input stream
@param headers the message's headers
164048
private void readQueryResult(InH3 hIn, HeadersAmp headers)
      throws IOException
  {
    ServiceRefAmp serviceRef = readToAddress(hIn);
  
    long id = hIn.readLong();

    QueryRefAmp queryRef = serviceRef.removeQueryRef(id);
  
    if (queryRef != null) {
      ClassLoader loader = queryRef.getClassLoader();

      Thread thread = Thread.currentThread();
      thread.setContextClassLoader(loader);
      // XXX: _serializer.setClassLoader(loader);
    }
    else {
      // XX: _serializer.setClassLoader(null);
    }

    Object value = hIn.readObject();

    if (log.isLoggable(_logLevel)) {
      log.log(_logLevel, "query-result-r " + value + " (in " + this + ")"
              + "\n  {id:" + id + ", to:" + serviceRef + "," + headers + "}");
    }

    if (queryRef != null) {
      queryRef.complete(headers, value);
    }
    else if (log.isLoggable(Level.WARNING)) {
      log.warning("query-result qid=" + id + " for service " + serviceRef +
                  " does not match any known queries.\n" + headers);
    }
  }
565974
public static String doPut(String host, String path,
                               Map<String, String> headers,
                               Map<String, String> queries,
                               String body) throws Exception {
        return EntityUtils.toString(doPutResponse(host, path, headers, queries, body).getEntity(), "utf-8");
    }
1012905
private void setHeaders(HttpMessage message, Map<String, String> headers) {
		message.setHeader(RequestHeaderKey.ACCEPT, RequestHeaderValue.Accept.ALL);
		message.setHeader(RequestHeaderKey.CONNECTION, RequestHeaderValue.Connection.KEEP_ALIVE);
		message.setHeader(RequestHeaderKey.USER_AGENT, this.config.getUserAgent());

		if (headers != null) {
			for (String headerKey : headers.keySet()) {
				message.setHeader(headerKey, headers.get(headerKey));
			}
		}
	}
895150
public static String getHeader(Map<String, List<String>> responseHeaders, String header) {
        if (responseHeaders == null) {
            return null;
        }
        // Search the headers case insensitive (headers should be evaluated as
        // case insensitive, but, the Swagger implementation uses HashMap that
        // is case sensitive)
        for (Map.Entry<String, List<String>> entry : responseHeaders.entrySet()) {
            if (entry.getKey().equalsIgnoreCase(header)) {
                List<String> headersList = entry.getValue();
                if (headersList != null && !headersList.isEmpty()) { // Better
                                                                     // safe
                                                                     // than
                                                                     // sorry
                    return headersList.get(0);
                }
                break; // Header found, but, was null or empty
            }
        }
        return null;
    }
575461
public static String parseCharset(Map<String, String> headers) {
        return parseCharset(headers, HTTP.DEFAULT_CONTENT_CHARSET);
    }
91559
public void queryError(HeadersAmp headers,
                         String to,
                         long qid,
                         Throwable exn)
    throws IOException
  {
    if (log.isLoggable(Level.FINEST)) {
      log.finest(this + " error " + exn
                + "\n  {to:" + to + "," + headers + "}");
      
    }
    
    if (log.isLoggable(Level.FINER)) {
      log.log(Level.FINER, exn.toString(), exn);
    }
    
    try {
      JsonWriterImpl jOut = _jOut;
      jOut.init();

      jOut.writeStartArray();
      jOut.write("error");

      writeHeaders(jOut, headers);

      jOut.write(to);
      jOut.write(qid);

      ErrorAmp error = ErrorAmp.create(exn);

      jOut.writeStartObject();
      jOut.writeKey("code");
      jOut.writeString(error.getCode().toString());
      
      jOut.writeKey("message");
      jOut.writeString(exn.getMessage());
      
      jOut.writeKey("class");
      jOut.writeString(exn.getClass().getName());
      
      jOut.writeEndObject();

      jOut.writeEndArray();

      jOut.close();
    } catch (Throwable e) {
      log.log(Level.WARNING, e.toString(), e);
      
      throw e;
    }
  }
678639
@SuppressWarnings("unused")
    final void handleHeaderValue(ByteBuffer buffer, ResponseParseState state, HttpResponseBuilder builder) {
        StringBuilder stringBuilder = state.stringBuilder;
        if (stringBuilder == null) {
            stringBuilder = new StringBuilder();
            state.parseState = 0;
        }

        int parseState = state.parseState;
        while (buffer.hasRemaining()) {
            final byte next = buffer.get();
            switch (parseState) {
                case NORMAL: {
                    if (next == '\r') {
                        parseState = BEGIN_LINE_END;
                    } else if (next == '\n') {
                        parseState = LINE_END;
                    } else if (next == ' ' || next == '\t') {
                        parseState = WHITESPACE;
                    } else {
                        stringBuilder.append((char) next);
                    }
                    break;
                }
                case WHITESPACE: {
                    if (next == '\r') {
                        parseState = BEGIN_LINE_END;
                    } else if (next == '\n') {
                        parseState = LINE_END;
                    } else if (next == ' ' || next == '\t') {
                    } else {
                        if (stringBuilder.length() > 0) {
                            stringBuilder.append(' ');
                        }
                        stringBuilder.append((char) next);
                        parseState = NORMAL;
                    }
                    break;
                }
                case LINE_END:
                case BEGIN_LINE_END: {
                    if (next == '\n' && parseState == BEGIN_LINE_END) {
                        parseState = LINE_END;
                    } else if (next == '\t' ||
                            next == ' ') {
                        //this is a continuation
                        parseState = WHITESPACE;
                    } else {
                        //we have a header
                        HttpString nextStandardHeader = state.nextHeader;
                        String headerValue = stringBuilder.toString();

                        //TODO: we need to decode this according to RFC-2047 if we have seen a =? symbol
                        builder.getResponseHeaders().add(nextStandardHeader, headerValue);

                        state.nextHeader = null;

                        state.leftOver = next;
                        state.stringBuilder.setLength(0);
                        if (next == '\r') {
                            parseState = AWAIT_DATA_END;
                        } else {
                            state.state = ResponseParseState.HEADER;
                            state.parseState = 0;
                            return;
                        }
                    }
                    break;
                }
                case AWAIT_DATA_END: {
                    state.state = ResponseParseState.PARSE_COMPLETE;
                    return;
                }
            }
        }
        //we only write to the state if we did not finish parsing
        state.parseState = parseState;
    }
1351994
public Response response(String url, String... headers) throws IOException {
		return call(url, headers).execute();
	}
430470
def read_response_headers(response)
      raw_headers = response.headers
      headers = {}
      EXCLUDE_RESPONSE_HEADER_PATTERNS.each do |pattern|
        raw_headers = raw_headers.reject { |h| h if h.starts_with? pattern }
      end
      raw_headers.each do |key, val|
        headers.merge!(cleanup_header(key) => val)
      end
      headers
    end
1000787
protected List<BoxAPIResponse> parseResponse(BoxJSONResponse batchResponse) {
        JsonObject responseJSON = JsonObject.readFrom(batchResponse.getJSON());
        List<BoxAPIResponse> responses = new ArrayList<BoxAPIResponse>();
        Iterator<JsonValue> responseIterator = responseJSON.get("responses").asArray().iterator();
        while (responseIterator.hasNext()) {
            JsonObject jsonResponse = responseIterator.next().asObject();
            BoxAPIResponse response = null;

            //Gather headers
            Map<String, String> responseHeaders = new HashMap<String, String>();

            if (jsonResponse.get("headers") != null) {
                JsonObject batchResponseHeadersObject = jsonResponse.get("headers").asObject();
                for (JsonObject.Member member : batchResponseHeadersObject) {
                    String headerName = member.getName();
                    String headerValue = member.getValue().asString();
                    responseHeaders.put(headerName, headerValue);
                }
            }

            // Construct a BoxAPIResponse when response is null, or a BoxJSONResponse when there's a response
            // (not anticipating any other response as per current APIs.
            // Ideally we should do it based on response header)
            if (jsonResponse.get("response") == null || jsonResponse.get("response").isNull()) {
                response =
                    new BoxAPIResponse(jsonResponse.get("status").asInt(), responseHeaders);
            } else {
                response =
                    new BoxJSONResponse(jsonResponse.get("status").asInt(), responseHeaders,
                        jsonResponse.get("response").asObject());
            }
            responses.add(response);
        }
        return responses;
    }
68790
public void setResponse(Map<String, Object> headers) {
        int size = RES_200.length;
        byte[] len = stringToBytes(String.valueOf(0));
        size += CONTENT_LENGTH.length;
        size += len.length;
        size += TextCommandConstants.RETURN.length;
        if (headers != null) {
            for (Map.Entry<String, Object> entry : headers.entrySet()) {
                size += stringToBytes(HEADER_CUSTOM_PREFIX + entry.getKey() + ": ").length;
                size += stringToBytes(entry.getValue().toString()).length;
                size += TextCommandConstants.RETURN.length;
            }
        }
        size += TextCommandConstants.RETURN.length;
        this.response = ByteBuffer.allocate(size);
        response.put(RES_200);
        response.put(CONTENT_LENGTH);
        response.put(len);
        response.put(TextCommandConstants.RETURN);
        if (headers != null) {
            for (Map.Entry<String, Object> entry : headers.entrySet()) {
                response.put(stringToBytes(HEADER_CUSTOM_PREFIX + entry.getKey() + ": "));
                response.put(stringToBytes(entry.getValue().toString()));
                response.put(TextCommandConstants.RETURN);
            }
        }
        response.put(TextCommandConstants.RETURN);
        response.flip();
    }
753284
@Override
	public void parseHeader(String header, S sequence) {
		sequence.setOriginalHeader(header);
		String[] data = getHeaderValues(header);

		if (data.length == 1) {
			sequence.setAccession(new AccessionID(data[0]));
		} else {
			throw new RuntimeException(
					"No header or Some Error Occurred while reading header");
		}
	}
1319330
public void setResponse(JsonRpcResponse response) {
    if (response.isError()) {
      setException(response.error());
      return;
    }

    try {
      set((V) Messages.fromJson(method.outputBuilder(), response.result()));
    } catch (Exception e) {
      setException(e);
    }
  }
934127
public void parseBatchResult(ClientResponse response) throws IOException,
            ServiceException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        InputStream inputStream = response.getEntityInputStream();
        ReaderWriter.writeTo(inputStream, byteArrayOutputStream);
        response.setEntityInputStream(new ByteArrayInputStream(
                byteArrayOutputStream.toByteArray()));
        JobInfo jobInfo;

        List<DataSource> parts = parseParts(response.getEntityInputStream(),
                response.getHeaders().getFirst("Content-Type"));

        if (parts.size() == 0 || parts.size() > entityBatchOperations.size()) {
            throw new UniformInterfaceException(String.format(
                    "Batch response from server does not contain the correct amount "
                            + "of parts (expecting %d, received %d instead)",
                    parts.size(), entityBatchOperations.size()), response);
        }

        for (int i = 0; i < parts.size(); i++) {
            DataSource ds = parts.get(i);
            EntityBatchOperation entityBatchOperation = entityBatchOperations
                    .get(i);

            StatusLine status = StatusLine.create(ds);
            InternetHeaders headers = parseHeaders(ds);
            InputStream content = parseEntity(ds);

            if (status.getStatus() >= HTTP_ERROR) {

                InBoundHeaders inBoundHeaders = new InBoundHeaders();
                @SuppressWarnings("unchecked")
                Enumeration<Header> e = headers.getAllHeaders();
                while (e.hasMoreElements()) {
                    Header header = e.nextElement();
                    inBoundHeaders.putSingle(header.getName(),
                            header.getValue());
                }

                ClientResponse clientResponse = new ClientResponse(
                        status.getStatus(), inBoundHeaders, content, null);

                UniformInterfaceException uniformInterfaceException = new UniformInterfaceException(
                        clientResponse);
                throw uniformInterfaceException;
            } else if (entityBatchOperation instanceof Job.CreateBatchOperation) {

                try {
                    jobInfo = oDataAtomUnmarshaller.unmarshalEntry(content,
                            JobInfo.class);
                    Job.CreateBatchOperation jobCreateBatchOperation = (Job.CreateBatchOperation) entityBatchOperation;
                    jobCreateBatchOperation.setJobInfo(jobInfo);
                } catch (JAXBException e) {
                    throw new ServiceException(e);
                }
            } else if (entityBatchOperation instanceof Task.CreateBatchOperation) {
                try {
                    oDataAtomUnmarshaller.unmarshalEntry(content,
                            TaskInfo.class);
                } catch (JAXBException e) {
                    throw new ServiceException(e);
                }
            }
        }
    }
790799
private static String[] parseResponseHeader(InputStream pIS) throws IOException {
        List<String> headers = new ArrayList<String>();

        // Wrap Stream in Reader
        BufferedReader in = new BufferedReader(new InputStreamReader(pIS));

        // Get response status
        String header;

        while ((header = in.readLine()) != null) {
            //System.err.println(header);
            headers.add(header);
        }
        return headers.toArray(new String[headers.size()]);
    }
438176
function parserOnHeaders(headers, url) {
  // Once we exceeded headers limit - stop collecting them
  if (this.maxHeaderPairs <= 0 ||
      this._headers.length < this.maxHeaderPairs) {
    this._headers = this._headers.concat(headers);
  }
  this._url += url;
}
1138739
private void parseHeaders() throws IOException
  {
    _ws.flush();
    
    CharBuffer line = new CharBuffer();

    // Skip blank lines
    int count = 0;
    do {
      line.clear();
      if (! _rs.readln(line)) {
        _isKeepalive = false;
        return;
      }
    } while (line.length() == 0 && ++count < 10);

    if (line.length() == 0) {
      _isKeepalive = false;
      return;
    }

    if (line.startsWith("HTTP/1.1 100")) {
      count = 100;
      do {
        line.clear();
        if (! _rs.readln(line)) {
          _isKeepalive = false;
          return;
        }
      } while (line.length() != 0 && count-- > 0);
      
      count = 100;
      do {
        line.clear();
        if (! _rs.readln(line)) {
          _isKeepalive = false;
          return;
        }
      } while (line.length() == 0 && count-- > 0);
    }

    if (line.length() == 0) {
      _isKeepalive = false;
      return;
    }

    int i = 0;
    for (i = 0; i < line.length() && line.charAt(i) != ' '; i++) {
    }
    
    for (; i < line.length() && line.charAt(i) == ' '; i++) {
    }
    
    int status = 0;
    for (; i < line.length(); i++) {
      char ch = line.charAt(i);
      if (ch >= '0' && ch <= '9')
        status = 10 * status + ch - '0';
      else
        break;
    }

    if (status != 200)
      _isKeepalive = false;
    else if (! line.startsWith("HTTP/1.1 "))
      _isKeepalive = false;

    _attributes.put("status", String.valueOf(status));
    _attributes.put("status-message", line.toString());

    CharBuffer key = new CharBuffer();
    while (true) {
      line.clear();
      if (! _rs.readln(line) || line.length() == 0)
          break;

      int lineLength = line.length();
      
      for (i = 0;
           i < lineLength && Character.isWhitespace(line.charAt(i));
           i++) {
      }

      key.clear();
      for (;
           i < lineLength && ! Character.isWhitespace(line.charAt(i))
             && line.charAt(i) != ':';
           i++) {
        key.append((char) line.charAt(i));
      }

      for (;
           i < lineLength && Character.isWhitespace(line.charAt(i));
           i++) {
      }

      if (key.length() == 0 || lineLength <= i || line.charAt(i) != ':')
        continue;

      for (i++;
           i < lineLength && Character.isWhitespace(line.charAt(i));
           i++) {
      }

      key.toLowerCase();
      String value = line.substring(i);

      if (log.isLoggable(Level.FINE))
        log.fine(key + ": " + value);
      
      if (key.matchesIgnoreCase("content-length")) {
        _contentLength = Integer.parseInt(value.trim());
      }
      else if (key.matchesIgnoreCase("connection")
               && value.equalsIgnoreCase("close")) {
        _isKeepalive = false;
      }
      else if (key.matchesIgnoreCase("transfer-encoding")
               && value.equalsIgnoreCase("chunked")) {
        
        _isChunked = true;
        _chunkLength = 0;
      }

      String keyString = key.toLowerCase().toString();
      
      String oldValue = (String) _attributes.put(keyString, value);

      if (oldValue != null) {
        value = oldValue + '\n' + value;
      }
      
      _attributes.put(keyString, value);
    }
  }