Download object by hash.

@param hash    Object hash.
@param handler Stream handler.
@return Stream handler result.
@throws FileNotFoundException File not found exception if object don't exists on LFS server.
@throws IOException           On some errors.
168775
@NotNull
  public <T> T getObject(@NotNull final String hash, @NotNull final StreamHandler<T> handler) throws IOException {
    return doWork(auth -> {
      final ObjectRes links = doRequest(auth, new MetaGet(), AuthHelper.join(auth.getHref(), PATH_OBJECTS + "/" + hash));
      if (links == null) {
        throw new FileNotFoundException();
      }
      return getObject(new Meta(hash, -1), links, handler);
    }, Operation.Download);
  }
107461
@Override
  protected long download(T object, File outFile) throws IOException
  {
    try {
      return RetryUtils.retry(
          () -> {
            try (final InputStream is = openObjectFunction.open(object);
                 final OutputStream os = new FileOutputStream(outFile)) {
              return IOUtils.copyLarge(is, os, buffer);
            }
          },
          retryCondition,
          outFile::delete,
          maxFetchRetry + 1,
          StringUtils.format("Failed to download object[%s]", object)
      );
    }
    catch (Exception e) {
      throw new IOException(e);
    }
  }
450693
public FileSender sendFile(String filePath, final Handler<AsyncResult<Void>> doneHandler) {
    final File file = new File(filePath);
    output.vertx().fileSystem().exists(file.getAbsolutePath(), new Handler<AsyncResult<Boolean>>() {
      @Override
      public void handle(AsyncResult<Boolean> result) {
        if (result.failed()) {
          new DefaultFutureResult<Void>(result.cause()).setHandler(doneHandler);
        } else if (!result.result()) {
          new DefaultFutureResult<Void>(new IOException("File not found.")).setHandler(doneHandler);
        } else {
          output.group("file", file.getName(), new Handler<OutputGroup>() {
            @Override
            public void handle(final OutputGroup group) {
              output.vertx().fileSystem().open(file.getAbsolutePath(), new Handler<AsyncResult<AsyncFile>>() {
                @Override
                public void handle(AsyncResult<AsyncFile> result) {
                  if (result.failed()) {
                    new DefaultFutureResult<Void>(result.cause()).setHandler(doneHandler);
                  } else {
                    doSendFile(result.result(), group, doneHandler);
                  }
                }
              });
            }
          });
        }
      }
    });
    return this;
  }
585758
function download(input, output) {
	if (!output) output = input.split("/").pop();
	var file = fs.createWriteStream(output);
	var request = http.get(input, response => { response.pipe(file); });
}
216028
@NonNull
    private static byte[] download(String url) throws IOException {
        InputStream is = null;
        ByteArrayOutputStream os = null;

        try {

            final URL u = new URL(url);
            final URLConnection connection = u.openConnection();
            connection.connect();

            is = connection.getInputStream();
            os = new ByteArrayOutputStream();

            final byte[] buffer = new byte[4096];
            int read;

            while (true) {
                read = is.read(buffer, 0, buffer.length);
                if (read == -1) {
                    break;
                }
                os.write(buffer, 0, read);
            }

            return os.toByteArray();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ignored) {
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ignored) {
                }
            }
        }
    }
1353134
public <R> R download(String uri,
			ContentHandler<BasicHttpResponse, R> handler)
			throws RedmineException {
		final HttpGet request = new HttpGet(uri);
		return errorCheckingCommunicator.sendRequest(request, handler);
	}
303333
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
        s.defaultReadObject();
        mRequestHandler =  new DownloadRequestHandler(this);
    }
1194932
private void downloadOneChunk(String accountId, String vaultName,
            String jobId, RandomAccessFile output, long currentPosition,
            long endPosition, ProgressListener progressListener) {
        final long chunkSize = endPosition - currentPosition + 1;
        TreeHashInputStream input = null;
        int retries = 0;
        while (true) {
            try {
                GetJobOutputRequest req = new GetJobOutputRequest()
                    .withAccountId(accountId)
                    .withVaultName(vaultName)
                    .withRange("bytes=" + currentPosition + "-" + endPosition)
                    .withJobId(jobId)
                    .withGeneralProgressListener(progressListener)
                    ;
                GetJobOutputResult jobOutputResult = glacier.getJobOutput(req);
                try {
                    input = new TreeHashInputStream(new BufferedInputStream(jobOutputResult.getBody()));
                    appendToFile(output, input);
                } catch (NoSuchAlgorithmException e) {
                    throw failure(e, "Unable to compute hash for data integrity");
                } finally {
                    closeQuietly(input, log);
                }

                // Only do tree-hash check when the output checksum is returned from Glacier
                if (null != jobOutputResult.getChecksum()) {
                    // Checksum does not match
                    if (!input.getTreeHash().equalsIgnoreCase(jobOutputResult.getChecksum())) {
                        // Discard the chunk of bytes received 
                        publishResponseBytesDiscarded(progressListener, chunkSize);
                        if (log.isDebugEnabled())
                            log.debug("reverting " + chunkSize);
                        throw new IOException("Client side computed hash doesn't match server side hash; possible data corruption");
                    }
                } else {
                    log.warn("Cannot validate the downloaded output since no tree-hash checksum is returned from Glacier. "
                            + "Make sure the InitiateJob and GetJobOutput requests use tree-hash-aligned ranges.");
                }
                // Successfully download
                return;
                // We will retry IO exception
            } catch (IOException ioe) {
                if (retries < DEFAULT_MAX_RETRIES) {
                    retries++;
                    if (log.isDebugEnabled()) {
                        log.debug(retries
                                + " retry downloadOneChunk accountId="
                                + accountId + ", vaultName=" + vaultName
                                + ", jobId=" + jobId + ", currentPosition="
                                + currentPosition + " endPosition="
                                + endPosition);
                    }
                    try {
                        output.seek(currentPosition);
                    } catch (IOException e) {
                        throw new AmazonClientException("Unable to download the archive: " + ioe.getMessage(), e);
                    }
                } else {
                    throw new AmazonClientException("Unable to download the archive: " + ioe.getMessage(), ioe);
                }
            }
        }
    }
