def RegisterObject(obj, request):
    '''
        Recursively register an object plus all contained child objects.
        Registering means we put the object somewhere it can be looked up
        in the Web API.
        We would mainly like to register PyGnome objects.  Others
        we probably don't care about.
    '''
    if (hasattr(obj, 'id') and
            not obj.__class__.__name__ == 'type'):
        # print 'RegisterObject(): registering:', (obj.__class__.__name__,
        #                                           obj.id)
        set_session_object(obj, request)
    if isinstance(obj, (list, tuple, OrderedCollection,
                        SpillContainerPair)):
        for i in obj:
            RegisterObject(i, request)
    elif hasattr(obj, '__dict__'):
        for k in dir(obj):
            attr = getattr(obj, k)
            if not (k.find('_') == 0 or
                    isinstance(attr, (MethodType, FunctionType,
                                      BuiltinFunctionType,
                                      int, float, str, unicode, NoneType,
                                      Logger, BBox)
                               )):
                # print 'RegisterObject(): recursing attr:', (k, type(attr))
                RegisterObject(attr, request)
def RegisterObject(obj, request):
    '''
        Recursively register an object plus all contained child objects.
        Registering means we put the object somewhere it can be looked up
        in the Web API.
        We would mainly like to register PyGnome objects.  Others
        we probably don't care about.
    '''
    sequence_types = (list, tuple, OrderedCollection, SpillContainerPair)

    if (isinstance(obj, GnomeId)):
        set_session_object(obj, request)
        log.info('registering {0} on session {1}'.format(obj.name, request.session.session_id))

    if isinstance(obj, sequence_types):
        for i in obj:
            if (isinstance(i, GnomeId)):
                RegisterObject(i, request)
    elif hasattr(obj, '__dict__'):
        for k in dir(obj):
            attr = None
            try:
                attr = getattr(obj, k)
            except Exception as e:
                log.warning(str(e))
            if ((isinstance(attr, GnomeId) and get_session_object(attr.id, request) is None)
                or isinstance(attr, sequence_types)):
                RegisterObject(attr, request)
Example #3
0
def create_map(request):
    '''Creates a Gnome Map object.'''
    log_prefix = 'req({0}): create_map():'.format(id(request))
    init_session_objects(request)

    try:
        json_request = ujson.loads(request.body)
    except:
        raise cors_exception(request, HTTPBadRequest)

    if not JSONImplementsOneOf(json_request, implemented_types):
        raise cors_exception(request, HTTPNotImplemented)

    if 'filename' in json_request:
        json_request['filename'] = get_file_path(request,
                                                 json_request=json_request)

    gnome_sema = request.registry.settings['py_gnome_semaphore']
    gnome_sema.acquire()
    log.info('  ' + log_prefix + 'semaphore acquired...')

    try:
        obj = CreateObject(json_request, get_session_objects(request))
    except:
        raise cors_exception(request,
                             HTTPUnsupportedMediaType,
                             with_stacktrace=True)
    finally:
        gnome_sema.release()
        log.info('  ' + log_prefix + 'semaphore released...')

    set_session_object(obj, request)
    return obj.serialize()
Example #4
0
def create_map(request):
    '''Creates a Gnome Map object.'''
    log_prefix = 'req({0}): create_map():'.format(id(request))
    init_session_objects(request)

    try:
        json_request = ujson.loads(request.body)
    except:
        raise cors_exception(request, HTTPBadRequest)

    if not JSONImplementsOneOf(json_request, implemented_types):
        raise cors_exception(request, HTTPNotImplemented)

    if 'filename' in json_request:
        json_request['filename'] = get_file_path(request,
                                                 json_request=json_request)

    gnome_sema = request.registry.settings['py_gnome_semaphore']
    gnome_sema.acquire()
    log.info('  ' + log_prefix + 'semaphore acquired...')

    try:
        obj = CreateObject(json_request, get_session_objects(request))
    except:
        raise cors_exception(request, HTTPUnsupportedMediaType,
                             with_stacktrace=True)
    finally:
        gnome_sema.release()
        log.info('  ' + log_prefix + 'semaphore released...')

    set_session_object(obj, request)
    return obj.serialize()
