Setup the reponse output stream.
Use the current state of the request and response, to set tranfer
parameters such as chunking and content length.
355405
protected void firstWrite()
        throws IOException
    {
        if (_response.isCommitted())
            return;
        
        // Nobble the OutputStream for HEAD requests
        if (HttpRequest.__HEAD.equals(_request.getMethod()))
            _outputStream.nullOutput();    
            
        int length=_response.getIntField(HttpFields.__ContentLength);
        if (length>=0)
            _outputStream.setContentLength(length);
    }
293248
public void resource(InputStream input) {
        checkCommitted();
        finalizeResponse();

        // content type to OCTET_STREAM if it's not set
        if (getContentType() == null) {
            contentType(HttpConstants.ContentType.APPLICATION_OCTET_STREAM);
        }

        try {
            send(input);
        } catch (IOException e) {
            throw new PippoRuntimeException(e);
        }
    }
932843
function(input, chainLink) {
        var output = this.getOutputIndex(
            chainLink.process.description.processOutputs, chainLink.output
        );
        input.reference.mimeType = this.findMimeType(
            input.complexData.supported.formats,
            chainLink.process.description.processOutputs[output].complexOutput.supported.formats
        );
        var formats = {};
        formats[input.reference.mimeType] = true;
        chainLink.process.setResponseForm({
            outputIndex: output,
            supportedFormats: formats
        });
        input.reference.body = chainLink.process.description;
        while (this.executeCallbacks.length > 0) {
            this.executeCallbacks[0]();
        }
    }
670950
def set_stream(self, stream):
        

        for handler in self.handlers[:]:
            if isinstance(handler, logging.StreamHandler):
                self.handlers.remove(handler)

        if stream is not None:
            stream_handler = logging.StreamHandler(stream)
            stream_handler.addFilter(_StreamHandlerEchoFilter())
            stream_handler.setFormatter(logging.Formatter('%(message)s'))
            self.addHandler(stream_handler)

        self.stream = stream
1189899
def rest_put_stream(self, url, stream, headers=None, session=None, verify=True, cert=None):
        
        res = session.put(url, headers=headers, data=stream, verify=verify, cert=cert)
        return res.text, res.status_code
218709
def _init_length(self, request_method):
        
        length = self.headers.get('content-length')

        if length is not None:
            if self.chunked:
                # This Response will fail with an IncompleteRead if it can't be
                # received as chunked. This method falls back to attempt reading
                # the response before raising an exception.
                log.warning("Received response with both Content-Length and "
                            "Transfer-Encoding set. This is expressly forbidden "
                            "by RFC 7230 sec 3.3.2. Ignoring Content-Length and "
                            "attempting to process response as Transfer-Encoding: "
                            "chunked.")
                return None

            try:
                # RFC 7230 section 3.3.2 specifies multiple content lengths can
                # be sent in a single Content-Length header
                # (e.g. Content-Length: 42, 42). This line ensures the values
                # are all valid ints and that as long as the `set` length is 1,
                # all values are the same. Otherwise, the header is invalid.
                lengths = set([int(val) for val in length.split(',')])
                if len(lengths) > 1:
                    raise InvalidHeader("Content-Length contained multiple "
                                        "unmatching values (%s)" % length)
                length = lengths.pop()
            except ValueError:
                length = None
            else:
                if length < 0:
                    length = None

        # Convert status to int for comparison
        # In some cases, httplib returns a status of "_UNKNOWN"
        try:
            status = int(self.status)
        except ValueError:
            status = 0

        # Check for responses that shouldn't include a body
        if status in (204, 304) or 100 <= status < 200 or request_method == 'HEAD':
            length = 0

        return length
34931
def build_response(
        self, request, response, from_cache=False, cacheable_methods=None
    ):
        
        cacheable = cacheable_methods or self.cacheable_methods
        if not from_cache and request.method in cacheable:
            # Check for any heuristics that might update headers
            # before trying to cache.
            if self.heuristic:
                response = self.heuristic.apply(response)

            # apply any expiration heuristics
            if response.status == 304:
                # We must have sent an ETag request. This could mean
                # that we've been expired already or that we simply
                # have an etag. In either case, we want to try and
                # update the cache if that is the case.
                cached_response = self.controller.update_cached_response(
                    request, response
                )

                if cached_response is not response:
                    from_cache = True

                # We are done with the server response, read a
                # possible response body (compliant servers will
                # not return one, but we cannot be 100% sure) and
                # release the connection back to the pool.
                response.read(decode_content=False)
                response.release_conn()

                response = cached_response

            # We always cache the 301 responses
            elif response.status == 301:
                self.controller.cache_response(request, response)
            else:
                # Wrap the response file with a wrapper that will cache the
                #   response when the stream has been consumed.
                response._fp = CallbackFileWrapper(
                    response._fp,
                    functools.partial(
                        self.controller.cache_response, request, response
                    ),
                )
                if response.chunked:
                    super_update_chunk_length = response._update_chunk_length

                    def _update_chunk_length(self):
                        super_update_chunk_length()
                        if self.chunk_left == 0:
                            self._fp._close()

                    response._update_chunk_length = types.MethodType(
                        _update_chunk_length, response
                    )

        resp = super(CacheControlAdapter, self).build_response(request, response)

        # See if we should invalidate the cache.
        if request.method in self.invalidating_methods and resp.ok:
            cache_url = self.controller.cache_url(request.url)
            self.cache.delete(cache_url)

        # Give the request a from_cache attr to let people use it
        resp.from_cache = from_cache

        return resp
