readResponse - Read the bytes for the response from the slave.

@return a <tt>ModbusRespose</tt>

@throws com.ghgande.j2mod.modbus.ModbusIOException If the response cannot be read from the socket/port
174184
protected ModbusResponse readResponseIn() throws ModbusIOException {
        boolean done;
        ModbusResponse response;
        int dlength;

        try {
            do {
                // 1. read to function code, create request and read function
                // specific bytes
                synchronized (byteInputStream) {
                    int uid = readByte();

                    if (uid != -1) {
                        int fc = readByte();
                        byteInputOutputStream.reset();
                        byteInputOutputStream.writeByte(uid);
                        byteInputOutputStream.writeByte(fc);

                        // create response to acquire length of message
                        response = ModbusResponse.createModbusResponse(fc);
                        response.setHeadless();

                        /*
                         * With Modbus RTU, there is no end frame. Either we
                         * assume the message is complete as is or we must do
                         * function specific processing to know the correct
                         * length. To avoid moving frame timing to the serial
                         * input functions, we set the timeout and to message
                         * specific parsing to read a response.
                         */
                        getResponse(fc, byteInputOutputStream);
                        dlength = byteInputOutputStream.size() - 2; // less the crc
                        if (logger.isDebugEnabled()) {
                            logger.debug("Response: {}", ModbusUtil.toHex(byteInputOutputStream.getBuffer(), 0, dlength + 2));
                        }
                        byteInputStream.reset(inBuffer, dlength);

                        // check CRC
                        int[] crc = ModbusUtil.calculateCRC(inBuffer, 0, dlength); // does not include CRC
                        if (ModbusUtil.unsignedByteToInt(inBuffer[dlength]) != crc[0] || ModbusUtil.unsignedByteToInt(inBuffer[dlength + 1]) != crc[1]) {
                            logger.debug("CRC should be {}, {}", crc[0], crc[1]);
                            throw new IOException("CRC Error in received frame: " + dlength + " bytes: " + ModbusUtil.toHex(byteInputStream.getBuffer(), 0, dlength));
                        }
                    }
                    else {
                        throw new IOException("Error reading response");
                    }

                    // read response
                    byteInputStream.reset(inBuffer, dlength);
                    response.readFrom(byteInputStream);
                    done = true;
                }
            } while (!done);
            return response;
        }
        catch (IOException ex) {
            // FIXME: This printout is wrong when reading response from other slave
            throw new ModbusIOException("I/O exception - failed to read response for request [%s] - %s", ModbusUtil.toHex(lastRequest), ex.getMessage());
        }
    }
816580
def _read_response(self):
        
        try:
            line = self.readline()
        except RuntimeError:
            Dut._logger.warning("Failed to read PIPE", extra={'type': '!<-'})
            return -1
        if line:
            if self.store_traces:
                self.traces.append(line)
                self.response_traces.append(line)
            EventObject(EventTypes.DUT_LINE_RECEIVED, self, line)
            match = re.search(r"^\[([\w\W]{4})\]\[([\W\w]{4,}?)\]\: (.*)", line)
            if match:
                self.logger.debug(line, extra={'type': '<<<'})
            else:
                self.logger.info(line, extra={'type': '<--'})

            retcode = self.check_retcode(line)
            if retcode is not None:
                resp = CliResponse()
                resp.retcode = retcode
                resp.traces = self.response_traces
                resp.lines = self.response_traces
                self.response_traces = []
                return resp
        return None
185513
def _get_response(self, connection):
        

        response_header = self._receive(connection, 13)
        logger.debug('Response header: %s', response_header)

        if (not response_header.startswith(b'ZBXD\x01') or
                len(response_header) != 13):
            logger.debug('Zabbix return not valid response.')
            result = False
        else:
            response_len = struct.unpack('<Q', response_header[5:])[0]
            response_body = connection.recv(response_len)
            result = json.loads(response_body.decode("utf-8"))
            logger.debug('Data received: %s', result)

        try:
            connection.close()
        except Exception as err:
            pass

        return result
