Kernel::httpIO

Runs http input/output services.
546531
private function httpIO()
    {
        $services = [
            'Http\Message\ServerRequest' => 'serverRequest',
            'Http\Input'                 => 'input',
            'Http\Output'                => 'output',
        ];

        foreach ($services as $className => $classOffset) {
            $this->services->load($className, $classOffset);
        }
    }
861493
private static PumpStreamHandler redirectOutputAlsoTo(PumpStreamHandler pumps, OutputStream output) {
    if (output == null)
      throw new IllegalArgumentException("OutputStream must be provided.");
    OutputStream current = pumps.getOut();
    if (current != null && !(current instanceof NullOutputStream)) {
      output = new TeeOutputStream(current, output);
    }
    return new PumpStreamHandler(output, pumps.getErr(), pumps.getInput());
  }
1224359
final public function run()
    {
        \Devil::registerApplication($this);
        if ($moduleID = $this->url->isModuleRequested()) {
            if ($module = $this->loadModule($moduleID)) {
                if ($module->beforeRun()) {
                    $this->url->useModule($moduleID);
                    $module->run();
                    $module->afterRun();
                } else {
                    $module->errorRun();
                }
            } else {
                throw new HttpException(HttpException::NOT_FOUND);
            }
        } else {
           parent::run();
        }
    }
729705
private function initHttp()
    {
        $this->di->mapService('core.http', '\Core\Http\Http', [
            'core.http.cookie',
            'core.http.header'
        ]);
        $this->di->mapService('core.http.cookie', '\Core\Http\Cookie\CookieHandler');
        $this->di->mapService('core.http.header', '\Core\Http\Header\HeaderHandler');

        $this->http = $this->di->get('core.http');
    }
450145
protected /*HttpBuilder*/void streamOut(InputStream in) {
//        StreamResponse resp = new StreamResponse(context, in);
//        context.setControllerResponse(resp);
//        return new HttpBuilder(resp);
        //TODO finish and TEST the god damn method
        //------------------
        Result r = ResultBuilder.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .renderable(in);
//        context.setControllerResponse(r);
        result = r;
    }
1320252
private function cliIO()
    {
        $services = [
            'Cli\Input'  => 'input',
            'Cli\Output' => 'output',
        ];

        foreach ($services as $className => $classOffset) {
            $this->services->load($className, $classOffset);
        }
    }
