Attempts a resumable upload.

        Returns etag from server upon success.

        Raises ResumableUploadException if any problems occur.
495629
def _attempt_resumable_upload(self, key, fp, file_length, headers, cb,
                                  num_cb):
        
        (server_start, server_end) = self.SERVER_HAS_NOTHING
        conn = key.bucket.connection
        if self.tracker_uri:
            # Try to resume existing resumable upload.
            try:
                (server_start, server_end) = (
                    self._query_server_pos(conn, file_length))
                self.server_has_bytes = server_start
                key=key
                if conn.debug >= 1:
                    print 'Resuming transfer.'
            except ResumableUploadException, e:
                if conn.debug >= 1:
                    print 'Unable to resume transfer (%s).' % e.message
                self._start_new_resumable_upload(key, headers)
        else:
            self._start_new_resumable_upload(key, headers)

        # upload_start_point allows the code that instantiated the
        # ResumableUploadHandler to find out the point from which it started
        # uploading (e.g., so it can correctly compute throughput).
        if self.upload_start_point is None:
            self.upload_start_point = server_end

        if server_end == file_length:
            # Boundary condition: complete file was already uploaded (e.g.,
            # user interrupted a previous upload attempt after the upload
            # completed but before the gsutil tracker file was deleted). Set
            # total_bytes_uploaded to server_end so we'll attempt to upload
            # no more bytes but will still make final HTTP request and get
            # back the response (which contains the etag we need to compare
            # at the end).
            total_bytes_uploaded = server_end
        else:
            total_bytes_uploaded = server_end + 1
        fp.seek(total_bytes_uploaded)
        conn = key.bucket.connection

        # Get a new HTTP connection (vs conn.get_http_connection(), which reuses
        # pool connections) because httplib requires a new HTTP connection per
        # transaction. (Without this, calling http_conn.getresponse() would get
        # "ResponseNotReady".)
        http_conn = conn.new_http_connection(self.tracker_uri_host,
                                             conn.is_secure)
        http_conn.set_debuglevel(conn.debug)

        # Make sure to close http_conn at end so if a local file read
        # failure occurs partway through server will terminate current upload
        # and can report that progress on next attempt.
        try:
            return self._upload_file_bytes(conn, http_conn, fp, file_length,
                                           total_bytes_uploaded, cb, num_cb)
        except (ResumableUploadException, socket.error):
            resp = self._query_server_state(conn, file_length)
            if resp.status == 400:
                raise ResumableUploadException('Got 400 response from server '
                    'state query after failed resumable upload attempt. This '
                    'can happen for various reasons, including specifying an '
                    'invalid request (e.g., an invalid canned ACL) or if the '
                    'file size changed between upload attempts',
                    ResumableTransferDisposition.ABORT)
            else:
                raise
        finally:
            http_conn.close()
388734
def canonical(request, uploaded_at, file_id):
    
    filer_file = get_object_or_404(File, pk=file_id, is_public=True)
    if (uploaded_at != filer_file.uploaded_at.strftime('%s') or
            not filer_file.file):
        raise Http404('No %s matches the given query.' %
                      File._meta.object_name)
    return redirect(filer_file.url)
1185003
def reachable_for_upload? (pw)
      return :mountable if mounted?
      return false unless check_pw :rw , pw
      begin
        mount pw, :rw
        return :mountable
      rescue
        return false
      ensure
        unmount
      end
    end
123502
def is_error_retryable(request, exc):
    
    if is_last_attempt(request):
        return False

    return (
        isinstance(exc, RetryableException)
        or IRetryableError.providedBy(exc)
    )
498883
function(e){
          var status = $.status();
          if(status=='success'||status=='error') {
            $.callback(status, $.message());
            $.resumableObj.uploadNextChunk();
          } else {
            $.callback('retry', $.message());
            $.abort();
            $.retries++;
            var retryInterval = $.getOpt('chunkRetryInterval');
            if(retryInterval !== undefined) {
              $.pendingRetry = true;
              setTimeout($.send, retryInterval);
            } else {
              $.send();
            }
          }
        }
570908
private void captureUploadStateIfPossible() {
        if (origReq.getSSECustomerKey() == null) {
            persistableUpload = new PersistableUpload(origReq.getBucketName(),
                    origReq.getKey(), origReq.getFile()
                            .getAbsolutePath(), multipartUploadId,
                    configuration.getMinimumUploadPartSize(),
                    configuration.getMultipartUploadThreshold());
            notifyPersistableTransferAvailability();
        }
    }
516214
def push(tool, slug, config_loader, prompt=lambda included, excluded: True):
    
    check_dependencies()

    org, (included, excluded) = connect(slug, config_loader)

    with authenticate(org) as user, prepare(tool, slug, user, included):
        if prompt(included, excluded):
            return upload(slug, user, tool)
        else:
            raise Error(_("No files were submitted."))
690041
def _call(self, method, url, params, uploads):
        
        try:
            data = self._request(method, url, params, uploads)
        except Exception, e:
            self._failed_cb(e)
        else:
            self._completed_cb(data)
