/* Abstract base class for ServerRequest and ClientResponse.
14718
function IncomingMessage(socket) {
  stream.Stream.call(this);

  // TODO Remove one of these eventually.
  this.socket = socket;
  this.connection = socket;

  this.httpVersion = null;
  this.complete = false;
  this.headers = {};
  this.trailers = {};

  this.readable = true;

  this._paused = false;
  this._pendings = [];

  this._endEmitted = false;

  // request (server) only
  this.url = '';

  this.method = null;

  // response (client) only
  this.statusCode = null;
  this.client = this.socket;
}
416305
function ServerClientStream(app){
    var StreamHandler;
    app.use(function(req, res, next){
      if(req.originalUrl == '/promise-pipe-connector' && req.method=='POST'){
        var message = req.body;
        message._response = res;
        StreamHandler(message)
      } else {
        return next();
      }
    });
    return {
      send: function(message){
        if(!message._response) throw Error("no response defined");
        var res = message._response;
        message._response = undefined;
        res.json(message);
      },
      listen: function(handler){
        StreamHandler = handler;
      }
    }
  }
1233361
function(client, msg, serverType, serverId, cb) {
  if (typeof serverId !== 'string') {
    logger.error('[omelo-rpc] serverId is not a string : %s', serverId);
    return;
  }
  if (serverId === '*') {
    let servers = client._routeContext.getServersByType(serverType);
    if (!servers) {
      logger.error('[omelo-rpc] serverType %s servers not exist', serverType);
      return;
    }

    async.each(servers, function(server, next) {
      let serverId = server['id'];
      client.rpcInvoke(serverId, msg, function(err) {
        next(err);
      });
    }, cb);
  } else {
    client.rpcInvoke(serverId, msg, cb);
  }
}
1239406
@EachBean(ServiceHttpClientConfiguration.class)
    @Requires(condition = ServiceHttpClientCondition.class)
    DefaultHttpClient serviceHttpClient(
            @Parameter ServiceHttpClientConfiguration configuration,
            @Parameter StaticServiceInstanceList instanceList) {
        List<URI> originalURLs = configuration.getUrls();
        Collection<URI> loadBalancedURIs = instanceList.getLoadBalancedURIs();
        boolean isHealthCheck = configuration.isHealthCheck();

        LoadBalancer loadBalancer = loadBalancerFactory.create(instanceList);

        Optional<String> path = configuration.getPath();
        DefaultHttpClient httpClient;
        if (path.isPresent()) {
            httpClient = beanContext.createBean(DefaultHttpClient.class, loadBalancer, configuration, path.get());
        } else {
            httpClient = beanContext.createBean(DefaultHttpClient.class, loadBalancer, configuration);
        }

        httpClient.setClientIdentifiers(configuration.getServiceId());

        if (isHealthCheck) {
            taskScheduler.scheduleWithFixedDelay(configuration.getHealthCheckInterval(), configuration.getHealthCheckInterval(), () -> Flowable.fromIterable(originalURLs).flatMap(originalURI -> {
                URI healthCheckURI = originalURI.resolve(configuration.getHealthCheckUri());
                return httpClient.exchange(HttpRequest.GET(healthCheckURI)).onErrorResumeNext(throwable -> {
                    if (throwable instanceof HttpClientResponseException) {
                        HttpClientResponseException responseException = (HttpClientResponseException) throwable;
                        HttpResponse response = responseException.getResponse();
                        //noinspection unchecked
                        return Flowable.just(response);
                    }
                    return Flowable.just(HttpResponse.serverError());
                }).map(response -> Collections.singletonMap(originalURI, response.getStatus()));
            }).subscribe(uriToStatusMap -> {
                Map.Entry<URI, HttpStatus> entry = uriToStatusMap.entrySet().iterator().next();

                URI uri = entry.getKey();
                HttpStatus status = entry.getValue();

                if (status.getCode() >= 300) {
                    loadBalancedURIs.remove(uri);
                } else if (!loadBalancedURIs.contains(uri)) {
                    loadBalancedURIs.add(uri);
                }
            }));
        }
        return httpClient;
    }
870032
def create_rest_client_class(name, apis, BaseClass=RestClient):
    

    apis_with_actions = list(itertools.chain.from_iterable([ zip([api] * len(api.actions), api.actions) for api in apis]))

    api_funcs = [create_api_call_func(api, verb) for api, verb in apis_with_actions]
    api_funcs.extend([create_async_api_call_func(api, verb) for api, verb in apis_with_actions])
    api_mapper = dict([ (f.__name__, f) for f in api_funcs ])

    # Adapted from :
    # http://stackoverflow.com/questions/15247075/how-can-i-dynamically-create-derived-classes-from-a-base-class
    def __init__(self, thread_count=_ASYNC_WORKER_THREAD_COUNT, **reqargs):
        BaseClass.__init__(self)
        setattr(self, 'reqargs', read_only_dict(reqargs))
        self._executor = concurrent.futures.ThreadPoolExecutor(thread_count)

    api_mapper['__init__'] =  __init__

    ClientClass = type(_CLIENT_NAME_FMT.format(name), (BaseClass,), api_mapper)
    return ClientClass
22190
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $middlewares = $this->module_service->findByInterface(MiddlewareInterface::class);

        $pipeline = $handler;

        foreach ($middlewares as $middleware) {
            $pipeline = new class($pipeline, $middleware) implements RequestHandlerInterface {
                /** @var RequestHandlerInterface */
                private $handler;

                /** @var MiddlewareInterface */
                private $middleware;

                public function __construct(RequestHandlerInterface $handler, MiddlewareInterface $middleware)
                {
                    $this->handler    = $handler;
                    $this->middleware = $middleware;
                }

                public function handle(ServerRequestInterface $request): ResponseInterface
                {
                    return $this->middleware->process($request, $this->handler);
                }
            };
        }

        return $pipeline->handle($request);
    }