926092
public function read()
    {
        // First, read headers only
        $response = '';
        $gotStatus = false;

        while (($line = @fgets($this->socket)) !== false) {
            $gotStatus = $gotStatus || (strpos($line, 'HTTP') !== false);
            if ($gotStatus) {
                $response .= $line;
                if (rtrim($line) === '') break;
            }
        }

        $this->_checkSocketReadTimeout();

        $statusCode = Zend_Http_Response::extractCode($response);

        // Handle 100 and 101 responses internally by restarting the read again
        if ($statusCode == 100 || $statusCode == 101) return $this->read();

        // Check headers to see what kind of connection / transfer encoding we have
        $headers = Zend_Http_Response::extractHeaders($response);

        /**
         * Responses to HEAD requests and 204 or 304 responses are not expected
         * to have a body - stop reading here
         */
        if ($statusCode == 304 || $statusCode == 204 ||
            $this->method == Zend_Http_Client::HEAD) {

            // Close the connection if requested to do so by the server
            if (isset($headers['connection']) && $headers['connection'] == 'close') {
                $this->close();
            }
            return $response;
        }

        // If we got a 'transfer-encoding: chunked' header
        if (isset($headers['transfer-encoding'])) {

            if (strtolower($headers['transfer-encoding']) == 'chunked') {

                do {
                    $line  = @fgets($this->socket);
                    $this->_checkSocketReadTimeout();

                    $chunk = $line;

                    // Figure out the next chunk size
                    $chunksize = trim($line);
                    if (! ctype_xdigit($chunksize)) {
                        $this->close();

                        throw new Zend_Http_Client_Adapter_Exception('Invalid chunk size "' .
                            $chunksize . '" unable to read chunked body');
                    }

                    // Convert the hexadecimal value to plain integer
                    $chunksize = hexdec($chunksize);

                    // Read next chunk
                    $read_to = ftell($this->socket) + $chunksize;

                    do {
                        $current_pos = ftell($this->socket);
                        if ($current_pos >= $read_to) break;

                        if($this->out_stream) {
                            if(stream_copy_to_stream($this->socket, $this->out_stream, $read_to - $current_pos) == 0) {
                              $this->_checkSocketReadTimeout();
                              break;
                             }
                        } else {
                            $line = @fread($this->socket, $read_to - $current_pos);
                            if ($line === false || strlen($line) === 0) {
                                $this->_checkSocketReadTimeout();
                                break;
                            }
                                    $chunk .= $line;
                        }
                    } while (! feof($this->socket));

                    $chunk .= @fgets($this->socket);
                    $this->_checkSocketReadTimeout();

                    if(!$this->out_stream) {
                        $response .= $chunk;
                    }
                } while ($chunksize > 0);
            } else {
                $this->close();

                throw new Zend_Http_Client_Adapter_Exception('Cannot handle "' .
                    $headers['transfer-encoding'] . '" transfer encoding');
            }

            // We automatically decode chunked-messages when writing to a stream
            // this means we have to disallow the Zend_Http_Response to do it again
            if ($this->out_stream) {
                $response = str_ireplace("Transfer-Encoding: chunked\r\n", '', $response);
            }
        // Else, if we got the content-length header, read this number of bytes
        } elseif (isset($headers['content-length'])) {

            // If we got more than one Content-Length header (see ZF-9404) use
            // the last value sent
            if (is_array($headers['content-length'])) {
                $contentLength = $headers['content-length'][count($headers['content-length']) - 1];
            } else {
                $contentLength = $headers['content-length'];
            }

            $current_pos = ftell($this->socket);
            $chunk = '';

            for ($read_to = $current_pos + $contentLength;
                 $read_to > $current_pos;
                 $current_pos = ftell($this->socket)) {

                 if($this->out_stream) {
                     if(@stream_copy_to_stream($this->socket, $this->out_stream, $read_to - $current_pos) == 0) {
                          $this->_checkSocketReadTimeout();
                          break;
                     }
                 } else {
                    $chunk = @fread($this->socket, $read_to - $current_pos);
                    if ($chunk === false || strlen($chunk) === 0) {
                        $this->_checkSocketReadTimeout();
                        break;
                    }

                    $response .= $chunk;
                }

                // Break if the connection ended prematurely
                if (feof($this->socket)) break;
            }

        // Fallback: just read the response until EOF
        } else {

            do {
                if($this->out_stream) {
                    if(@stream_copy_to_stream($this->socket, $this->out_stream) == 0) {
                          $this->_checkSocketReadTimeout();
                          break;
                     }
                }  else {
                    $buff = @fread($this->socket, 8192);
                    if ($buff === false || strlen($buff) === 0) {
                        $this->_checkSocketReadTimeout();
                        break;
                    } else {
                        $response .= $buff;
                    }
                }

            } while (feof($this->socket) === false);

            $this->close();
        }

        // Close the connection if requested to do so by the server
        if (isset($headers['connection']) && $headers['connection'] == 'close') {
            $this->close();
        }

        return $response;
    }
