Beispiel #1
0
    def get_item(self):
        """Gets the ``Item``.

        return: (osid.assessment.Item) - the assessment item
        *compliance: mandatory -- This method must be implemented.*

        """
        # So, for now we're assuming that what should be returned here is the question.
        # We could change this class impl to "know" if it came from a ResponseLookupSession call
        # and return the whole Item if so.
        try:
            # an un-answered response will have a magic itemId here
            item_lookup_session = get_item_lookup_session(
                runtime=self._runtime, proxy=self._proxy)
            item_lookup_session.use_federated_bank_view()
            item = item_lookup_session.get_item(self._item_id)
        except errors.NotFound:
            # otherwise an answered response will have an assessment-session itemId
            if self._section is not None:
                question = self._section.get_question(self._item_id)
                ils = self._section._get_item_lookup_session()
                real_item_id = Id(question._my_map['itemId'])
                item = ils.get_item(real_item_id)
            else:
                raise errors.NotFound()
        return item.get_question()
Beispiel #2
0
    def _init_object(self, catalog_id, proxy, runtime, db_name, cat_name,
                     cat_class):
        """Initialize this session an OsidObject based session."""
        self._catalog_identifier = None
        self._init_proxy_and_runtime(proxy, runtime)

        uses_cataloging = False
        if catalog_id is not None and catalog_id.get_identifier(
        ) != PHANTOM_ROOT_IDENTIFIER:
            self._catalog_identifier = catalog_id.get_identifier()

            config = self._runtime.get_configuration()
            parameter_id = Id('parameter:' + db_name +
                              'CatalogingProviderImpl@mongo')

            try:
                provider_impl = config.get_value_by_parameter(
                    parameter_id).get_string_value()
            except (AttributeError, KeyError, errors.NotFound):
                collection = JSONClientValidated(db_name,
                                                 collection=cat_name,
                                                 runtime=self._runtime)
                try:
                    self._my_catalog_map = collection.find_one(
                        {'_id': ObjectId(self._catalog_identifier)})
                except errors.NotFound:
                    if catalog_id.get_identifier_namespace(
                    ) != db_name + '.' + cat_name:
                        self._my_catalog_map = self._create_orchestrated_cat(
                            catalog_id, db_name, cat_name)
                    else:
                        raise errors.NotFound(
                            'could not find catalog identifier ' +
                            catalog_id.get_identifier() + cat_name)
            else:
                uses_cataloging = True
                cataloging_manager = self._runtime.get_manager(
                    'CATALOGING',
                    provider_impl)  # need to add version argument
                lookup_session = cataloging_manager.get_catalog_lookup_session(
                )
                # self._my_catalog_map = lookup_session.get_catalog(catalog_id)._my_map
                # self._catalog = Catalog(osid_object_map=self._my_catalog_map, runtime=self._runtime,
                #                         proxy=self._proxy)
                self._catalog = lookup_session.get_catalog(catalog_id)
        else:
            self._catalog_identifier = PHANTOM_ROOT_IDENTIFIER
            self._my_catalog_map = make_catalog_map(
                cat_name, identifier=self._catalog_identifier)

        if not uses_cataloging:
            self._catalog = cat_class(osid_object_map=self._my_catalog_map,
                                      runtime=self._runtime,
                                      proxy=self._proxy)

        self._catalog._authority = self._authority  # there should be a better way...
        self._catalog_id = self._catalog.get_id()
        self._forms = dict()
Beispiel #3
0
 def has_next_assessment_part(self, assessment_part_id):
     """This supports the basic simple sequence case. Can be overriden in a record for other cases"""
     if not self.supports_child_ordering or not self.supports_simple_child_sequencing:
         raise AttributeError()  # Only available through a record extension
     if 'childIds' in self._my_map and str(
             assessment_part_id) in self._my_map['childIds']:
         if self._my_map['childIds'][-1] != str(assessment_part_id):
             return True
         else:
             return False
     raise errors.NotFound('the Part with Id ' + str(assessment_part_id) +
                           ' is not a child of this Part')
Beispiel #4
0
    def _get_question_map(self, question_id):
        """get question map from questions matching question_id

        This can make sense of both Section assigned Ids or normal Question/Item Ids

        """
        if question_id.get_authority() == ASSESSMENT_AUTHORITY:
            key = '_id'
            match_value = ObjectId(question_id.get_identifier())
        else:
            key = 'questionId'
            match_value = str(question_id)
        for question_map in self._my_map['questions']:
            if question_map[key] == match_value:
                return question_map
        raise errors.NotFound()