1004911
public static <T> ServiceFuture<T> fromResponse(final Observable<ServiceResponse<T>> observable, final ServiceCallback<T> callback) {
        final ServiceFuture<T> serviceFuture = new ServiceFuture<>();
        serviceFuture.subscription = observable
                .last()
                .subscribe(new Action1<ServiceResponse<T>>() {
                    @Override
                    public void call(ServiceResponse<T> t) {
                        if (callback != null) {
                            callback.success(t.body());
                        }
                        serviceFuture.set(t.body());
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        if (callback != null) {
                            callback.failure(throwable);
                        }
                        serviceFuture.setException(throwable);
                    }
                });
        return serviceFuture;
    }
403621
function createAbstractClass(params, constructor) {
        if (!isObject(params)) {
            throw new Error('Expected abstract class definition to be an object with the abstract class members.');
        }
        // Validate class name
        if (hasOwn(params, '$name')) {
            if (!isString(params.$name)) {
                throw new Error('Abstract class name must be a string.');
            } else if (/\s+/.test(params.$name)) {
                throw new Error('Abstract class name cannot have spaces.');
            }
        } else {
            params.$name = 'Unnamed';
        }

        var def,
            abstractObj = { methods: {}, staticMethods: {}, unimplemented: 0 },
            saved = {},
            key;

        // If we are extending an abstract class also, inherit the abstract methods
        if (isFunction(params.$extends)) {
            if (params.$extends[$abstract]) {
                mixIn(abstractObj.methods, params.$extends[$abstract].methods);
                mixIn(abstractObj.staticMethods, params.$extends[$abstract].staticMethods);
            }
        }

        // Handle abstract methods
        if (hasOwn(params, '$abstracts')) {
            saved.$abstracts = params.$abstracts;     // Save them for later use
        }

        // Handle interfaces
        if (hasOwn(params, '$implements')) {
            saved.$interfaces = params.$implements;   // Save them for later use
        }

        // Create the class definition
        def = Class.$create(params, constructor, { isAbstract: true });

        abstractObj.check = bind(checkClass, def);

        if (hasDefineProperty) {
            Object.defineProperty(def, $abstract, {
                value: abstractObj,
                writable: false
            });
        } else {
            def[$abstract] = abstractObj;
        }

        // Parse the saved interfaces
        if (hasOwn(saved, '$interfaces')) {
            parseInterfaces(saved.$interfaces, def);
        }

        // Parse the abstract methods
        if (hasOwn(saved, '$abstracts')) {
            parseAbstracts(saved.$abstracts, def);
        }

        // Finally update the unimplemented count
        for (key in def[$abstract].methods) {
            if (!def[$class].methods[key]) {
                abstractObj.unimplemented += 1;
            }
        }
        for (key in def[$abstract].staticMethods) {
            if (!def[$class].staticMethods[key]) {
                abstractObj.unimplemented += 1;
            }
        }

        return def;
    }