587257
private void setupInputStream() throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    // set timeout for connecting and reading
    connection.setConnectTimeout(httpTimeout);
    connection.setReadTimeout(httpTimeout);

    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
      throw new IOException("Fetch of " + url + " failed with status code "
          + connection.getResponseCode() + "\nResponse message:\n"
          + connection.getResponseMessage());
    }

    String contentLength = connection
        .getHeaderField(TransferFsImage.CONTENT_LENGTH);
    if (contentLength != null) {
      // store image size
      advertisedSize = Long.parseLong(contentLength);
      if (advertisedSize <= 0) {
        throw new IOException("Invalid " + TransferFsImage.CONTENT_LENGTH
            + " header: " + contentLength);
      }
    } else {
      throw new IOException(TransferFsImage.CONTENT_LENGTH
          + " header is not provided " + "by the server when trying to fetch "
          + url);
    }

    // get the digest
    digest = TransferFsImage.parseMD5Header(connection);
    if (digest == null) {
      // digest must be provided, otherwise the image is not valid
      throw new IOException("Image digest not provided for url: " + url);
    }

    // get the input stream directly from the connection
    inputStream = connection.getInputStream();
    initialized = true;
  }
791469
private void fillOutputStream(OutputStream stream, int length)
			throws AsnException, IOException {
		byte[] dataBucket = new byte[DATA_BUCKET_SIZE];
		int readCount;

		while (length != 0) {
			int cnt = length < DATA_BUCKET_SIZE ? length : DATA_BUCKET_SIZE;
			readCount = read(dataBucket, 0, cnt);
			if (readCount < cnt)
				throw new AsnException("input stream has reached the end");
			stream.write(dataBucket, 0, readCount);
			length -= readCount;
		}
	}
1020405
private void initStreamOutput() throws SAXException
    {

        // Try to rule out if this is an not to be an HTML document based on prefix
        boolean firstElementIsHTML = isFirstElemHTML();

        if (firstElementIsHTML)
        {
            // create an HTML output handler, and initialize it

            // keep a reference to the old handler, ... it will soon be gone
            SerializationHandler oldHandler = m_handler;

            /* We have to make sure we get an output properties with the proper
             * defaults for the HTML method.  The easiest way to do this is to
             * have the OutputProperties class do it.
             */

            Properties htmlProperties =
                OutputPropertiesFactory.getDefaultMethodProperties(Method.HTML);
            Serializer serializer =
                SerializerFactory.getSerializer(htmlProperties);

            // The factory should be returning a ToStream
            // Don't know what to do if it doesn't
            // i.e. the user has over-ridden the content-handler property
            // for html
            m_handler = (SerializationHandler) serializer;
            //m_handler = new ToHTMLStream();

            Writer writer = oldHandler.getWriter();

            if (null != writer)
                m_handler.setWriter(writer);
            else
            {
                OutputStream os = oldHandler.getOutputStream();

                if (null != os)
                    m_handler.setOutputStream(os);
            }

            // need to copy things from the old handler to the new one here

            //            if (_setVersion_called)
            //            {
            m_handler.setVersion(oldHandler.getVersion());
            //            }
            //            if (_setDoctypeSystem_called)
            //            {
            m_handler.setDoctypeSystem(oldHandler.getDoctypeSystem());
            //            }
            //            if (_setDoctypePublic_called)
            //            {
            m_handler.setDoctypePublic(oldHandler.getDoctypePublic());
            //            }
            //            if (_setMediaType_called)
            //            {
            m_handler.setMediaType(oldHandler.getMediaType());
            //            }
            
            m_handler.setTransformer(oldHandler.getTransformer());
        }

        /* Now that we have a real wrapped handler (XML or HTML) lets
         * pass any cached calls to it
         */
        // Call startDocument() if necessary
        if (m_needToCallStartDocument)
        {
            m_handler.startDocument();
            m_needToCallStartDocument = false;
        }

        // the wrapped handler is now fully initialized
        m_wrapped_handler_not_initialized = false;
    }