Example #5
0
def update_model(request):
    '''
        Returns Model object in JSON.
        - This method varies slightly from the common object method in that
          if we don't specify a model ID, we:
          - update the current active model if it exists or...
          - generate a 'Not Found' exception.
    '''
    log_prefix = 'req({0}): update_model():'.format(id(request))
    log.info('>>' + log_prefix)

    ret = None
    try:
        json_request = ujson.loads(request.body.decode('utf-8'))
    except Exception:
        raise cors_exception(request, HTTPBadRequest)

    if not JSONImplementsOneOf(json_request, implemented_types):
        raise cors_exception(request, HTTPNotImplemented)

    session_lock = acquire_session_lock(request)
    log.info('  {} session lock acquired (sess:{}, thr_id: {})'.format(
        log_prefix, id(session_lock),
        current_thread().ident))

    obj_id = obj_id_from_req_payload(json_request)
    if obj_id:
        active_model = get_session_object(obj_id, request)
    else:
        active_model = get_active_model(request)

    if active_model:
        try:
            if UpdateObject(active_model, json_request,
                            get_session_objects(request)):
                set_session_object(active_model, request)
            ret = active_model.serialize(options=web_ser_opts)
        except Exception:
            raise cors_exception(request,
                                 HTTPUnsupportedMediaType,
                                 with_stacktrace=True)
        finally:
            session_lock.release()
            log.info('  ' + log_prefix + 'session lock released...')
    else:
        session_lock.release()
        log.info('  {} session lock released (sess:{}, thr_id: {})'.format(
            log_prefix, id(session_lock),
            current_thread().ident))

        msg = ("raising cors_exception() in update_model. "
               "Updating model before it exists.")
        log.warning('  ' + log_prefix + msg)

        raise cors_exception(request, HTTPNotFound)

    log.info('<<' + log_prefix)
    return ret
Example #6
0
def update_model(request):
    '''
        Returns Model object in JSON.
        - This method varies slightly from the common object method in that
          if we don't specify a model ID, we:
          - update the current active model if it exists or...
          - generate a 'Not Found' exception.
    '''
    log_prefix = 'req({0}): update_model():'.format(id(request))
    log.info('>>' + log_prefix)

    ret = None
    try:
        json_request = ujson.loads(request.body)
    except:
        raise cors_exception(request, HTTPBadRequest)

    if not JSONImplementsOneOf(json_request, implemented_types):
        raise cors_exception(request, HTTPNotImplemented)

    gnome_sema = request.registry.settings['py_gnome_semaphore']
    gnome_sema.acquire()
    log.info('  ' + log_prefix + 'semaphore acquired...')

    obj_id = obj_id_from_req_payload(json_request)
    if obj_id:
        active_model = get_session_object(obj_id, request)
    else:
        active_model = get_active_model(request)

    if active_model:
        try:
            if UpdateObject(active_model, json_request,
                            get_session_objects(request)):
                set_session_object(active_model, request)
            ret = active_model.serialize()
        except:
            raise cors_exception(request,
                                 HTTPUnsupportedMediaType,
                                 with_stacktrace=True)
        finally:
            gnome_sema.release()
            log.info('  ' + log_prefix + 'semaphore released...')
    else:
        gnome_sema.release()
        log.info('  ' + log_prefix + 'semaphore released...')

        msg = ("raising cors_exception() in update_model. "
               "Updating model before it exists.")
        log.warning('  ' + log_prefix + msg)

        raise cors_exception(request, HTTPNotFound)

    log.info('<<' + log_prefix)
    return ret