664645
@Override
    protected void readResponseHeaders(HttpState state, HttpConnection conn) throws IOException, HttpException {
        getResponseHeaderGroup().clear();

        Header[] headers = ZapHttpParser.parseHeaders(conn.getResponseInputStream(), getParams().getHttpElementCharset());
        // Wire logging moved to HttpParser
        getResponseHeaderGroup().setHeaders(headers);
    }
111398
public static DnsResponse readDnsResponse(ByteBuf payload) throws ParseException {
		try {
			short transactionId = payload.readShort();
			payload.moveHead(1); // skip first flags byte

			//                                                                    last 4 flag bits are error code
			ResponseErrorCode errorCode = ResponseErrorCode.fromBits(payload.readByte() & 0b00001111);

			short questionCount = payload.readShort();
			short answerCount = payload.readShort();
			payload.moveHead(4); // skip authority and additional counts (2 bytes each)

			if (questionCount != 1) {
				// malformed response, we are always sending only one question
				throw QUESTION_COUNT_NOT_ONE;
			}

			// read domain name from first query
			StringBuilder sb = new StringBuilder();
			byte componentSize = payload.readByte();
			while (componentSize != 0) {
				sb.append(new String(payload.array(), payload.head(), componentSize, US_ASCII));
				payload.moveHead(componentSize);
				componentSize = payload.readByte();
				if (componentSize != 0) {
					sb.append('.');
				}
			}
			String domainName = sb.toString();

			// read query record type
			short recordTypeCode = payload.readShort();
			RecordType recordType = RecordType.fromCode(recordTypeCode);
			if (recordType == null) {
				// malformed response, we are sending query only with existing RecordType's
				throw new UnknownFormatException(DnsProtocol.class, "Received DNS response with unknown query record type (" +
						Integer.toHexString(recordTypeCode & 0xFFFF) + ")");
			}

			// read query class (only for sanity check)
			short queryClassCode = payload.readShort();
			QueryClass queryClass = QueryClass.fromCode(queryClassCode);
			if (queryClass != QueryClass.INTERNET) {
				throw new UnknownFormatException(DnsProtocol.class, "Received DNS response with unknown query class (" +
						Integer.toHexString(queryClassCode & 0xFFFF) + ")");
			}

			// at this point, we know the query of this response
			DnsQuery query = DnsQuery.of(domainName, recordType);

			// and so we have all the data to fail if error code is not zero
			DnsTransaction transaction = DnsTransaction.of(transactionId, query);
			if (errorCode != ResponseErrorCode.NO_ERROR) {
				return DnsResponse.ofFailure(transaction, errorCode);
			}

//			// skip other queries if any (we are sending only one and checking for it above, so this is dead code)
//			for (int i = 0; i < questionCount - 1; i++) {
//				// skip domain name (bytes until zero-terminator)
//				while ((componentSize = payload.readByte()) != 0) {
//					payload.moveHead(componentSize);
//				}
//				payload.moveHead(4); // skip query record type and class (2 bytes each)
//			}

			List<InetAddress> ips = new ArrayList<>();
			int minTtl = Integer.MAX_VALUE;
			for (int i = 0; i < answerCount; i++) {
				payload.moveHead(2); // skip answer name (2 bytes)
				RecordType currentRecordType = RecordType.fromCode(payload.readShort());
				payload.moveHead(2); // skip answer class (2 bytes)
				if (currentRecordType != recordType) { // this is some other record
					payload.moveHead(4); // skip ttl
					payload.moveHead(payload.readShort()); // and skip data
					continue;
				}
				minTtl = Math.min(payload.readInt(), minTtl);
				short length = payload.readShort();
				if (length != recordType.dataLength) {
					throw new InvalidSizeException(DnsProtocol.class, "Bad record length received. " + recordType +
							"-record length should be " + recordType.dataLength + " bytes, it was " + length);
				}
				byte[] bytes = new byte[length];
				payload.read(bytes);
				try {
					ips.add(InetAddress.getByAddress(domainName, bytes));
				} catch (UnknownHostException ignored) {
					// never happens, we have explicit check for length
				}
			}
			// fail if no IPs were parsed (or answer count was zero)
			if (ips.isEmpty()) {
				return DnsResponse.ofFailure(transaction, NO_DATA);
			}
			return DnsResponse.of(transaction, DnsResourceRecord.of(ips.toArray(new InetAddress[0]), minTtl));
		} catch (IndexOutOfBoundsException e) {
			throw new ParseException(DnsProtocol.class, "Failed parsing DNS response", e);
		}
	}