608509
private ClientResponseImpl coreCall(Object... paramListIn) {
        VoltTable[] results = null;

        // use local var to avoid warnings about reassigning method argument
        Object[] paramList = paramListIn;

        try {
            if ((m_paramTypes.length > 0) && (m_paramTypes[0] == ParameterSet.class)) {
                assert(m_paramTypes.length == 1);
                paramList = new Object[] { ParameterSet.fromArrayNoCopy(paramListIn) };
            }

            if (paramList.length != m_paramTypes.length) {
                String msg = "PROCEDURE " + m_procedureName + " EXPECTS " + String.valueOf(m_paramTypes.length) +
                    " PARAMS, BUT RECEIVED " + String.valueOf(paramList.length);
                m_statusCode = ClientResponse.GRACEFUL_FAILURE;
                return ProcedureRunner.getErrorResponse(m_statusCode, m_appStatusCode, m_appStatusString, msg, null);
            }

            for (int i = 0; i < m_paramTypes.length; i++) {
                try {
                    paramList[i] = ParameterConverter.tryToMakeCompatible(m_paramTypes[i], paramList[i]);
                    // check the result type in an assert
                    assert(ParameterConverter.verifyParameterConversion(paramList[i], m_paramTypes[i]));
                } catch (Exception e) {
                    String msg = "PROCEDURE " + m_procedureName + " TYPE ERROR FOR PARAMETER " + i +
                            ": " + e.toString();
                    m_statusCode = ClientResponse.GRACEFUL_FAILURE;
                    return ProcedureRunner.getErrorResponse(m_statusCode, m_appStatusCode, m_appStatusString, msg, null);
                }
            }

            try {
                m_procedure.m_runner = this;
                Object rawResult = m_procMethod.invoke(m_procedure, paramList);

                if (rawResult instanceof CompletableFuture<?>) {
                    final CompletableFuture<?> fut = (CompletableFuture<?>) rawResult;

                    fut.thenRun(() -> {
                        //
                        // Happy path. No exceptions thrown. Procedure work is complete.
                        //
                        Object innerRawResult = null;
                        ClientResponseImpl response = null;
                        try {
                            innerRawResult = fut.get();
                        } catch (InterruptedException | ExecutionException e) {
                            assert(false);
                            // this is a bad place to be, but it's hard to know if it's crash bad...
                            innerRawResult = new ClientResponseImpl(ClientResponseImpl.UNEXPECTED_FAILURE,
                                    new VoltTable[0],
                                    "Future returned from NTProc " + m_procedureName + " failed to complete.",
                                    m_clientHandle);
                        }

                        if (innerRawResult instanceof ClientResponseImpl) {
                            response = (ClientResponseImpl) innerRawResult;
                        }
                        else {
                            try {
                                VoltTable[] r = ParameterConverter.getResultsFromRawResults(m_procedureName, innerRawResult);
                                response = responseFromTableArray(r);
                            } catch (Exception e) {
                                // this is a bad place to be, but it's hard to know if it's crash bad...
                                response = new ClientResponseImpl(ClientResponseImpl.GRACEFUL_FAILURE,
                                        new VoltTable[0],
                                        "Type " + innerRawResult.getClass().getName() +
                                            " returned from NTProc \"" + m_procedureName +
                                            "\" was not an acceptible VoltDB return type.",
                                        m_clientHandle);
                            }
                        }

                        completeCall(response);
                    })
                    .exceptionally(e -> {
                        //
                        // Exception path. Some bit of async work threw something.
                        //
                        SerializableException se = null;
                        if (e instanceof SerializableException) {
                            se = (SerializableException) e;
                        }

                        String msg = "PROCEDURE " + m_procedureName + " THREW EXCEPTION: ";
                        if (se != null) {
                            msg += se.getMessage();
                        } else {
                            msg += e.toString();
                        }
                        m_statusCode = ClientResponse.GRACEFUL_FAILURE;
                        completeCall(ProcedureRunner.getErrorResponse(m_statusCode, m_appStatusCode, m_appStatusString, msg, se));
                        return null;
                    });

                    return null;
                }
                results = ParameterConverter.getResultsFromRawResults(m_procedureName, rawResult);
            }
            catch (IllegalAccessException e) {
                // If reflection fails, invoke the same error handling that other exceptions do
                throw new InvocationTargetException(e);
            }
        }
        catch (InvocationTargetException itex) {
            //itex.printStackTrace();
            Throwable ex = itex.getCause();
            if (CoreUtils.isStoredProcThrowableFatalToServer(ex)) {
                // If the stored procedure attempted to do something other than linklibrary or instantiate
                // a missing object that results in an error, throw the error and let the server deal with
                // the condition as best as it can (usually a crashLocalVoltDB).
                throw (Error)ex;
            }
            return ProcedureRunner.getErrorResponse(m_procedureName,
                                                    true,
                                                    0,
                                                    m_appStatusCode,
                                                    m_appStatusString,
                                                    null,
                                                    ex);
        }

        return responseFromTableArray(results);
    }