489787
private <RequestT, ResponseT> ResponseT uploadObject(final InputStream originalStream,
                                                         final File file,
                                                         final ObjectMetadata metadata,
                                                         final ProgressListener listener,
                                                         final Request<RequestT> request,
                                                         final S3DataSource originalRequest,
                                                         final boolean skipServerSideValidation,
                                                         final boolean skipClientSideValidationPerRequest,
                                                         final UploadObjectStrategy<RequestT, ResponseT> uploadStrategy,
                                                         final boolean setContentTypeIfNotProvided) {

        InputStream input = getInputStream(originalStream, file, metadata, request,
                                           skipServerSideValidation, setContentTypeIfNotProvided);

        final ObjectMetadata returnedMetadata;
        MD5DigestCalculatingInputStream md5DigestStream = null;
        try {
            if (metadata.getContentMD5() == null && !skipClientSideValidationPerRequest) {
                /*
                 * If the user hasn't set the content MD5, then we don't want to buffer the whole
                 * stream in memory just to calculate it. Instead, we can calculate it on the fly
                 * and validate it with the returned ETag from the object upload.
                 */
                input = md5DigestStream = new MD5DigestCalculatingInputStream(input);
            }

            populateRequestMetadata(request, metadata);
            request.setContent(input);
            publishProgress(listener, ProgressEventType.TRANSFER_STARTED_EVENT);
            try {
                returnedMetadata = uploadStrategy.invokeServiceCall(request);
            } catch (Throwable t) {
                publishProgress(listener, ProgressEventType.TRANSFER_FAILED_EVENT);
                throw failure(t);
            }
        } finally {
            cleanupDataSource(originalRequest, file, originalStream, input, log);
        }

        String contentMd5 = metadata.getContentMD5();
        if (md5DigestStream != null) {
            contentMd5 = Base64.encodeAsString(md5DigestStream.getMd5Digest());
        }

        final String etag = returnedMetadata.getETag();
        if (contentMd5 != null && !skipMd5CheckStrategy.skipClientSideValidationPerPutResponse(returnedMetadata)) {
            byte[] clientSideHash = BinaryUtils.fromBase64(contentMd5);
            byte[] serverSideHash = BinaryUtils.fromHex(etag);

            if (!Arrays.equals(clientSideHash, serverSideHash)) {
                publishProgress(listener, ProgressEventType.TRANSFER_FAILED_EVENT);
                throw new SdkClientException(
                    "Unable to verify integrity of data upload. Client calculated content hash (contentMD5: " + contentMd5
                    + " in base 64) didn't match hash (etag: " + etag + " in hex) calculated by Amazon S3.  "
                    + "You may need to delete the data stored in Amazon S3. (metadata.contentMD5: " + metadata.getContentMD5()
                    + ", md5DigestStream: " + md5DigestStream
                    + uploadStrategy.md5ValidationErrorSuffix()
                    + ")");
            }
        }

        publishProgress(listener, ProgressEventType.TRANSFER_COMPLETED_EVENT);

        return uploadStrategy.createResult(returnedMetadata, contentMd5);
    }
476143
function upload (options, callback) {
  const promise = (
    Promise.resolve(options)
      .then(applyDefaults)
      .then(validateOptions)
      .then(opts => {
        options = opts
        return options
      })
      .then(transformOptions)
      .then(prepareRequest)
      .then(sendRequest)
      .catch(err => {
        return cleanupTempFiles(options)
          .then(() => Promise.reject(err))
      })
      .then(cleanupTempFiles)
  )
  if (callback) {
    promise
      .then(message => callback(null, message))
      .catch(err => callback(err, null))
  }
  return promise
}
97987
def perform(self):
        """"""

        if self._file_size < self._SINGLE_UPLOAD_MAX:
            resource = "{0}{1}".format(self._DEFAULT_RESOURCE, self.bucket)
            response = self.__upload(resource, open(self._file_path, 'rb').read())
            return response.headers['location']
        else:
            response = self.__init_chunked_upload()
            min_chunk_size = int(response.headers['x-ton-min-chunk-size'])
            chunk_size = min_chunk_size * self._DEFAULT_CHUNK_SIZE
            location = response.headers['location']

            f = open(self._file_path, 'rb')
            bytes_read = 0
            while True:
                bytes = f.read(chunk_size)
                if not bytes:
                    break
                bytes_start = bytes_read
                bytes_read += len(bytes)
                response = self.__upload_chunk(location, chunk_size, bytes, bytes_start, bytes_read)
                response_time = int(response.headers['x-response-time'])
                chunk_size = min_chunk_size * size(self._DEFAULT_CHUNK_SIZE,
                                                   self._RESPONSE_TIME_MAX,
                                                   response_time)
            f.close()

            return location.split("?")[0]