1022601
def get_response(request)
      begin
        data = @transport.recv(@max_bytes)
        message = Message.decode(data, @mib)
        response = message.pdu
      end until request.request_id == response.request_id
      response
    end
1318754
public synchronized HttpResponseBody readResponseBody(HttpHeader httpHeader) {

		int contentLength = httpHeader.getContentLength();	// -1 = default to unlimited length until connection close
		
		HttpResponseBody body = (contentLength > 0) ? new HttpResponseBody(contentLength) : new HttpResponseBody();
		
		readBody(contentLength, body);
		
		return body;
	}
512005
public byte[] getResponseBodyAsByteArray() {
        final ByteBuf bodyByteBuf = httpInputMessage.getBody();
        final byte[] bytes = new byte[bodyByteBuf.readableBytes()];
        bodyByteBuf.readBytes(bytes);
        return bytes;
    }
1349988
private <T extends Object> T getResponse(HttpResponse httpResponse, Class<T> clazz) throws IOException, HttpRosetteAPIException {
        int status = httpResponse.getStatusLine().getStatusCode();
        String encoding = headerValueOrNull(httpResponse.getFirstHeader(HttpHeaders.CONTENT_ENCODING));

        try (
                InputStream stream = httpResponse.getEntity().getContent();
                InputStream inputStream = "gzip".equalsIgnoreCase(encoding) ? new GZIPInputStream(stream) : stream) {
            String ridHeader = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteAPI-DocumentRequest-Id"));
            if (HTTP_OK != status) {
                String ecHeader = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteAPI-Status-Code"));
                String emHeader = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteAPI-Status-Message"));
                String responseContentType = headerValueOrNull(httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE));
                if ("application/json".equals(responseContentType)) {
                    ErrorResponse errorResponse = mapper.readValue(inputStream, ErrorResponse.class);
                    if (ridHeader != null) {
                        LOG.debug("DocumentRequest ID " + ridHeader);
                    }
                    if (ecHeader != null) {
                        errorResponse.setCode(ecHeader);
                    }
                    if (429 == status) {
                        String concurrencyMessage = "You have exceeded your plan's limit on concurrent calls. "
                                + "This could be caused by multiple processes or threads making Rosette API calls in parallel, "
                                + "or if your httpClient is configured with higher concurrency than your plan allows.";
                        if (emHeader == null) {
                            emHeader = concurrencyMessage;
                        } else {
                            emHeader = concurrencyMessage + System.lineSeparator() + emHeader;
                        }
                    }
                    if (emHeader != null) {
                        errorResponse.setMessage(emHeader);
                    }
                    throw new HttpRosetteAPIException(errorResponse, status);
                } else {
                    String errorContent;
                    if (inputStream != null) {
                        byte[] content = getBytes(inputStream);
                        errorContent = new String(content, "utf-8");
                    } else {
                        errorContent = "(no body)";
                    }
                    // something not from us at all
                    throw new HttpRosetteAPIException("Invalid error response (not json)",
                            ErrorResponse.builder().code("invalidErrorResponse").message(errorContent).build(), status);
                }
            } else {
                return mapper.readValue(inputStream, clazz);
            }
        }
    }
110925
@Override
    public T handleResponse(final HttpResponse response) throws IOException {

        InputStream content = null;
        final T addresses;

        try {
            final StatusLine status = response.getStatusLine();
            if (status.getStatusCode() >= HttpStatus.SC_BAD_REQUEST) {
                throw new IOException(String.format("HTTP error: %s %s", status.getStatusCode(), status.getReasonPhrase()));
            }
            content = response.getEntity().getContent();
            addresses = gsonInstance
                    .fromJson(new InputStreamReader(content, "utf-8"), responseType);
        } finally {
            if (null != content) {
                content.close();
            }
            response.getEntity().consumeContent();
        }

        return addresses;
    }