812991
def main(request, query, hproPk=None, returnMenuOnly=False):
    
    if settings.PIAPI_STANDALONE:
        global plugIt, baseURI

        # Check if settings are ok
        if settings.PIAPI_ORGAMODE and settings.PIAPI_REALUSERS:
            return gen404(request, baseURI,
                          "Configuration error. PIAPI_ORGAMODE and PIAPI_REALUSERS both set to True !")

        hproject = None
    else:
        (plugIt, baseURI, hproject) = getPlugItObject(hproPk)
        hproject.update_last_access(request.user)

    # Check for SSL Requirements and redirect to ssl if necessary
    if hproject and hproject.plugItRequiresSsl:
        if not request.is_secure():
            secure_url = 'https://{0}{1}'.format(request.get_host(), request.get_full_path())
            return HttpResponsePermanentRedirect(secure_url)

    orgaMode = None
    currentOrga = None
    plugItMenuAction = None
    availableOrga = []

    # If standalone mode, change the current user and orga mode based on parameters
    if settings.PIAPI_STANDALONE:

        if not settings.PIAPI_REALUSERS:
            currentUserMode = request.session.get('plugit-standalone-usermode', 'ano')

            request.user = generate_user(mode=currentUserMode)

            orgaMode = settings.PIAPI_ORGAMODE

            currentOrga = SimpleOrga()
            currentOrga.name = request.session.get('plugit-standalone-organame', 'EBU')
            currentOrga.pk = request.session.get('plugit-standalone-orgapk', '-1')
            currentOrga.ebu_codops = request.session.get('plugit-standalone-orgacodops', 'zzebu')
        else:
            request.user.ebuio_member = request.user.is_staff
            request.user.ebuio_admin = request.user.is_superuser
            request.user.subscription_labels = _get_subscription_labels(request.user, hproject)

        proxyMode = settings.PIAPI_PROXYMODE
        plugItMenuAction = settings.PIAPI_PLUGITMENUACTION

        # TODO Add STANDALONE Orgas here
        # availableOrga.append((orga, isAdmin))

        # Get meta, if not in proxy mode
        if not proxyMode:

            try:
                meta = plugIt.getMeta(query)
            except Exception as e:
                report_backend_error(request, e, 'meta', hproPk)
                meta = None

            if not meta:
                return gen404(request, baseURI, 'meta')
        else:
            meta = {}

    else:
        request.user.ebuio_member = hproject.isMemberRead(request.user)
        request.user.ebuio_admin = hproject.isMemberWrite(request.user)
        request.user.subscription_labels = _get_subscription_labels(request.user, hproject)
        orgaMode = hproject.plugItOrgaMode
        proxyMode = hproject.plugItProxyMode
        plugItMenuAction = hproject.plugItMenuAction

        # Get meta, if not in proxy mode
        if not proxyMode:

            try:
                meta = plugIt.getMeta(query)
            except Exception as e:
                report_backend_error(request, e, 'meta', hproPk)
                meta = None

            if not meta:
                return gen404(request, baseURI, 'meta')
        else:
            meta = {}

        if orgaMode:
            # List available orgas
            if request.user.is_authenticated():
                # If orga limited only output the necessary orgas to which the user has access
                if hproject and hproject.plugItLimitOrgaJoinable:
                    # Get List of Plugit Available Orgas first
                    projectOrgaIds = hproject.plugItOrgaJoinable.order_by('name').values_list('pk', flat=True)
                    for (orga, isAdmin) in request.user.getOrgas(distinct=True):
                        if orga.pk in projectOrgaIds:
                            availableOrga.append((orga, isAdmin))

                else:
                    availableOrga = request.user.getOrgas(distinct=True)

            if not availableOrga:
                # TODO HERE TO CHANGE PUBLIC
                if not meta.get('public'):  # Page is not public, raise 403
                    return gen403(request, baseURI, 'no_orga_in_orgamode', hproject)
            else:
                # Build the current orga
                realCurrentOrga = get_current_orga(request, hproject, availableOrga)

                currentOrga = SimpleOrga()

                currentOrga.pk = realCurrentOrga.pk
                currentOrga.name = realCurrentOrga.name
                currentOrga.ebu_codops = realCurrentOrga.ebu_codops

                # Get rights
                request.user.ebuio_orga_member = realCurrentOrga.isMember(request.user)
                request.user.ebuio_orga_admin = realCurrentOrga.isOwner(request.user)

    cacheKey = get_cache_key(request, meta, orgaMode, currentOrga)

    # Check access rights
    error = check_rights_and_access(request, meta, hproject)

    if error:
        return error

    # Check cache
    (cache, menucache, context) = find_in_cache(cacheKey)

    if cache:
        return build_final_response(request, meta, cache, menucache, hproject, proxyMode, context)

    # Build parameters
    getParameters, postParameters, files = build_parameters(request, meta, orgaMode, currentOrga)

    # Bonus headers
    things_to_add = build_extra_headers(request, proxyMode, orgaMode, currentOrga)

    current_session = get_current_session(request, hproPk)

    # Do the action
    try:
        (data, session_to_set, headers_to_set) = plugIt.doAction(query, request.method, getParameters, postParameters, files, things_to_add, proxyMode=proxyMode, session=current_session)
    except Exception as e:
        report_backend_error(request, e, 'meta', hproPk)
        return gen500(request, baseURI)

    update_session(request, session_to_set, hproPk)

    # Handle special case (redirect, etc..)
    spe_cases = handle_special_cases(request, data, baseURI, meta)
    if spe_cases:

        for header, value in headers_to_set.items():
            spe_cases[header] = value

        return spe_cases

    # Save data for proxyMode
    if proxyMode:
        rendered_data = data
        data = {}
    else:
        rendered_data = None

    # Get template
    (templateContent, templateError) = get_template(request, query, meta, proxyMode)

    if templateError:
        return templateError

    # Build the context
    context = build_context(request, data, hproject, orgaMode, currentOrga, availableOrga)

    # Render the result
    menu = None  # Some page may not have a menu
    (result, menu) = render_data(context, templateContent, proxyMode, rendered_data, plugItMenuAction)

    # Cache the result for future uses if requested
    cache_if_needed(cacheKey, result, menu, context, meta)

    # Return menu only : )
    if returnMenuOnly:
        return menu

    # Return the final response
    final = build_final_response(request, meta, result, menu, hproject, proxyMode, context)

    for header, value in headers_to_set.items():
        final[header] = value

    return final