1323164
@PreAuthorize("isAuthenticated()")
    public E uploadFile(MultipartFile file) throws Exception {

        if (file == null) {
            final String errMsg = "Upload failed. File is null.";
            LOG.error(errMsg);
            throw new Exception(errMsg);
        } else if (file.isEmpty()) {
            final String errMsg = "Upload failed. File is empty.";
            LOG.error(errMsg);
            throw new Exception(errMsg);
        }

        InputStream is = null;
        byte[] fileByteArray = null;
        E fileToPersist = getEntityClass().newInstance();

        try {
            is = file.getInputStream();
            fileByteArray = IOUtils.toByteArray(is);
        } catch (Exception e) {
            throw new Exception("Could not create the bytearray: " + e.getMessage());
        } finally {
            IOUtils.closeQuietly(is);
        }

        fileToPersist.setFile(fileByteArray);
        fileToPersist.setFileType(file.getContentType());
        fileToPersist.setFileName(file.getOriginalFilename());

        dao.saveOrUpdate(fileToPersist);

        return fileToPersist;
    }
870951
def _upload_resumable_unit(self, uu_info):
        

        # Get actual unit size
        unit_size = uu_info.fd.len

        if uu_info.hash_ is None:
            raise ValueError('UploadUnitInfo.hash_ is now required')

        return self._api.upload_resumable(
            uu_info.fd,
            uu_info.upload_info.size,
            uu_info.upload_info.hash_info.file,
            uu_info.hash_,
            uu_info.uid,
            unit_size,
            filedrop_key=uu_info.upload_info.filedrop_key,
            folder_key=uu_info.upload_info.folder_key,
            path=uu_info.upload_info.path,
            action_on_duplicate=uu_info.upload_info.action_on_duplicate)
918841
def RetryOnUnavailable(func):
  """"""

  @functools.wraps(func)
  def Wrapper(*args, **kwargs):
    while True:
      try:
        response = func(*args, **kwargs)
      except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
        time.sleep(5)
        if (isinstance(e, urlerror.HTTPError)
            and e.getcode() == httpclient.SERVICE_UNAVAILABLE):
          continue
        elif isinstance(e, socket.timeout):
          continue
        raise
      else:
        if response.getcode() == httpclient.OK:
          return response
        else:
          raise StatusException(response)
  return Wrapper
209840
function(callback) {
            if (resumeEnabled) {
                qq.each(localStorage, function(key, item) {
                    if (key.indexOf(qq.format("qq{}resume", namespace)) === 0) {
                        var uploadData = JSON.parse(item);
                        callback(key, uploadData);
                    }
                });
            }
        }
1069143
def put(self, tpart):
        
        if self.closed:
            raise UserCritical(msg='attempt to upload tar after closing',
                               hint='report a bug')

        while True:
            too_many = (
                self.concurrency_burden + 1 > self.max_concurrency
                or self.member_burden + len(tpart) > self.max_members
            )

            if too_many:
                # If there are not enough resources to start an upload
                # even with zero uploads in progress, then something
                # has gone wrong: the user should not be given enough
                # rope to hang themselves in this way.
                if self.concurrency_burden == 0:
                    raise UserCritical(
                        msg=('not enough resources in pool to '
                             'support an upload'),
                        hint='report a bug')

                # _wait blocks until an upload finishes and clears its
                # used resources, after which another attempt to
                # evaluate scheduling resources for another upload
                # might be worth evaluating.
                #
                # Alternatively, an error was encountered in a
                # previous upload in which case it'll be raised here
                # and cause the process to regard the upload as a
                # failure.
                self._wait()
                gc.collect()
            else:
                # Enough resources available: commence upload
                self._start(tpart)
                return
961236
def _attempt_resumable_download(self, key, fp, headers, cb, num_cb,
                                    torrent, version_id):
        
        cur_file_size = get_cur_file_size(fp, position_to_eof=True)

        if (cur_file_size and 
            self.etag_value_for_current_download and
            self.etag_value_for_current_download == key.etag.strip('"\'')):
            # Try to resume existing transfer.
            if cur_file_size > key.size:
              raise ResumableDownloadException(
                  '%s is larger (%d) than %s (%d).\nDeleting tracker file, so '
                  'if you re-try this download it will start from scratch' %
                  (fp.name, cur_file_size, str(storage_uri_for_key(key)),
                   key.size), ResumableTransferDisposition.ABORT)
            elif cur_file_size == key.size:
                if key.bucket.connection.debug >= 1:
                    print 'Download complete.'
                return
            if key.bucket.connection.debug >= 1:
                print 'Resuming download.'
            headers = headers.copy()
            headers['Range'] = 'bytes=%d-%d' % (cur_file_size, key.size - 1)
            cb = ByteTranslatingCallbackHandler(cb, cur_file_size).call
            self.download_start_point = cur_file_size
        else:
            if key.bucket.connection.debug >= 1:
                print 'Starting new resumable download.'
            self._save_tracker_info(key)
            self.download_start_point = 0
            # Truncate the file, in case a new resumable download is being
            # started atop an existing file.
            fp.truncate(0)

        # Disable AWSAuthConnection-level retry behavior, since that would
        # cause downloads to restart from scratch.
        key.get_file(fp, headers, cb, num_cb, torrent, version_id,
                     override_num_retries=0)
        fp.flush()