<commit_before>#
# Modified routeserver to output XML-formatted route results.
# Author: <NAME> (<EMAIL>)
# Company: University of Illinois at Chicago
# Last modified: 4/20/10
#

from routeserver_servable import Servable
from SocketServer import ForkingMixIn
from wsgiref.simple_server import WSGIServer, make_server
from graphserver.graphdb import GraphDatabase
import cgi
from graphserver.core import State, WalkOptions
import time
import sys
import graphserver
from graphserver.util import TimeHelpers
from graphserver.ext.osm.pgosmdb import PostgresGIS_OSMDB
from graphserver.ext.gtfs.pggtfsdb import PostgresGIS_GTFSDB
from math import fmod, sin, cos, atan2, pi, degrees
from graphserver.ext.osm.vincenty import vincenty
import json

class ChicagoMap:
    bounding_lon_left=-89.106976260401382
    bounding_lat_bottom=41.028302192122915
    bounding_lon_right=-86.866313839598618
    bounding_lat_top=42.948031407877082

class WalkPath:
    def __init__(self):
        self.name = ""
        self.dep_time = ""
        self.arr_time = ""
        self.points = []
        self.length = 0.0
        self.bearing = 0.0
        self.direction = ""
        self.turn_direction = ""
        self.lastlat = 0.0
        self.lastlon = 0.0
        self.total_distance = 0.0
        self.timezone = ""

class RouteInfo:
    def __init__(self):
        self.origlat = ""
        self.origlon = ""
        self.actual_dep_time = 0
        self.dep_time_diff = 0
        self.destlat = ""
        self.destlon = ""
        self.actual_arr_time = 0
        self.arr_time_diff = 0
        self.first_edge = True
        self.last_edge = False
        self.street_mode = ""

class MyWSGIServer(ForkingMixIn, WSGIServer):
    pass

class RouteServer(Servable):
    def __init__(self, graphdb_filename, pgosmdb_handle, pggtfsdb_handle, event_dispatch):
        graphdb = GraphDatabase( graphdb_filename )
        self.graph = graphdb.incarnate()
        self.graph.num_agencies = 3
        self.graph.numagencies = self.graph.num_agencies
        self.event_dispatch = event_dispatch
        self.pgosmdb = pgosmdb_handle
        self.pggtfsdb = pggtfsdb_handle
    
    def run_test_server(self, port=8080):
        print "starting RouteServer on port " + str(port)
        httpd = make_server('', port, self.wsgi_app(), MyWSGIServer)
        httpd.serve_forever()
    run_test_server.serve = False
    
    def transit_path(self, trip_id, board_stop_id, alight_stop_id, origlon=0, origlat=0, destlon=0, destlat=0):
        
        sys.stderr.write("[transit_path_entry_point," + str(time.time()) + "]\n")
        
        ret_string = '<transit trip_id="' + str(trip_id) + '" board_stop_id="' + str(board_stop_id) + '" alight_stop_id="' + str(alight_stop_id) + '">'
        ret_string += '<points>'
        
        sys.stderr.write("[get_transit_path_points," + str(time.time()) + "]\n")
        for point in self.pggtfsdb.get_transit_path_points(trip_id, board_stop_id, alight_stop_id):<commit_msg>got rid of Servable<commit_after>#
# Modified routeserver to output XML-formatted route results.
# Author: <NAME> (<EMAIL>)
# Company: University of Illinois at Chicago
# Last modified: 4/20/10
#

from routeserver_servable import Servable
from SocketServer import ForkingMixIn
from wsgiref.simple_server import WSGIServer, make_server
from graphserver.graphdb import GraphDatabase
import cgi
from graphserver.core import State, WalkOptions
import time
import sys
import graphserver
from graphserver.util import TimeHelpers
from graphserver.ext.osm.pgosmdb import PostgresGIS_OSMDB
from graphserver.ext.gtfs.pggtfsdb import PostgresGIS_GTFSDB
from math import fmod, sin, cos, atan2, pi, degrees
from graphserver.ext.osm.vincenty import vincenty
import json

class ChicagoMap:
    bounding_lon_left=-89.106976260401382
    bounding_lat_bottom=41.028302192122915
    bounding_lon_right=-86.866313839598618
    bounding_lat_top=42.948031407877082

class WalkPath:
    def __init__(self):
        self.name = ""
        self.dep_time = ""
        self.arr_time = ""
        self.points = []
        self.length = 0.0
        self.bearing = 0.0
        self.direction = ""
        self.turn_direction = ""
        self.lastlat = 0.0
        self.lastlon = 0.0
        self.total_distance = 0.0
        self.timezone = ""