294232
public <R> R download(String uri,
			ContentHandler<BasicHttpResponse, R> handler)
			throws RedmineException {
		final URI requestUri = configurator.addAPIKey(uri);
		final HttpGet request = new HttpGet(requestUri);
        if (onBehalfOfUser != null) {
            request.addHeader("X-Redmine-Switch-User", onBehalfOfUser);
        }
        return errorCheckingCommunicator.sendRequest(request, handler);
    }
168159
private synchronized void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();

        // rebuild hash hashtable
        hash = new Hashtable<>();
        for (NameValue<N, V> nameValue : order) {
            putInHash(nameValue.name, nameValue.value);
        }
    }
739607
def ReceiveFileHash(self, responses):
    """"""
    index = responses.request_data["index"]
    if not responses.success:
      self.Log("Failed to hash file: %s", responses.status)
      self.state.pending_hashes.pop(index, None)
      # Report the error.
      self._FileFetchFailed(index, "HashFile")
      return

    self.state.files_hashed += 1
    response = responses.First()
    if response.HasField("hash"):
      hash_obj = response.hash
    else:
      # Deprecate this method of returning hashes.
      hash_obj = rdf_crypto.Hash()

      if len(response.results) < 1 or response.results[0]["name"] != "generic":
        self.Log("Failed to hash file: %s", self.state.indexed_pathspecs[index])
        self.state.pending_hashes.pop(index, None)
        return

      result = response.results[0]

      try:
        for hash_type in ["md5", "sha1", "sha256"]:
          value = result.GetItem(hash_type)
          setattr(hash_obj, hash_type, value)
      except AttributeError:
        self.Log("Failed to hash file: %s", self.state.indexed_pathspecs[index])
        self.state.pending_hashes.pop(index, None)
        return

    try:
      tracker = self.state.pending_hashes[index]
    except KeyError:
      # Hashing the file failed, but we did stat it.
      self._FileFetchFailed(index, responses.request.request.name)
      return

    tracker["hash_obj"] = hash_obj
    tracker["bytes_read"] = response.bytes_read

    self.state.files_hashed_since_check += 1
    if self.state.files_hashed_since_check >= self.MIN_CALL_TO_FILE_STORE:
      self._CheckHashesWithFileStore()
339372
public Blade get(@NonNull String path, @NonNull RouteHandler handler) {
        this.routeMatcher.addRoute(path, handler, HttpMethod.GET);
        return this;
    }
567251
@Override
  public InputStream getFileStream(String file) throws FileBasedHelperException {
    SftpGetMonitor monitor = new SftpGetMonitor();
    try {
      ChannelSftp channel = getSftpChannel();
      return new SftpFsFileInputStream(channel.get(file, monitor), channel);
    } catch (SftpException e) {
      throw new FileBasedHelperException("Cannot download file " + file + " due to " + e.getMessage(), e);
    }
  }
1062502
def get(self, multihash, **kwargs):
        
        args = (multihash,)
        return self._client.download('/get', args, **kwargs)
542413
@Advice.OnMethodExit
	public static void afterGetHandler(@Advice.Return Object handler) {
		SpringMvcRequestNameDeterminerTransformer.setRequestNameByHandler(handler);
	}
1082856
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        //Only GET methods are allowed
        if ($request->getMethod() !== 'GET') {
            if ($this->continueOnError) {
                return $handler->handle($request);
            }

            return $this->createResponse(405)->withHeader('Allow', 'GET');
        }

        $file = static::getFilename($request->getUri()->getPath());

        if ($this->filesystem->has($file)) {
            return $this->read($request, $file);
        }

        //If the file does not exists, check if is gzipped
        $file .= '.gz';

        if (stripos($request->getHeaderLine('Accept-Encoding'), 'gzip') === false || !$this->filesystem->has($file)) {
            if ($this->continueOnError) {
                return $handler->handle($request);
            }

            return $this->createResponse(404);
        }

        return $this->read($request, $file)->withHeader('Content-Encoding', 'gzip');
    }
1035980
def stream(key)
        object = object_for(key)

        chunk_size = 5.megabytes
        offset = 0

        raise ActiveStorage::FileNotFoundError unless object.exists?

        while offset < object.content_length
          yield object.get(range: "bytes=#{offset}-#{offset + chunk_size - 1}").body.string.force_encoding(Encoding::BINARY)
          offset += chunk_size
        end
      end