Reads the OCSP response cache from the server.
<p>
Must be synchronized by OCSP_RESPONSE_CACHE_LOCK.
183742
private void readOcspResponseCacheServer()
  {
    long sleepTime = INITIAL_SLEEPING_TIME_IN_MILLISECONDS;
    DecorrelatedJitterBackoff backoff = new DecorrelatedJitterBackoff(
        sleepTime, MAX_SLEEPING_TIME_IN_MILLISECONDS);
    Exception error = null;
    String ocspCacheServerInUse;

    if (ocspCacheServer.new_endpoint_enabled)
    {
      ocspCacheServerInUse = ocspCacheServer.SF_OCSP_RESPONSE_CACHE_SERVER;
    }
    else
    {
      ocspCacheServerInUse = SF_OCSP_RESPONSE_CACHE_SERVER_URL;
    }

    for (int retry = 0; retry < MAX_RETRY_COUNTER; ++retry)
    {
      try
      {
        HttpClient client = getHttpClient();
        URI uri = new URI(ocspCacheServerInUse);
        HttpGet get = new HttpGet(uri);
        HttpResponse response = client.execute(get);

        if (response == null || response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
        {
          throw new IOException(
              String.format(
                  "Failed to get the OCSP response from the OCSP " +
                  "cache server: HTTP: %d",
                  response != null ? response.getStatusLine().getStatusCode() :
                  -1));
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        IOUtils.copy(response.getEntity().getContent(), out);
        JsonNode m = OBJECT_MAPPER.readTree(out.toByteArray());
        readJsonStoreCache(m);
        LOGGER.debug("Successfully downloaded OCSP cache from the server.");
        return;
      }
      catch (IOException | URISyntaxException ex)
      {
        error = ex;
        LOGGER.debug("Retrying {}/{} after sleeping {}(ms)",
                     retry + 1, MAX_RETRY_COUNTER, sleepTime);
        try
        {
          Thread.sleep(sleepTime);
          sleepTime = backoff.nextSleepTime(sleepTime);
        }
        catch (InterruptedException ex0)
        { // nop
        }
      }
    }
    LOGGER.debug(
        "Failed to read the OCSP response cache from the server. " +
        "Server: {}, Err: {}", ocspCacheServerInUse, error);
  }
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;
    }
942017
static void resetOCSPResponseCacherServerURL(String ocspCacheServerUrl)
  {
    if (ocspCacheServerUrl == null || SF_OCSP_RESPONSE_CACHE_SERVER_RETRY_URL_PATTERN != null)
    {
      return;
    }
    SF_OCSP_RESPONSE_CACHE_SERVER_URL = ocspCacheServerUrl;
    if (!SF_OCSP_RESPONSE_CACHE_SERVER_URL.startsWith(DEFAULT_OCSP_CACHE_HOST))
    {
      try
      {
        URL url = new URL(SF_OCSP_RESPONSE_CACHE_SERVER_URL);
        if (url.getPort() > 0)
        {
          SF_OCSP_RESPONSE_CACHE_SERVER_RETRY_URL_PATTERN =
              String.format("%s://%s:%d/retry/%s",
                            url.getProtocol(), url.getHost(), url.getPort(), "%s/%s");
        }
        else
        {
          SF_OCSP_RESPONSE_CACHE_SERVER_RETRY_URL_PATTERN =
              String.format("%s://%s/retry/%s",
                            url.getProtocol(), url.getHost(), "%s/%s");
        }
      }
      catch (IOException e)
      {
        throw new RuntimeException(
            String.format(
                "Failed to parse SF_OCSP_RESPONSE_CACHE_SERVER_URL: %s",
                SF_OCSP_RESPONSE_CACHE_SERVER_URL));
      }
    }
  }
754647
protected int checkResponse(TCPReadRequestContext rsc) {
        // Parse the proxy server response
        //
        WsByteBuffer[] buffers = rsc.getBuffers();

        // check if the correct response was received
        if (null == buffers) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Could not complete proxy handshake, null buffers");
            }
            return STATUS_ERROR;
        }
        int status = validateProxyResponse(buffers);
        if (STATUS_DONE == status) {
            releaseProxyReadBuffer();
        }
        return status;
    }