257617
public void setOutput(OutputStream stream, String encoding)
    throws UnsupportedEncodingException {
        
        if (encoding == null) {
            encoding = "UTF8";
        }
        
        java.io.Writer writer = new OutputStreamWriter(stream, encoding);
        fOut = new PrintWriter(writer);
        
    }
604260
def __SendChunk(self, start, additional_headers=None):
        """"""
        self.EnsureInitialized()
        no_log_body = self.total_size is None
        request = http_wrapper.Request(url=self.url, http_method='PUT')
        if self.__gzip_encoded:
            request.headers['Content-Encoding'] = 'gzip'
            body_stream, read_length, exhausted = compression.CompressStream(
                self.stream, self.chunksize)
            end = start + read_length
            # If the stream length was previously unknown and the input stream
            # is exhausted, then we're at the end of the stream.
            if self.total_size is None and exhausted:
                self.__total_size = end
        elif self.total_size is None:
            # For the streaming resumable case, we need to detect when
            # we're at the end of the stream.
            body_stream = buffered_stream.BufferedStream(
                self.stream, start, self.chunksize)
            end = body_stream.stream_end_position
            if body_stream.stream_exhausted:
                self.__total_size = end
            # TODO: Here, change body_stream from a stream to a string object,
            # which means reading a chunk into memory.  This works around
            # https://code.google.com/p/httplib2/issues/detail?id=176 which can
            # cause httplib2 to skip bytes on 401's for file objects.
            # Rework this solution to be more general.
            body_stream = body_stream.read(self.chunksize)
        else:
            end = min(start + self.chunksize, self.total_size)
            body_stream = stream_slice.StreamSlice(self.stream, end - start)
        # TODO(craigcitro): Think about clearer errors on "no data in
        # stream".
        request.body = body_stream
        request.headers['Content-Type'] = self.mime_type
        if no_log_body:
            # Disable logging of streaming body.
            # TODO: Remove no_log_body and rework as part of a larger logs
            # refactor.
            request.loggable_body = '<media body>'
        if self.total_size is None:
            # Streaming resumable upload case, unknown total size.
            range_string = 'bytes %s-%s/*' % (start, end - 1)
        elif end == start:
            # End of an upload with 0 bytes left to send; just finalize.
            range_string = 'bytes */%s' % self.total_size
        else:
            # Normal resumable upload case with known sizes.
            range_string = 'bytes %s-%s/%s' % (start, end - 1, self.total_size)

        request.headers['Content-Range'] = range_string
        if additional_headers:
            request.headers.update(additional_headers)

        return self.__SendMediaRequest(request, end)
804007
public synchronized void upload(StaplerRequest req, StaplerResponse rsp) throws InterruptedException, IOException {
        rsp.setStatus(HttpServletResponse.SC_OK);
        InputStream in = req.getInputStream();
        if (DIY_CHUNKING) {
            in = new ChunkedInputStream(in);
        }

        // publish the upload channel
        upload = in;
        LOGGER.log(Level.FINE, "Recording upload stream {0} for {1}: {2}", new Object[] {upload, uuid, this});
        notify();

        // wait until we are done
        while (!completed) {
            wait();
        }
    }
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); });
}
37293
protected void setupPathedInputStream() throws IOException
   {
      InputStream curIn = getBaseResource().openStream();

      for (int i = 0; i < this.segments.length; ++i)
      {
         curIn = getSegmentInputStream(curIn, segments[i]);
      }

      this.in = curIn;
   }
999271
async def _put_chunk(
            cls, session: aiohttp.ClientSession,
            upload_uri: str, buf: bytes):
        """"""
        # Build the correct headers.
        headers = {
            'Content-Type': 'application/octet-stream',
            'Content-Length': '%s' % len(buf),
        }
        credentials = cls._handler.session.credentials
        if credentials is not None:
            utils.sign(upload_uri, headers, credentials)

        # Perform upload of chunk.
        async with await session.put(
                upload_uri, data=buf, headers=headers) as response:
            if response.status != 200:
                content = await response.read()
                request = {
                    "body": buf,
                    "headers": headers,
                    "method": "PUT",
                    "uri": upload_uri,
                }
                raise CallError(request, response, content, None)
106734
def handle(self,
               t_input: inference.TranslatorInput,
               t_output: inference.TranslatorOutput,
               t_walltime: float = 0.):
        
        self.stream.write("%s\n" % t_output.translation)
        self.stream.flush()