class RouteInfo:
    def __init__(self):
        self.origlat = ""
        self.origlon = ""
        self.actual_dep_time = 0
        self.dep_time_diff = 0
        self.destlat = ""
        self.destlon = ""
        self.actual_arr_time = 0
        self.arr_time_diff = 0
        self.first_edge = True
        self.last_edge = False
        self.street_mode = ""

class MyWSGIServer(ForkingMixIn, WSGIServer):
    pass

class RouteServer:
    def __init__(self, graphdb_filename, pgosmdb_handle, pggtfsdb_handle, event_dispatch):
        graphdb = GraphDatabase( graphdb_filename )
        self.graph = graphdb.incarnate()
        self.graph.num_agencies = 3
        self.graph.numagencies = self.graph.num_agencies
        self.event_dispatch = event_dispatch
        self.pgosmdb = pgosmdb_handle
        self.pggtfsdb = pggtfsdb_handle
    
    def run_test_server(self, port=8080):
        print "starting RouteServer on port " + str(port)
        httpd = make_server('', port, self.wsgi_app(), MyWSGIServer)
        httpd.serve_forever()
    run_test_server.serve = False
    
    def wsgi_app(self):
        """returns a wsgi app which exposes this object as a webservice"""
        
        def myapp(environ, start_response):
            
            path_info = environ['PATH_INFO']
            query_string = environ['QUERY_STRING']
            
            #if not hasattr(self, 'pattern_cache'):
            #    self.pattern_cache = [(pth, args, pfunc) for pth, args, pfunc in self.patterns()]
            self.pattern_cache = [(re.compile('/path_xml'),[],self.path_xml),(re.compile('/transit_path'),[],self.transit_path)] 

            for ppath, pargs, pfunc in self.pattern_cache:
                if ppath.match(path_info):
                    
                    args = cgi.parse_qs(query_string)
                    args = dict( [(k,v[0]) for k,v in args.iteritems()] )
                        
                    try:
                        #use simplejson to coerce args to native types
                        #don't attempt to convert an arg 'jsoncallback'; just ignore it.
                        arglist = []
                        for k,v in args.iteritems():
                            if k=="jsoncallback":
                                arglist.append( (k,v) )
                            elif k != "_":
                                arglist.append( (k,json_loads(v)) )
                        args = dict( arglist )
                        
                        #try:
                        rr = xstr( pfunc(self,**args) )
                        #except TypeError:
                        #    problem = "Arguments different than %s"%str(pargs)
                        #    start_response('500 Internal Error', [('Content-type', 'text/plain'),('Content-Length', str(len(problem)))])
                        #    return [problem]
            
                        if hasattr(pfunc, 'mime'):
                            mime = pfunc.mime
                        else:
                            mime = self.DEFAULT_MIME
                            
                        start_response('200 OK', [('Content-type', mime),('Content-Length', str(len(rr)))])
                        return [rr]
                    except:
                        problem = traceback.format_exc()
                        start_response('500 Internal Error', [('Content-type', 'text/plain'),('Content-Length', str(len(problem)))])
                        return [problem]
                        
            # no match:
            problem = "No method corresponds to path '%s'"%environ['PATH_INFO']
            start_response('404 Not Found', [('Content-type', 'text/plain'),('Content-Length', str(len(problem)))])
            return [problem]
            
        return myapp

    def transit_path(self, trip_id, board_stop_id, alight_stop_id, origlon=0, origlat=0, destlon=0, destlat=0):
        
        sys.stderr.write("[transit_path_entry_point," + str(time.time()) + "]\n")
        
        ret_string = '<transit trip_id="' + str(trip_id) + '" board_stop_id="' + str(board_stop_id) + '" alight_stop_id="' + str(alight_stop_id) + '">'
        ret_string += '<points>'
        
        sys.stderr.write("[get_transit_path_points," + str(time.time()) + "]\n")
        for point in self.pggtfsdb.get_transit_path_points(trip_id, board_stop_id, alight_stop_id):
{'fraction_non_alphanumeric': 0.10300034486722612, 'fraction_numerical': 0.023795838602138176, 'mean_word_length': 2.1856462834126695, 'pattern_counts': {'":': 2, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '911046', 'n_tokens_mistral': 2840, 'n_tokens_neox': 2640, 'n_words': 554}