Beispiel #5
0
    def remove_root(self, id_):
        """Removes a root node.

        arg:    id (osid.id.Id): the ``Id`` of the node
        raise:  NotFound - ``id`` was not found or not in hierarchy
        raise:  NullArgument - ``id`` is ``null``
        raise:  OperationFailed - unable to complete request
        raise:  PermissionDenied - authorization failure
        *compliance: mandatory -- This method must be implemented.*

        """
        result = self._rls.get_relationships_by_genus_type_for_peers(
            self._phantom_root_id, id_, self._relationship_type)
        if not bool(result.available()):
            raise errors.NotFound()
        self._ras.delete_relationship(result.get_next_relationship().get_id())
        self._adopt_orphans(id_)
Beispiel #6
0
    def remove_children(self, id_):
        """Removes all childrenfrom an ``Id``.

        arg:    id (osid.id.Id): the ``Id`` of the node
        raise:  NotFound - an node identified by the given ``Id`` was
                not found
        raise:  NullArgument - ``id`` is ``null``
        raise:  OperationFailed - unable to complete request
        raise:  PermissionDenied - authorization failure
        *compliance: mandatory -- This method must be implemented.*

        """
        results = self._rls.get_relationships_by_genus_type_for_source(
            id_, self._relationship_type)
        if results.available() == 0:
            raise errors.NotFound()
        for r in results:
            self._ras.delete_relationship(r.get_id())
Beispiel #7
0
    def remove_child(self, id_, child_id):
        """Removes a childfrom an ``Id``.

        arg:    id (osid.id.Id): the ``Id`` of the node
        arg:    child_id (osid.id.Id): the ``Id`` of the child to remove
        raise:  NotFound - ``id`` or ``child_id`` was not found or
                ``child_id`` is not a child of ``id``
        raise:  NullArgument - ``id`` or ``child_id`` is ``null``
        raise:  OperationFailed - unable to complete request
        raise:  PermissionDenied - authorization failure
        *compliance: mandatory -- This method must be implemented.*

        """
        result = self._rls.get_relationships_by_genus_type_for_peers(
            id_, child_id, self._relationship_type)
        if not bool(result.available()):
            raise errors.NotFound()
        self._ras.delete_relationship(result.get_next_relationship().get_id())
Beispiel #8
0
 def _unassign_object_from_catalog(self, obj_id, cat_id):
     pkg_name = obj_id.get_identifier_namespace().split('.')[0]
     obj_name = obj_id.get_identifier_namespace().split('.')[1]
     catalog_key = 'assigned' + self._catalog_name + 'Ids'
     collection = JSONClientValidated(pkg_name,
                                      collection=obj_name,
                                      runtime=self._runtime)
     obj_map = collection.find_one(
         {'_id': ObjectId(obj_id.get_identifier())})
     if obj_map[catalog_key] == [str(cat_id)]:
         raise errors.OperationFailed(
             'unassigning object from ${cat_name_under} would leave it unattached'
         )
     try:
         obj_map[catalog_key].remove(str(cat_id))
     except (KeyError, ValueError):
         raise errors.NotFound()
     collection.save(obj_map)
