Processes a route call, something like `stuff::thing' or just a function name
or even a closure.
556040
protected function process($proto) {
        /* We're accepting different types of handler declarations. It can be
         * anything PHP defines as a 'callable', or in the form class::method. */
        $class = '';
        $method = '';
        $call = $proto['call'];
        $matches = $proto['params'];

        if(is_string($call) && preg_match('/^.+::.+$/', trim($call))) {
            list($class, $method) = explode('::', $call);
        }
        else if(is_array($call)) {
            $class = $call[0];
            $method = $call[1];
        }
        else if(is_callable($call)) {
            $method = $call;
        }

        $response = null;

        $this->modules->runMethod('preProcess', array(
            'request' => $this->request,
            'proto' => $proto,
            'response' => $response,
        ));

        if(!$class) { // Just a function call (or a closure?). Less hooks obviously.
            // Mounting system stuff into an object and generating the parameters.
            $params = array_merge(array((object)array(
                              'modules' => $this->modules,
                              'server'  => $this->server,
                              'request' => $this->request,
                              'sec'     => Injector::give('Security'))),
                      array_slice($matches, 1));
            $response = call_user_func_array($method, $params);
        }
        else if(class_exists($class)) {
            $obj = new $class($this->modules, $this->server,
                              $this->request, new Security());

            if(method_exists($obj, 'preRequest'))
                $obj->preRequest();

            if(method_exists($obj, $method)) {
                $response = call_user_func_array(array($obj, $method),
												 array_slice($matches, 1));
                if(method_exists($obj, 'postRequest'))
                    $response = $obj->postRequest($response);
            } else {
                throw new \BadMethodCallException("Method, $method, not supported.");
            }
        } else {
            throw new NoHandlerException("Class, $class, not found.");
        }

        // Cleaning up the response...
        if(gettype($response) == 'string') {
            $response = Injector::give('Response', $response);
        }
        else if($response === null) {
            $response = Injector::give('Response');
        }
        else if(gettype($response) != 'object'
                || (gettype($response) == 'object'
                    && (get_class($response) != 'atlatl\Response'
                        && !is_subclass_of($response, 'atlatl\Response')))) {
            throw new IllegalResponseException('Unknown response.');
        }

        $this->modules->runMethod('postProcess', array(
            'request' => $this->request,
            'proto' => $proto,
            'response' => $response
        ));

        return $response;
    }
335874
def find_call(self, path, method):
        
        if not path.endswith('/'):
            path += '/'
        path = path.split('/')[1:]
        return self._recursive_route_match(self._routes, path, method, [])
840196
def call(env)
      # remove the callback and _ parameters BEFORE calling the backend, so
      # that caching middleware does not store a copy for each value of the
      # callback parameter
      request = Rack::Request.new(env)
      callback = request.params.delete(@callback_param)
      timestamp = request.params.delete(@timestamp_param)
      env['QUERY_STRING'] = env['QUERY_STRING'].split("&").delete_if{|param|
        param =~ /^(#{@timestamp_param}|#{@callback_param})=/
      }.join("&")
      env['rack.jsonp.callback'] = callback
      env['rack.jsonp.timestamp'] = timestamp

      status, headers, response = @app.call(env)

      if callback && headers['Content-Type'] =~ /json/i
        response = pad(callback, response)
        headers['Content-Length'] = response.first.bytesize.to_s
        headers['Content-Type'] = 'application/javascript'
      elsif @carriage_return && headers['Content-Type'] =~ /json/i
        # add a \n after the response if this is a json (not JSONP) response
        response = carriage_return(response)
        headers['Content-Length'] = response.first.bytesize.to_s
      end

      [status, headers, response]
    end
870568
def passes_route_hooks?(route, message, robot)
      robot.hooks[:validate_route].all? do |hook|
        hook.call(handler: handler, route: route, message: message, robot: robot)
      end
    end
1360965
def _call_one_middleware(self, middleware):
        '''  '''
        args = {}
        for arg in middleware['args']:
            if hasattr(self, arg):
                # same as eval() but safer for arbitrary code execution
                args[arg] = reduce(getattr, arg.split('.'), self)
        self.logger.debug('calling middleware event {}'
                          .format(middleware['name']))
        middleware['call'](**args)
1079268
def call(args = {}, &block)
      response = API.call(full_name, args, token)
      Result.process(response, type, block)
    end
731948
function adaptForRouter(val, key) {
  key = key.split(/\s+/);
  if (typeof val === 'string' || typeof val === 'function' || Array.isArray(val)) {
    val = {
      path: key[0],
      method: key[1],
      controller: val
    };
  } else if (typeof val === 'object') {
    if (!val.path) {
      val.path = key[0];
    }
    if (!val.method) {
      val.method = key[1];
    }
  } else {
    throw new Error(`Problem with route "${key}"`);
  }
  return val;
}
579770
function asyncWrap (route) {
  return (req, res, next) => route(req, res, next).catch(next)
}
396672
function remove(route, callback, context){
    var route = get({
      path: route
    });

    if (!route)
      return;

    for (var i = 0, cb; cb = route.callbacks_[i]; i++)
    {
      if (cb.cb_ === callback && cb.context === context)
      {
        route.callbacks_.splice(i, 1);

        if (route.value && callback && callback.leave)
        {
          callback.leave.call(context);

          /** @cut */ if (module.exports.debug)
          /** @cut */   basis.dev.info(
          /** @cut */     namespace + ': add handler for route `' + path + '`\n',
          /** @cut */     { type: 'leave', path: route.path, cb: callback.leave, route: route }
          /** @cut */   );
        }

        if (!route.callbacks_.length)
        {
          // check no attaches to route
          if ((!route.handler || !route.handler.handler) && !route.matched.handler)
          {
            basis.array.remove(allRoutes, route);

            if (!(route instanceof ParametrizedRoute))
              delete plainRoutesByPath[route.path];
          }
        }

        return;
      }
    }
    /** @cut */ basis.dev.warn(namespace + ': no callback removed', { callback: callback, context: context });
  }
1238895
function(route, name, callback) 
	{
		var regExp = conbo.isRegExp(route) ? route : this.__routeToRegExp(route);
		
		if (!callback) 
		{
			callback = this[name];
		}
		
		if (conbo.isFunction(name)) 
		{
			callback = name;
			name = '';
		}
		
		if (!callback) 
		{
			callback = this[name];
		}
		
		this.__history.addRoute(regExp, (function(path)
		{
			var args = this.__extractParameters(regExp, path);
			
			var params = conbo.isString(route) 
				? conbo.object((route.match(/:\w+/g) || []).map(function(r) { return r.substr(1); }), args) 
				: {}
				;
			
			callback && callback.apply(this, args);
			
			var options = 
			{
				router:		this,
				route:		regExp,
				name:		name,
				parameters:	args,
				params:		params,
				path:		path
			};
			
			this.dispatchEvent(new conbo.ConboEvent('route:'+name, options));
			this.dispatchEvent(new conbo.ConboEvent(conbo.ConboEvent.ROUTE, options));
			
		}).bind(this));
		
		return this;
	}
8585
function on (route, methods) {
    assert.equal(typeof route, 'string')
    methods = methods || {}

    // mount subrouter
    if (methods[sym]) return router.on(route, methods)

    assert.equal(typeof methods, 'object')

    // mount http methods
    router.on(route, function (args) {
      demuxSsa(args, function (req, res, params) {
        const meth = methodist(req, defaultFn, methods)
        meth(req, res, params)

        // default function to call if methods don't match
        // null -> null
        function defaultFn () {
          router._default(args)
        }
      })
    })
    return emit
  }
621557
function process_get(request, response, uri) {
	// if path is /things then return the set of thing models
	let path = URL.parse(request.url).pathname;
	
	if (path === "/things") {
		if (!authorised(request))
			return fail(401, "unauthorized", response);
		
		let list = [];
		
		for (var name in things) {
			if (things.hasOwnProperty(name)) {
				list.push(things[name].model);
			}
		}
		
		body = JSON.stringify(list, null, 4);
	
		response.writeHead(200, {
			'Content-Type': mime_types.json,
			'Pragma': 'no-cache',
			'Cache-Control': 'no-cache',
			'Access-Control-Allow-Origin': '*',
			'Access-Control-Allow-Credentials': 'true',
			'Content-Length': body.length
		});

		if (request.method === "GET")
				response.write(body);

		response.end();
		return;
	}

	// does path start with /things/thingID for some thingID?

	if (/^\/things\/.+/.test(path)) {
		if (!authorised(request))
			return fail(401, "unauthorized", response);

		path = path.substr(8);
		
		let i = path.indexOf('/');
		var thingID, body;
		
		if (i < 0) {
			thingID = path;
			path = "";
		} else {
			thingID = path.substr(0, i);
			path = path.substr(i);
		}
		
		if (thingID) {
			let thing = things[thingID];
			
			if (!thing)
				return fail(404, "unknown thing: " + thingID, response);
				
			if (!thing.model)
				return fail(404, "no model for thing: " + thingID, response);
				
			if (path === "") {
				body = JSON.stringify(thing.model, null, 4);
				console.log(body);
			} else if (path === "/properties"){
				// construct set of property values
				let values = {};
				
				for (var name in thing.properties) {
					if (thing.properties.hasOwnProperty(name)) {
						values[name] = thing.properties[name].value;
					}
				}
				
				body = JSON.stringify(values, null, 4);
			} else if (/^\/properties\/.+/.test(path)) {
				path = path.substr(12);
				console.log("property name: " + path);
				let property = thing.properties[path];
				
				if (property === undefined)
					return fail(404, "unknown property: " + path, response);
					
				body = JSON.stringify(property.value, null, 4);
			} else if (path === "/events") {
				// add to thing's set of server-sent event streams
				console.log("new server-sent event stream for thing: " + thing.name);
				
				response.writeHead(200, {
					'Content-Type': 'text/event-stream',
					'Cache-Control': 'no-cache',
					'Connection': 'keep-alive',
					'Access-Control-Allow-Credentials': 'true',
					'Access-Control-Allow-Origin': '*'
				});

				if (request.method === "HEAD") {
					response.end();
					return;
				}

				let id = gensym();
				console.log('client id = ' + id);
				
				thing.clients[id] = {
					id: id,
					response: response
				};
				
				// tidy up when connection is closed
				// e.g. after a browser tab is hidden

				response.on("close", function () {
					console.log('lost client id = ' + id);
					let clients = thing.clients
					delete clients[id];
				});

				response.on("end", function () {
					console.log('lost client id = ' + id);
					let clients = thing.clients
					delete clients[id];
				});

				return;
			} else if (/^\/events\/.+/.test(path)) {
				path = path.substr(8);
				console.log("long poll on event named: " + path);
				let event = thing.events[path];
				
				if (event === undefined)
					return fail(404, "unknown event: " + path, response);
					
				event.longpoll.push(response);
				return;
			} else {
				return fail(404, "invalid request: " + uri, response);
			}
			
			console.log('body length = ' + body.length);
			
			response.writeHead(200, {
				'Content-Type': mime_types.json,
				'Pragma': 'no-cache',
				'Cache-Control': 'no-cache',
				'Access-Control-Allow-Origin': '*',
				'Access-Control-Allow-Credentials': 'true',
				'Content-Length': body.length
			});

			if (request.method === "GET")
					response.write(body);

			response.end();
			return;
		}
		
		return fail(404, "missing thingID: " + path, response);
	}
	
	let prefix = './www';

	console.log('request for "' + path + '"');
	// assume this is a request for a file

	if (path[path.length-1] === '/')
		path += 'index.html';

	let filename = decodeURI(prefix + path);
	let gzipped = false;

	console.log('filename: ' + filename);

	FS.stat(filename, function(error, stat) {
		var ext = PATH.extname(filename);
		var mime = null;

		if (ext === ".gz") {
			gzipped = true;
			ext = PATH.extname(filename.substr(0, filename.length-3));
		}

		if (ext.length > 1)
			mime = mime_types[ext.split(".")[1]];

		if (error || !mime) {
			console.log("unable to serve " + filename);
			var body = "404 not found: " + request.url;
			response.writeHead(404, {
				'Content-Type': 'text/plain',
				'Content-Length': body.length
			});

			if (request.method === "GET")
				response.write(body);

			response.end();
		} else {
			if (gzipped) {
				console.log("filename has mime type " + mime);
				response.writeHead(200, {
					'Content-Type': mime,
					'Content-Encoding': 'gzip',
					'Pragma': 'no-cache',
					'Cache-Control': 'no-cache',
					'Access-Control-Allow-Origin': '*',
					'Access-Control-Allow-Credentials': 'true',
					'Content-Length': stat.size
				});
			} else {
				response.writeHead(200, {
					'Content-Type': mime,
					'Pragma': 'no-cache',
					'Cache-Control': 'no-cache',
					'Access-Control-Allow-Origin': '*',
					'Access-Control-Allow-Credentials': 'true',
					'Content-Length': stat.size
				});
			}

			if (request.method === "GET") {
				var stream = FS.createReadStream(filename);
				stream.pipe(response);
			} else
				response.end();
		}
	});
}
646515
function routeChat(call) {
  call.on('data', function(note) {
    var key = pointKey(note.getLocation());
    /* For each note sent, respond with all previous notes that correspond to
     * the same point */
    if (route_notes.hasOwnProperty(key)) {
      _.each(route_notes[key], function(note) {
        call.write(note);
      });
    } else {
      route_notes[key] = [];
    }
    // Then add the new note to the list
    route_notes[key].push(note);
  });
  call.on('end', function() {
    call.end();
  });
}
750191
function Route(ctx, path, handler) {
  if (!(this instanceof Route))
    return new Route(ctx, path, handler);

  this.ctx = null;
  this.path = null;
  this.handler = null;

  this.regex = /^/;
  this.map = [];
  this.compiled = false;

  if (ctx) {
    assert(typeof ctx === 'object');
    this.ctx = ctx;
  }

  if (path) {
    if (path instanceof RegExp) {
      this.regex = path;
    } else {
      assert(typeof path === 'string');
      assert(path.length > 0);
      this.path = path;
    }
  }

  assert(handler);
  assert(typeof handler === 'function' || typeof handler === 'object');

  this.handler = handler;
}
628222
function (params) {
			// 
			// Close the route once it has been handled.
			//
			var closeRoute = function () {
				that._closeRoute(dir, req, res, params);
			};

			var async = new Async(closeRoute);
			routeConfig.handler(req, res, params, async);

			if (!async.started()) {
				// No async operation was started.
				// Close the route immediately.
				closeRoute();
			}			
		}
456347
function(router, target) {
    // By default, just patch the router's own methods.
    // If a target is given, then patch the router to call the target's methods
    target = target || router;

    // get(setting), which is different than get(path, fn)
    var get = router.get;

    // Wrap all of these methods to convert Swagger-style paths to Express-style paths
    var fns = {};
    ['use', 'route', 'all'].concat(swaggerMethods).forEach(function(method) {
      fns[method] = target[method];
      router[method] = function(path) {
        var args = _.drop(arguments, 0);

        // Special-case for `app.get(setting)`
        if (args.length === 1 && method === 'get') {
          return get.call(router, path);
        }

        // Convert Swagger-style path to Express-style path
        if (_.isString(path)) {
          args[0] = path.replace(util.swaggerParamRegExp, ':$1');
        }

        // Pass-through to the corresponding Express method
        var ret = fns[method].apply(target, args);

        if (router.__sortMiddleWare) {
          router.__sortMiddleWare();
        }

        return ret;
      };
    });
  }
1080304
function () {
        return hooks.process(this._getApi())
            .then(function handleHooks(data) {
                if (Type.isInitialized(data) && !!data) {
                    return data;
                } else if (this.isPromiseChainStopped) {
                    return false;
                }
                return router
                    .process(this.request.method, this.parsedUrl, this.getRequestHeaders()) // find route
                    .then(this._resolveRoute.bind(this)); // resolve route chain
            }.bind(this)) // handle hook chain
            .then(this._compress.bind(this))
            .then(this._render.bind(this)) // resolve route chain
            .catch(this._handleError.bind(this)) // catch hook error
            .then(this._compress.bind(this))
            .then(this._render.bind(this)) // render hook error
            .catch(this._handleError.bind(this)) // catch render error
            .then(this._compress.bind(this))
            .then(this._render.bind(this)); // resolve render error
    }