158666
function(class_data) {

		var skeleton = class_data.skeleton,
			name,
			serialized_value,
			serialized_actions = [],
			is_polymorphic = !class_data.is_monomorphic;

		for (name in skeleton) {

			switch (skeleton[name].type) {
				case this.MEMBER_TYPES.REGEXP:
				case this.MEMBER_TYPES.FUNCTION:
					serialized_value = 'r[' + skeleton[name].index + ']';
					break;
				//case 'undefined':
				case this.MEMBER_TYPES.STRING:
					if (is_polymorphic) {
						serialized_value = '"' + skeleton[name].value.replace(/\"/g, "\\\"") + '"';
					}
					break;
				case this.MEMBER_TYPES.PRIMITIVE: // null, boolean, number
					if (is_polymorphic) {
						serialized_value = skeleton[name].value + '';
					}
					break;
			}

			if (serialized_value) {

				if (Lava.VALID_PROPERTY_NAME_REGEX.test(name)) {

					serialized_actions.push('p.' + name + ' = ' + serialized_value + ';');

				} else {

					serialized_actions.push('p[' + Firestorm.String.quote(name) + '] = ' + serialized_value + ';');

				}

				serialized_value = null;

			}

		}

		for (name in class_data.shared) {

			serialized_actions.push('p.' + name + ' = s.' + name + ';');

		}

		return serialized_actions.length
			? new Function('cd,p', "\tvar r=cd.references,\n\t\ts=cd.shared;\n\n\t" + serialized_actions.join('\n\t') + "\n")
			: null;

	}
240825
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
	{
		[
			'Request-Type' => $type,
			'Response-Headers' => $headers,
		] = $this->analyze($request);

		switch ($type) {
			case self::ERROR_NO_HOST_HEADER:
			case self::ERROR_ORIGIN_NOT_ALLOWED:
			case self::ERROR_METHOD_NOT_SUPPORTED:
			case self::ERROR_HEADERS_NOT_SUPPORTED:
				return Factory::response(403);

			case self::TYPE_REQUEST_OUT_OF_CORS_SCOPE:
				return $handler->handle($request);

			case self::TYPE_PRE_FLIGHT_REQUEST:
				$response = Factory::response(200);

				return self::withCorsHeaders($response, $headers);

			default:
				$response = $handler->handle($request);

				return self::withCorsHeaders($response, $headers);
		}
	}
438811
private void createResponse() {
        response = new GenericAnalyticsResponse(
                queryErrorObservable.onBackpressureBuffer(),
                queryRowObservable.onBackpressureBuffer(),
                querySignatureObservable.onBackpressureBuffer(),
                queryStatusObservable.onBackpressureBuffer(),
                queryInfoObservable.onBackpressureBuffer(),
                handle,
                currentRequest,
                status,
                requestID,
                clientContextID
        );
    }