Example #7
0
def update_model(request):
    '''
        Returns Model object in JSON.
        - This method varies slightly from the common object method in that
          if we don't specify a model ID, we:
          - update the current active model if it exists or...
          - generate a 'Not Found' exception.
    '''
    log_prefix = 'req({0}): update_model():'.format(id(request))
    log.info('>>' + log_prefix)

    ret = None
    try:
        json_request = ujson.loads(request.body)
    except:
        raise cors_exception(request, HTTPBadRequest)

    if not JSONImplementsOneOf(json_request, implemented_types):
        raise cors_exception(request, HTTPNotImplemented)

    gnome_sema = request.registry.settings['py_gnome_semaphore']
    gnome_sema.acquire()
    log.info('  ' + log_prefix + 'semaphore acquired...')

    obj_id = obj_id_from_req_payload(json_request)
    if obj_id:
        active_model = get_session_object(obj_id, request)
    else:
        active_model = get_active_model(request)

    if active_model:
        try:
            if UpdateObject(active_model, json_request,
                            get_session_objects(request)):
                set_session_object(active_model, request)
            ret = active_model.serialize()
        except:
            raise cors_exception(request, HTTPUnsupportedMediaType,
                                 with_stacktrace=True)
        finally:
            gnome_sema.release()
            log.info('  ' + log_prefix + 'semaphore released...')
    else:
        gnome_sema.release()
        log.info('  ' + log_prefix + 'semaphore released...')

        msg = ("raising cors_exception() in update_model. "
               "Updating model before it exists.")
        log.warning('  ' + log_prefix + msg)

        raise cors_exception(request, HTTPNotFound)

    log.info('<<' + log_prefix)
    return ret
Example #8
0
def create_model(request):
    '''
        Creates a new model
    '''
    log_prefix = 'req({0}): create_object():'.format(id(request))
    log.info('>>' + log_prefix)

    try:
        json_request = ujson.loads(request.body.decode('utf-8'))
    except Exception:
        json_request = None

    if json_request and not JSONImplementsOneOf(json_request,
                                                implemented_types):
        raise cors_exception(request, HTTPNotImplemented)

    session_lock = acquire_session_lock(request)
    log.info('  {} session lock acquired (sess:{}, thr_id: {})'.format(
        log_prefix, id(session_lock),
        current_thread().ident))

    try:
        clean_session_dir(request)
        init_session_objects(request, force=True)

        if json_request:
            new_model = CreateObject(json_request,
                                     get_session_objects(request))
        else:
            new_model = Model()

        set_session_object(new_model, request)

        set_active_model(request, new_model.id)
    except Exception:
        raise cors_exception(request,
                             HTTPUnsupportedMediaType,
                             with_stacktrace=True)
    finally:
        session_lock.release()
        log.info('  {} session lock released (sess:{}, thr_id: {})'.format(
            log_prefix, id(session_lock),
            current_thread().ident))

    log.info('<<' + log_prefix)
    return new_model.serialize(options=web_ser_opts)
Example #9
0
def create_model(request):
    '''
        Creates a new model
    '''
    log_prefix = 'req({0}): create_object():'.format(id(request))
    log.info('>>' + log_prefix)

    try:
        json_request = ujson.loads(request.body)
    except:
        json_request = None

    if json_request and not JSONImplementsOneOf(json_request,
                                                implemented_types):
        raise cors_exception(request, HTTPNotImplemented)

    gnome_sema = request.registry.settings['py_gnome_semaphore']
    gnome_sema.acquire()
    log.info('  ' + log_prefix + 'semaphore acquired...')

    try:
        init_session_objects(request, force=True)

        if json_request:
            new_model = CreateObject(json_request,
                                     get_session_objects(request))
        else:
            new_model = Model()

        set_session_object(new_model, request)
        set_session_object(new_model._map, request)

        set_active_model(request, new_model.id)
    except:
        raise cors_exception(request,
                             HTTPUnsupportedMediaType,
                             with_stacktrace=True)
    finally:
        gnome_sema.release()
        log.info('  ' + log_prefix + 'semaphore released...')

    log.info('<<' + log_prefix)
    return new_model.serialize()