218311
@Override
    protected void readResponse(HttpState state, HttpConnection conn)
    throws IOException, HttpException {
        LOG.trace("enter HttpMethodBase.readResponse(HttpState, HttpConnection)");
        
        boolean isUpgrade = false;
        
		while (getStatusLine() == null) {
            readStatusLine(state, conn);
            processStatusLine(state, conn);
            readResponseHeaders(state, conn);
            processResponseHeaders(state, conn);
            
            int status = this.statusLine.getStatusCode();
            if (status == 101) {
            	LOG.debug("Retrieved HTTP status code '101 Switching Protocols'. Keep connection open!");

            	// This means the requester has asked the server to switch protocols
            	// and the server is acknowledging that it will do so
            	// e.g.: upgrade to websocket
            	
				if (conn instanceof ZapHttpConnection) {
	            	isUpgrade = true;
	            	// avoid connection release of HttpClient library 
	            	conn.setHttpConnectionManager(null);
	            }
            } else if ((status >= 100) && (status < 200)) {
                if (LOG.isInfoEnabled()) {
                    LOG.info("Discarding unexpected response: " + this.statusLine.toString()); 
                }
                this.statusLine = null;
            }
        }

    	// get socket and input stream out of HttpClient
		if (conn instanceof ZapHttpConnection) {
			ZapHttpConnection zapConn = (ZapHttpConnection) conn;
	    	upgradedSocket = zapConn.getSocket();
			inputStream = zapConn.getResponseInputStream();
		}
		
		if (!isUpgrade) {
			// read & process rest of response
			// only if connection should not be kept
	        readResponseBody(state, conn);        
	        processResponseBody(state, conn);
		}
    }
803889
protected <T, E> T handleResponse(final HttpURLConnection connection,
			final DataTypeDescriptor<T> datad, final DataTypeDescriptor<E> errord)
			throws IOException {
		connection.connect();

		int status = connection.getResponseCode();
		if (status == HttpURLConnection.HTTP_OK) {
			// It's a successful response, try to read the result.
			return readResult(connection, datad);

		} else if (status == APPLICATION_EXC_STATUS) {
			// It's an expected application exception.
			throw (RuntimeException) readApplicationException(connection, errord);

		} else {
			// Something bad happened, try to read the error message.
			throw readError(connection);
		}
	}
141389
def _read_response(self, response):
        
        rclass = response['rclass']
        if rclass != "virtual":
            raise ArtifactoryException("Repositiry '{}' have '{}', but expect 'virtual'".format(self.name, rclass))

        self.name = response["key"]
        self.description = response["description"]
        self.packageType = response["packageType"]
        self._repositories = response["repositories"]
233527
byte[] readSignResponse() throws IOException {
    // Read the first 9 bytes from the InputStream which are the SSH2_AGENT_SIGN_RESPONSE headers.
    final byte[] headerBytes = readBytes(9, "SSH2_AGENT_SIGN_RESPONSE");
    log.debug("Received SSH2_AGENT_SIGN_RESPONSE message from ssh-agent.");
    final SignResponseHeaders headers = SignResponseHeaders.from(headerBytes);

    // Read the rest of the SSH2_AGENT_SIGN_RESPONSE message from ssh-agent.
    // 5 is the sum of the number of bytes of response code and response length
    final byte[] bytes = readBytes(headers.getLength() - 5);
    final ByteIterator iterator = new ByteIterator(bytes);
    final byte[] responseType = iterator.next();

    final String signatureFormatId = new String(responseType);
    if (!signatureFormatId.equals(Rsa.RSA_LABEL)) {
      throw new RuntimeException("I unexpectedly got a non-Rsa signature format ID in the "
                                 + "SSH2_AGENT_SIGN_RESPONSE's signature blob.");
    }

    return iterator.next();
  }
724644
def read(self):
    """"""
    if FLAGS.sc2_verbose_protocol:
      self._log(" Reading response ".center(60, "-"))
      start = time.time()
    response = self._read()
    if FLAGS.sc2_verbose_protocol:
      self._log(" %0.1f msec\n" % (1000 * (time.time() - start)))
      self._log_packet(response)
    if not response.HasField("status"):
      raise ProtocolError("Got an incomplete response without a status.")
    prev_status = self._status
    self._status = Status(response.status)  # pytype: disable=not-callable
    if response.error:
      err_str = ("Error in RPC response (likely a bug). "
                 "Prev status: %s, new status: %s, error:\n%s" % (
                     prev_status, self._status, "\n".join(response.error)))
      logging.error(err_str)
      raise ProtocolError(err_str)
    return response
1364728
protected Response getResponse(Object connection, Object responseObject) throws IOException {
        Response response = new Response();
        response.setObject(responseObject);
        response.setContent(externalResponseToString(responseObject));
        return response;
    }