Beispiel #9
0
 def _create_orchestrated_cat(self, foreign_catalog_id, db_name, cat_name):
     """Creates a catalog in the current service orchestrated with a foreign service Id."""
     if (foreign_catalog_id.identifier_namespace == db_name + '.' + cat_name
             and foreign_catalog_id.authority == self._authority):
         raise errors.NotFound()  # This is not a foreign catalog
     foreign_service_name = foreign_catalog_id.get_identifier_namespace(
     ).split('.')[0]
     # foreign_cat_name = inflection.underscore(foreign_catalog_id.namespace.split('.')[1])
     # catalog_name = foreign_cat_name.lower()
     catalog_name = camel_to_under(
         foreign_catalog_id.namespace.split('.')[1])
     manager = self._get_provider_manager(foreign_service_name.upper())
     lookup_session = getattr(
         manager,
         'get_{0}_lookup_session'.format(catalog_name))(proxy=self._proxy)
     getattr(lookup_session, 'get_{0}'.format(catalog_name))(
         foreign_catalog_id)  # Raises NotFound
     collection = JSONClientValidated(db_name,
                                      collection=cat_name,
                                      runtime=self._runtime)
     foreign_identifier = ObjectId(foreign_catalog_id.get_identifier())
     default_text = 'Orchestrated ' + foreign_service_name
     catalog_map = make_catalog_map(cat_name,
                                    identifier=foreign_identifier,
                                    default_text=default_text)
     collection.insert_one(catalog_map)
     alias_id = Id(identifier=foreign_catalog_id.identifier,
                   namespace=db_name + '.' + cat_name,
                   authority=self._authority)
     try:
         admin_session = getattr(
             manager, 'get_{0}_admin_session'.format(catalog_name))(
                 proxy=self._proxy)
         getattr(admin_session,
                 'alias_{0}'.format(catalog_name))(foreign_catalog_id,
                                                   alias_id)
     except (errors.Unimplemented, AttributeError):
         pass
     return catalog_map
Beispiel #10
0
    def _get_descendent_cat_idstrs(self, cat_id, hierarchy_session=None):
        """Recursively returns a list of all descendent catalog ids, inclusive"""
        def get_descendent_ids(h_session):
            idstr_list = [str(cat_id)]
            if h_session is None:
                pkg_name = cat_id.get_identifier_namespace().split('.')[0]
                cat_name = cat_id.get_identifier_namespace().split('.')[1]
                try:
                    mgr = self._get_provider_manager('HIERARCHY')
                    h_session = mgr.get_hierarchy_traversal_session_for_hierarchy(
                        Id(authority=pkg_name.upper(),
                           namespace='CATALOG',
                           identifier=cat_name.upper()),
                        proxy=self._proxy)
                except (errors.OperationFailed, errors.Unsupported):
                    return idstr_list  # there is no hierarchy
            if h_session.has_children(cat_id):
                for child_id in h_session.get_children(cat_id):
                    idstr_list += self._get_descendent_cat_idstrs(
                        child_id, h_session)
            return list(set(idstr_list))

        use_caching = False
        try:
            config = self._runtime.get_configuration()
            parameter_id = Id('parameter:useCachingForQualifierIds@json')
            if config.get_value_by_parameter(parameter_id).get_boolean_value():
                use_caching = True
            else:
                pass
        except (AttributeError, KeyError, errors.NotFound):
            pass
        if use_caching:
            key = 'descendent-catalog-ids-{0}'.format(str(cat_id))

            # If configured to use memcache as the caching engine, use it.
            # Otherwise default to diskcache
            caching_engine = 'diskcache'

            try:
                config = self._runtime.get_configuration()
                parameter_id = Id('parameter:cachingEngine@json')
                caching_engine = config.get_value_by_parameter(
                    parameter_id).get_string_value()
            except (AttributeError, KeyError, errors.NotFound):
                pass

            if caching_engine == 'memcache':
                import memcache
                caching_host = '127.0.0.1:11211'
                try:
                    config = self._runtime.get_configuration()
                    parameter_id = Id('parameter:cachingHostURI@json')
                    caching_host = config.get_value_by_parameter(
                        parameter_id).get_string_value()
                except (AttributeError, KeyError, errors.NotFound):
                    pass

                mc = memcache.Client([caching_host], debug=0)

                catalog_ids = mc.get(key)
                if catalog_ids is None:
                    catalog_ids = get_descendent_ids(hierarchy_session)
                    mc.set(key, catalog_ids)
            elif caching_engine == 'diskcache':
                import diskcache
                with diskcache.Cache('/tmp/dlkit_cache') as cache:
                    # A little bit non-DRY, since it's almost the same as for memcache above.
                    # However, for diskcache.Cache, we have to call ".close()" or use a
                    #   ``with`` statement to safeguard calling ".close()", so we keep this
                    #   separate from the memcache implementation.
                    catalog_ids = cache.get(key)
                    if catalog_ids is None:
                        catalog_ids = get_descendent_ids(hierarchy_session)
                        cache.set(key, catalog_ids)
            else:
                raise errors.NotFound(
                    'The {0} caching engine was not found.'.format(
                        caching_engine))
        else:
            catalog_ids = get_descendent_ids(hierarchy_session)
        return catalog_ids