1034201
def run(): # pragma: no cover
    """"""
    out_file, out_format, arguments = parse()
    user, key = arguments.pop('user', None), arguments.pop('key', None)
    if not user or not key:
        sys.stderr.write('Credentials are required to perform API calls.\n')
        sys.exit(1)

    api = API(user, key, https=arguments.pop('https'), verify_ssl=arguments.pop('verify_ssl'),
              rate_limit=arguments.pop('rate_limit'))
    response = getattr(api, arguments.pop('api_call'))(**arguments)
    output = str(getattr(response, out_format) if out_format != 'list' else response.as_list())
    out_file.write(output if output.endswith('\n') else output + '\n')
24148
def _paload32(ins):
    ''' 
    '''
    output = _paddr(ins.quad[2])

    output.append('call __ILOAD32')
    output.append('push de')
    output.append('push hl')

    REQUIRES.add('iload32.asm')

    return output
815226
def api_handler(input_data, cloud, api, url_params=None, batch_size=None, **kwargs):
    
    url_params = url_params or {}
    input_data = standardize_input_data(input_data)

    cloud = cloud or config.cloud
    host = "%s.indico.domains" % cloud if cloud else config.host

    # LOCAL DEPLOYMENTS
    if not (host.endswith('indico.domains') or host.endswith('indico.io')):
        url_protocol = "http"
    else:
        url_protocol = config.url_protocol

    headers = dict(JSON_HEADERS)
    headers["X-ApiKey"] = url_params.get("api_key") or config.api_key
    url = create_url(url_protocol, host, api, dict(kwargs, **url_params))
    return collect_api_results(input_data, url, headers, api, batch_size, kwargs)
506105
def Run(self, args):
    """"""
    # Make sure we limit the size of our output
    if args.length > constants.CLIENT_MAX_BUFFER_SIZE:
      raise RuntimeError("Can not read buffers this large.")

    data = vfs.ReadVFS(args.pathspec, args.offset, args.length)

    digest = hashlib.sha256(data).digest()

    # Now report the hash of this blob to our flow as well as the offset and
    # length.
    self.SendReply(
        rdf_client.BufferReference(
            offset=args.offset, length=len(data), data=digest))
1018304
def execute(request_method, path, api_version, data, headers) # :nodoc:
      request.public_send(
        request_method,
        PagSeguro.api_url("#{api_version}/#{path}"),
        extended_data(data),
        extended_headers(request_method, headers)
      )
    end
772687
public void getToWrite(
                    final String url,
                    final Writer output,
                    final String... accept_media_types )
    {
        _execute( url, HttpMethod.GET,
                        new AcceptHeaderRequestCallback( accept_media_types ),
                        new WriterResponseExtractor( output ) );
    }
956134
public void getToWrite(
                    final String url,
                    final OutputStream output,
                    final String... accept_media_types
                    )
    {
        _execute( url, HttpMethod.GET,
                        new AcceptHeaderRequestCallback( accept_media_types ),
                        new OutputStreamResponseExtractor( output ) );
    }
881603
def perform
      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = true
      http.ssl_timeout = @options[:ssl_timeout] unless @options[:ssl_timeout].nil?
      http.open_timeout = @options[:open_timeout] unless @options[:open_timeout].nil?
      http.read_timeout = @options[:read_timeout] unless @options[:read_timeout].nil?

      req = Net::HTTP::Post.new(uri.request_uri, headers)
      req.body = body
      resp = http.request(req)
      verify_response(resp)

      resp
    end
551649
function httpOk(req, res, content, fileExt) {
    res.writeHead(200, {
        'Content-Type': Mine.getType(fileExt),
    });
    res.write(content, 'binary');
    res.end();
}
752514
def _http_response(self, url, method, data=None, **kwargs):
        
        header = {'content-type': 'application/json'}

        if data:
            data = json.dumps(data)
        path = url.format(**kwargs)
        logger.debug("%s %s", method.__name__.upper(), path)
        response = method(self.host + path,
                          data=data, headers=header, **self.method_kwargs)
        logger.debug("%s %s", response.status_code, response.reason)
        response.raise_for_status()

        return response