1116899
@Override
    protected BasicHttpProcessor createHttpProcessor() {
        BasicHttpProcessor httpproc = new BasicHttpProcessor();
        httpproc.addInterceptor(new RequestDefaultHeaders());
        // Required protocol interceptors
        httpproc.addInterceptor(new RequestContent(true));
        httpproc.addInterceptor(new RequestTargetHost());
        // Recommended protocol interceptors
        httpproc.addInterceptor(new RequestClientConnControl());
        httpproc.addInterceptor(new RequestUserAgent());
        httpproc.addInterceptor(new RequestExpectContinue());
        // HTTP state management interceptors
        httpproc.addInterceptor(new RequestAddCookies());
        httpproc.addInterceptor(new ResponseProcessCookies());
        // HTTP authentication interceptors
        httpproc.addInterceptor(new RequestAuthCache());
        httpproc.addInterceptor(new RequestTargetAuthentication());
        httpproc.addInterceptor(new RequestProxyAuthentication());
        return httpproc;
    }
1335538
public B annotatedService(String pathPrefix, Object service,
                              Function<Service<HttpRequest, HttpResponse>,
                                      ? extends Service<HttpRequest, HttpResponse>> decorator,
                              Iterable<?> exceptionHandlersAndConverters) {
        requireNonNull(pathPrefix, "pathPrefix");
        requireNonNull(service, "service");
        requireNonNull(decorator, "decorator");
        requireNonNull(exceptionHandlersAndConverters, "exceptionHandlersAndConverters");

        final List<AnnotatedHttpServiceElement> elements =
                AnnotatedHttpServiceFactory.find(pathPrefix, service, exceptionHandlersAndConverters);
        elements.forEach(e -> {
            Service<HttpRequest, HttpResponse> s = e.service();
            // Apply decorators which are specified in the service class.
            s = e.decorator().apply(s);
            // Apply decorators which are passed via annotatedService() methods.
            s = decorator.apply(s);

            // If there is a decorator, we should add one more decorator which handles an exception
            // raised from decorators.
            if (s != e.service()) {
                s = e.service().exceptionHandlingDecorator().apply(s);
            }
            service(e.pathMapping(), s);
        });
        return self();
    }
278594
@Override
	protected Class<?>[] getHandlerInterfaces(String serviceName) {
		Class<?> remoteInterface = interfaceMap.get(serviceName);
		if (remoteInterface != null) {
			return new Class<?>[]{remoteInterface};
		} else if (Proxy.isProxyClass(getHandler(serviceName).getClass())) {
			return getHandler(serviceName).getClass().getInterfaces();
		} else {
			return new Class<?>[]{getHandler(serviceName).getClass()};
		}
	}
1097079
public function createServerRequestFromServer(): ServerRequestInterface
        {
            $method  = $_SERVER['REQUEST_METHOD'];
            $uri     = (new UriFactory)->createUriFromServer($_SERVER);
            $files   = (new UploadedFileFactory)->createUploadedFileFromServer($_FILES);
            
            $request = $this->createServerRequest($method, $uri, $_SERVER);
            $request = $request->withQueryParams($_GET);
            $request = $request->withParsedBody($_POST);
            $request = $request->withCookieParams($_COOKIE);
            $request = $request->withUploadedFiles($files);
            return $request;
        }
1149970
function serializeRefs(k,v, clientData) {
  if (k == 'clientTemplates') {  //avoid circular refs but doesn't seem to work??
    return undefined;
  }
  if (v && typeof v === 'object') {
    //we have to do it like this to avoid toString being call internally
    var copy = new v.constructor();
    for (var prop in v) {
      if (!v.hasOwnProperty(prop)) continue;
      var val = v[prop]
      if (val && val._id) {
        var obj = val;
        clientData[obj._id] = _.extend(clientData[obj._id] || {}, obj);
        val = "@@@" + obj._id+ "@@@";
      }
      copy[prop] = val;
    }
    return copy;
  }
  return v;
}