902201
public int read(byte []buffer, int offset, int length, long timeout)
    throws IOException
  {
    if (length == 0) {
      throw new IllegalArgumentException();
    }

    long requestExpireTime = _requestExpireTime;

    if (requestExpireTime > 0 && requestExpireTime < CurrentTime.currentTime()) {
      close();
      throw new ClientDisconnectException(L.l("{0}: request-timeout read",
                                              addressRemote()));
    }

    int result = 0;

    synchronized (_readLock) {
      long now = CurrentTime.getCurrentTimeActual();

      long expires;

      // gap is because getCurrentTimeActual() isn't exact
      long gap = 20;

      if (timeout >= 0)
        expires = timeout + now - gap;
      else
        expires = _socketTimeout + now - gap;

      do {
        result = readNative(_socketFd, buffer, offset, length, timeout);

        now = CurrentTime.getCurrentTimeActual();

        timeout = expires - now;
      } while (result == JniStream.TIMEOUT_EXN && timeout > 0);
    }

    return result;
  }
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;
	}
697124
@Override
    public CacheKey getCacheKey(HttpServletRequest request, HttpServletResponse response) {
        final CacheKeyBuilder cacheKeyBuilder = CacheKey.builder(this.getClass().getName());

        for (final TransformerConfigurationSource source : this.sources) {
            final CacheKey key = source.getCacheKey(request, response);
            cacheKeyBuilder.add(key);
        }

        return cacheKeyBuilder.build();
    }
139268
@FFDCIgnore(IOException.class)
    // The feature manager and kernel only do provisioning from a single thread, so this is paranoia, but should
    // never be contended.
    private synchronized void readCache() {
        if (!!!_cacheRead) {
            BufferedReader reader = null;
            try {
                if (_cacheFile != null && _cacheFile.exists() && _cacheFile.isFile()) {
                    reader = new BufferedReader(new FileReader(_cacheFile));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        try {
                            BundleInfo bInfo = new BundleInfo(line);
                            if (bInfo.file.exists() && bInfo.symbolicName != null) {
                                addToCache(bInfo);
                            }
                        } catch (IOException e) {
                            // IOException creating BundleInfo.
                        }
                    }
                }
            } catch (IOException e) {
                // If we can't load the cache then we just throw everything 
                // away and do the more expensive read from original data.
                _bundleLocations.clear();
                _cacheBySymbolicName.clear();
            } finally {
                Utils.tryToClose(reader);
            }
            _cacheRead = true;
            // now we have read the cache we want to insure all base locations are processed.
            for (String loc : new HashSet<String>(_locations)) {
                includeBaseLocation(loc);
            }
        }
    }
808552
def read_cache_results
      @cache_results ||= begin
        mutable_keys = @cache_key_to_engine.keys.map { |k| k.dup }
        if mutable_keys.empty?
          {}
        else
          Rabl.configuration.cache_engine.read_multi(*mutable_keys)
        end
      end
    end
570201
void readStatusResponse() throws SshException, PublicKeySubsystemException {

		ByteArrayReader msg = new ByteArrayReader(nextMessage());

		try {

			msg.readString();
			int status = (int) msg.readInt();
			String desc = msg.readString();

			if (status != PublicKeySubsystemException.SUCCESS) {
				throw new PublicKeySubsystemException(status, desc);
			}
		} catch (IOException ex) {
			throw new SshException(ex);
		} finally {
			try {
				msg.close();
			} catch (IOException e) {
			}
		}
	}
171633
protected Set<ResponseMessage> read(OperationContext context) {
    Set<ResponseMessage> ret;
    try {
      PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
      Resource[] resources = resourceResolver.getResources(
          "classpath*:"
              + context.getName()
              + "*/http-response.springfox");
      // TODO: restdocs in safe package name, not directly under restdocs

      ret = Arrays.stream(resources)
          .map(toRawHttpResponse())
          .filter(Objects::nonNull)
          .collect(Collectors.collectingAndThen(
              toMap(
                  RawHttpResponse::getStatusCode,
                  mappingResponseToResponseMessageBuilder(),
                  mergingExamples()
              ),
              responseMessagesMap -> responseMessagesMap.values()
                  .stream()
                  .map(ResponseMessageBuilder::build)
                  .collect(Collectors.toSet())));
    } catch (
        Exception e) {
      LOG.warn("Failed to read restdocs example for {} " + context.getName() + " caused by: " + e.toString());
      ret = Collections.emptySet();
    }
    return ret;

  }
191639
def read_cache_fixtures!
      files = cache_files
      files.each do |file|
        cache_key = get_cache_key_from_filename(file)
        responses[cache_key] = Marshal.load(File.read(file))
      end
    end