Example #10
0
def create_model(request):
    '''
        Creates a new model
    '''
    log_prefix = 'req({0}): create_object():'.format(id(request))
    log.info('>>' + log_prefix)

    try:
        json_request = ujson.loads(request.body)
    except:
        json_request = None

    if json_request and not JSONImplementsOneOf(json_request,
                                                implemented_types):
        raise cors_exception(request, HTTPNotImplemented)

    gnome_sema = request.registry.settings['py_gnome_semaphore']
    gnome_sema.acquire()
    log.info('  ' + log_prefix + 'semaphore acquired...')

    try:
        init_session_objects(request, force=True)

        if json_request:
            new_model = CreateObject(json_request,
                                     get_session_objects(request))
        else:
            new_model = Model()

        set_session_object(new_model, request)
        set_session_object(new_model._map, request)

        set_active_model(request, new_model.id)
    except:
        raise cors_exception(request, HTTPUnsupportedMediaType,
                             with_stacktrace=True)
    finally:
        gnome_sema.release()
        log.info('  ' + log_prefix + 'semaphore released...')

    log.info('<<' + log_prefix)
    return new_model.serialize()
Example #11
0
def update_map(request):
    '''Updates a Gnome Map object.'''
    try:
        json_request = ujson.loads(request.body.decode('utf-8'))
    except Exception:
        raise cors_exception(request, HTTPBadRequest)

    if not JSONImplementsOneOf(json_request, implemented_types):
        raise cors_exception(request, HTTPNotImplemented)

    obj = get_session_object(obj_id_from_req_payload(json_request), request)
    if obj:
        try:
            UpdateObject(obj, json_request, get_session_objects(request))
        except Exception:
            raise cors_exception(request,
                                 HTTPUnsupportedMediaType,
                                 with_stacktrace=True)
    else:
        raise cors_exception(request, HTTPNotFound)

    set_session_object(obj, request)
    return obj.serialize(options=web_ser_opts)
Example #12
0
def RegisterObject(obj, request):
    '''
        Recursively register an object plus all contained child objects.
        Registering means we put the object somewhere it can be looked up
        in the Web API.
        We would mainly like to register PyGnome objects.  Others
        we probably don't care about.
    '''
    if (hasattr(obj, 'id') and not obj.__class__.__name__ == 'type'):
        # print 'RegisterObject(): registering:', (obj.__class__.__name__,
        #                                           obj.id)
        set_session_object(obj, request)
    if isinstance(obj, (list, tuple, OrderedCollection, SpillContainerPair)):
        for i in obj:
            RegisterObject(i, request)
    elif hasattr(obj, '__dict__'):
        for k in dir(obj):
            attr = getattr(obj, k)
            if not (k.find('_') == 0 or isinstance(
                    attr, (MethodType, FunctionType, BuiltinFunctionType, int,
                           float, str, unicode, NoneType, Logger, BBox))):
                # print 'RegisterObject(): recursing attr:', (k, type(attr))
                RegisterObject(attr, request)
Example #13
0
def update_map(request):
    '''Updates a Gnome Map object.'''
    try:
        json_request = ujson.loads(request.body)
    except:
        raise cors_exception(request, HTTPBadRequest)

    if not JSONImplementsOneOf(json_request, implemented_types):
        raise cors_exception(request, HTTPNotImplemented)

    obj = get_session_object(obj_id_from_req_payload(json_request),
                             request)
    if obj:
        try:
            UpdateObject(obj, json_request, get_session_objects(request))
        except:
            raise cors_exception(request, HTTPUnsupportedMediaType,
                                 with_stacktrace=True)
    else:
        raise cors_exception(request, HTTPNotFound)

    set_session_object(obj, request)
    return obj.serialize()