433947
private void loadBytesAsNeeded() throws IOException {
        if (available() <= 0) {
            _isEof = true;
        }

        while ((!_isEof) && (bytesLeftInBuffer() <= 0)) {
            _currentBufferPosition = 0;
            NfsReadResponse response = _file.read(_offset, _bytes.length, _bytes, _currentBufferPosition);
            _bytesInBuffer = response.getBytesRead();
            _offset += _bytesInBuffer;
            _isEof = response.isEof();
        }
    }
1035954
@Override
    public DOReader getReader(boolean cachedObjectRequired, Context context,
            String pid) throws ServerException {
        long getReaderStartTime = logger.isDebugEnabled() ?
                System.currentTimeMillis() : -1;
        String source = null;
        try {
            {
                DOReader reader = null;
                if (m_readerCache != null) {
                    reader = m_readerCache.get(pid);
                }
                if (reader == null) {
                    reader =
                            new SimpleDOReader(context, this, m_translator,
                                    m_defaultExportFormat,
                                    m_defaultStorageFormat,
                                    m_storageCharacterEncoding,
                                    m_permanentStore.retrieveObject(pid));
                    source = "filesystem";
                    if (m_readerCache != null) {
                        m_readerCache.put(reader, getReaderStartTime);
                    }
                } else {
                    source = "memory";
                }
                return reader;
            }
        } finally {
            if (logger.isDebugEnabled()) {
                long dur = System.currentTimeMillis() - getReaderStartTime;
                logger.debug("Got DOReader (source={}) for {} in {}ms.",
                        source, pid, dur);
            }
        }
    }
245393
private void readObject(java.io.ObjectInputStream in)
        throws IOException, ClassNotFoundException
    {
        in.defaultReadObject();
        _cache=new HashMap();
    }
977113
protected VirtualConnection startResponseRead() {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "startResponseRead");
        }
        HttpInvalidMessageException inv = checkRequestValidity();
        if (null != inv) {
            getAppWriteCallback().error(getVC(), inv);
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                Tr.exit(tc, "startResponseRead: error");
            }
            return null;
        }
        // check whether read-ahead is enabled. Bypass this code once the
        // init() method has been called (d264854) and continue as normal
        if (isReadAheadEnabled() && READ_STATE_TIME_RESET != getReadState()) {
            // read ahead is active

            int state = CALLBACK_STATE_IDLE;
            // grab the read-ahead states in a sync block to avoid timing windows
            // with the callback kicking in at the same time
            synchronized (this.stateSyncObject) {
                state = getCallbackState();
                setReadState(READ_STATE_ASYNC);
            }

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Async response read, callback state: " + state);
            }
            switch (state) {
                case (CALLBACK_STATE_COMPLETE):
                    // read-ahead has already completed successfully, start the
                    // parse logic now
                    readAsyncResponse();
                    break;
                case (CALLBACK_STATE_ERROR):
                    // read-ahead already hit an error, trigger that path now
                    setPersistent(false);
                    reConnect(getVC(), this.readException);
                    break;
                case (CALLBACK_STATE_PENDING):
                    // read-ahead is still going on
                    break;
                default:
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "Unexpected state (" + state + ") during async readahead");
                    }
                    setPersistent(false);
                    reConnect(getVC(), new IOException("Read-ahead state failure"));
                    break;
            }
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                Tr.exit(tc, "startResponseRead: read-ahead");
            }
            return null;
        }

        // When we get here, then the final write of the request has finished
        // and we need to tell the app channel of that IF the temp response
        // reads have been triggered. We will not read for a response here as
        // the app channel is using readNextResponse() for that path.
        // LI4335 - early reads also avoid starting read here
        if (this.bEarlyReads || this.bTempResponsesUsed) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                Tr.exit(tc, "startResponseRead: temp resp env");
            }
            getAppWriteCallback().complete(getVC());
            return null;
        }

        // otherwise start the read for the response now...
        getResponseImpl();
        readAsyncResponse();

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "startResponseRead");
        }
        return null;
    }
1238107
@SuppressWarnings("unchecked")
    public void loadCache() {
        if (!cacheManager.isNeedPersist()) {
            return;
        }
        File file = getSaveFile();
        if (null == file) {
            return;
        }
        if (!file.exists()) {
            return;
        }
        BufferedInputStream bis = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte buf[] = new byte[1024];
            int len = -1;
            while ((len = bis.read(buf)) != -1) {
                baos.write(buf, 0, len);
            }
            byte retArr[] = baos.toByteArray();
            Object obj = getPersistSerializer().deserialize(retArr, null);
            if (null != obj && obj instanceof ConcurrentHashMap) {
                cacheManager.getCache().putAll((ConcurrentHashMap<String, Object>) obj);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        } finally {
            if (null != bis) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }