Esempio n. 1
0
 def __init__(self):
     CdbDbApi.__init__(self)
     self.entityTypeHandler = EntityTypeHandler()
     self.domainHandler = DomainHandler()
     self.itemHandler = ItemHandler()
     self.sourceHandler = SourceHandler()
     self.relationshipTypeHandler = RelationshipTypeHandler()
Esempio n. 2
0
 def __init__(self):
     CdbDbEntityHandler.__init__(self)
     self.entityInfoHandler = EntityInfoHandler()
     self.domainHandler = DomainHandler()
     self.entityTypeHandler = EntityTypeHandler()
     self.sourceHandler = SourceHandler()
     self.logHandler = LogHandler()
     self.propertyValueHandler = PropertyValueHandler()
     self.relationshipTypeHandler = RelationshipTypeHandler()
     self.resourceTypeHandler = ResourceTypeHandler()
     self.userInfoHandler = UserInfoHandler()
Esempio n. 3
0
class DomainHandler(CdbDbEntityHandler):

    CATALOG_DOMAIN_NAME = "Catalog"
    INVENTORY_DOMAIN_NAME = "Inventory"
    LOCATION_DOMAIN_NAME = "Location"
    MAARC_DOMAIN_NAME = "MAARC"
    MACHINE_DESIGN_NAME = "Machine Design"

    def __init__(self):
        CdbDbEntityHandler.__init__(self)
        self.entityTypeHandler = EntityTypeHandler()

    def getDomains(self, session):
        return self._getAllDbObjects(session, Domain)

    def findDomainByName(self, session, name):
        return self._findDbObjByName(session, Domain, name)

    def addDomain(self, session, domainName, description):
        self._prepareAddUniqueNameObj(session, Domain, domainName)

        # Create Domain Handler
        dbDomain = Domain(name=domainName)
        if description:
            dbDomain.description = description

        session.add(dbDomain)
        session.flush()
        self.logger.debug('Inserted domain id %s' % dbDomain.id)
        return dbDomain

    def addAllowedEntityType(self, session, domainName, entityTypeName):
        domain = self.findDomainByName(session, domainName)
        entityType = self.entityTypeHandler.findEntityTypeByName(
            session, entityTypeName)

        dbAllowedEntityTypeDomain = AllowedEntityTypeDomain()

        dbAllowedEntityTypeDomain.domain = domain
        dbAllowedEntityTypeDomain.entityType = entityType

        session.add(dbAllowedEntityTypeDomain)
        session.flush()
        self.logger.debug(
            'Inserted allowed entity type %s for domain handler %s' %
            (entityTypeName, domainName))

        return dbAllowedEntityTypeDomain

    def getAllowedEntityTypeDomain(self, session, domain_id):
        try:
            query = session.query(AllowedEntityTypeDomain).filter(
                AllowedEntityTypeDomain.domain_id == domain_id)
            dbAllowedEntityTypeDomain = query.all()
            return dbAllowedEntityTypeDomain
        except NoResultFound, ex:
            entityDisplayName = self._getEntityDisplayName()
            raise ObjectNotFound("No %s with domain id: %s was found." %
                                 (entityDisplayName, domain_id))
Esempio n. 4
0
class DomainHandler(CdbDbEntityHandler):
    def __init__(self):
        CdbDbEntityHandler.__init__(self)
        self.entityTypeHandler = EntityTypeHandler()

    def findDomainByName(self, session, name):
        return self._findDbObjByName(session, Domain, name)

    def addDomain(self, session, domainName, description):
        self._prepareAddUniqueNameObj(session, Domain, domainName)

        # Create Domain Handler
        dbDomain = Domain(name=domainName)
        if description:
            dbDomain.description = description

        session.add(dbDomain)
        session.flush()
        self.logger.debug('Inserted domain id %s' % dbDomain.id)
        return dbDomain

    def addAllowedEntityType(self, session, domainName, entityTypeName):
        domain = self.findDomainByName(session, domainName)
        entityType = self.entityTypeHandler.findEntityTypeByName(
            session, entityTypeName)

        dbAllowedEntityTypeDomain = AllowedEntityTypeDomain()

        dbAllowedEntityTypeDomain.domain = domain
        dbAllowedEntityTypeDomain.entityType = entityType

        session.add(dbAllowedEntityTypeDomain)
        session.flush()
        self.logger.debug(
            'Inserted allowed entity type %s for domain handler %s' %
            (entityTypeName, domainName))

        return dbAllowedEntityTypeDomain
Esempio n. 5
0
class ItemDbApi(CdbDbApi):
    """
    DB APIs that allow updates to entities related to items.
    """
    def __init__(self):
        CdbDbApi.__init__(self)
        self.entityTypeHandler = EntityTypeHandler()
        self.domainHandler = DomainHandler()
        self.itemHandler = ItemHandler()
        self.sourceHandler = SourceHandler()
        self.relationshipTypeHandler = RelationshipTypeHandler()

    @CdbDbApi.executeTransaction
    def addEntityType(self, name, description, **kwargs):
        """
        Add an entity type record.

        :param name:
        :param description:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbEntityType = self.entityTypeHandler.addEntityType(
            session, name, description)
        return dbEntityType.getCdbObject()

    @CdbDbApi.executeQuery
    def getEntityTypeByName(self, name, **kwargs):
        """
        Get an entity type record by its name.

        :param name: entity type name.
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbEntityType = self.entityTypeHandler.findEntityTypeByName(
            session, name)
        return dbEntityType.getCdbObject()

    @CdbDbApi.executeTransaction
    def addAllowedChildEntityType(self, parentEntityTypeName,
                                  childEntityTypeName, **kwargs):
        """
        Add an allowed child entity type record

        :param parentEntityTypeName:
        :param childEntityTypeName:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbEntityType = self.entityTypeHandler.addAllowedChildEntityType(
            session, parentEntityTypeName, childEntityTypeName)
        return dbEntityType.getCdbObject()

    @CdbDbApi.executeQuery
    def getDomainByName(self, name, **kwargs):
        """
        Get an item Domain by its name.

        :param name: name of item domain
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbDomain = self.domainHandler.findDomainByName(session, name)
        return dbDomain.getCdbObject()

    @CdbDbApi.executeTransaction
    def addAllowedEntityTypeDomain(self, domainName, entityTypeName, **kwargs):
        """
        Add an allowed entity type for a domain record.

        :param domainName:
        :param entityTypeName:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbAllowedEntityTypeDomain = self.domainHandler.addAllowedEntityType(
            session, domainName, entityTypeName)
        return dbAllowedEntityTypeDomain.getCdbObject()

    @CdbDbApi.executeTransaction
    def addDomain(self, name, description, **kwargs):
        """
        Add an item domain record.

        :param name:
        :param description:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbDomain = self.domainHandler.addDomain(session, name, description)
        return dbDomain.getCdbObject()

    @CdbDbApi.executeTransaction
    def addRelationshipTypeHandler(self, name, description, **kwargs):
        """
        Add an item relationship type handler.

        :param name:
        :param description:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbRelationshipTypeHandler = self.relationshipTypeHandler.addRelationshipTypeHandler(
            session, name, description)
        return dbRelationshipTypeHandler.getCdbObject()

    @CdbDbApi.executeQuery
    def getRelationshipTypeHandlerByName(self, name, **kwargs):
        """
        Get an item relationship type handler by its name.

        :param name:
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbRelationshipTypeHandler = self.relationshipTypeHandler.getRelationshipTypeHandlerByName(
            session, name)
        return dbRelationshipTypeHandler.getCdbObject()

    @CdbDbApi.executeTransaction
    def addRelationshipType(self, name, description,
                            relationshipTypeHandlerName, **kwargs):
        """
        Add an item relationship type record.

        :param name:
        :param description:
        :param relationshipTypeHandlerName:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbRelationshipType = self.relationshipTypeHandler.addRelationshipType(
            session, name, description, relationshipTypeHandlerName)
        return dbRelationshipType.getCdbObject()

    @CdbDbApi.executeQuery
    def getRelationshipTypeByName(self, name, **kwargs):
        """
        Get an item relationship type record by its name.

        :param name:
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbRelationshipType = self.relationshipTypeHandler.getRelationshipTypeByName(
            session, name)
        return dbRelationshipType.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItem(self,
                domainName,
                name,
                derivedFromItemId,
                itemIdentifier1,
                itemIdentifier2,
                entityTypeName,
                qrId,
                description,
                createdByUserId,
                ownerUserId,
                ownerGroupId,
                isGroupWriteable,
                createdOnDataTime=None,
                lastModifiedOnDateTime=None,
                **kwargs):
        """
        Add an item record.

        :param domainName:
        :param name:
        :param derivedFromItemId:
        :param itemIdentifier1:
        :param itemIdentifier2:
        :param entityTypeName:
        :param qrId:
        :param description:
        :param createdByUserId:
        :param ownerUserId:
        :param ownerGroupId:
        :param isGroupWriteable:
        :param createdOnDataTime:
        :param lastModifiedOnDateTime:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItem = self.itemHandler.addItem(
            session, domainName, name, derivedFromItemId, itemIdentifier1,
            itemIdentifier2, entityTypeName, qrId, description,
            createdByUserId, ownerUserId, ownerGroupId, isGroupWriteable,
            createdOnDataTime, lastModifiedOnDateTime)
        return dbItem.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItemElement(self,
                       name,
                       parentItemId,
                       containedItemId,
                       isRequired,
                       description,
                       createdByUserId,
                       ownerUserId,
                       ownerGroupId,
                       isGroupWriteable,
                       createdOnDataTime=None,
                       lastModifiedOnDateTime=None,
                       **kwargs):
        """
        Add an item element record.

        :param name:
        :param parentItemId:
        :param containedItemId:
        :param isRequired:
        :param description:
        :param createdByUserId:
        :param ownerUserId:
        :param ownerGroupId:
        :param isGroupWriteable:
        :param createdOnDataTime:
        :param lastModifiedOnDateTime:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItemElement = self.itemHandler.addItemElement(
            session, name, parentItemId, containedItemId, isRequired,
            description, createdByUserId, ownerUserId, ownerGroupId,
            isGroupWriteable, createdOnDataTime, lastModifiedOnDateTime)
        return dbItemElement.getCdbObject()

    @CdbDbApi.executeQuery
    def getItemById(self, itemId, **kwargs):
        """
        Get an item record by its id.

        :param itemId:
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbItem = self.itemHandler.getItemById(session, itemId)
        return dbItem.getCdbObject()

    @CdbDbApi.executeQuery
    def getItemByUniqueAttributes(self, domainId, name, itemIdentifier1,
                                  itemIdentifier2, derivedFromItemId,
                                  **kwargs):
        """
        Get an item record based on its unique attributes.

        :param domainId:
        :param name:
        :param itemIdentifier1:
        :param itemIdentifier2:
        :param derivedFromItemId:
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbItem = self.itemHandler.getItemByUniqueAttributes(
            session, domainId, name, itemIdentifier1, itemIdentifier2,
            derivedFromItemId)
        return dbItem.getCdbObject()

    @CdbDbApi.executeQuery
    def getItemElementsByItemId(self, itemId, **kwargs):
        """
        Get a list of item elements for a particular item.

        :param itemId:
        :param kwargs:
        :return: CdbObject List of item elements of a particular item.
        """
        session = kwargs['session']
        dbItemElements = self.itemHandler.getItemElementsByItemId(
            session, itemId)
        return self.toCdbObjectList(dbItemElements)

    @CdbDbApi.executeQuery
    def getItemElementById(self, itemElementId, **kwargs):
        """
        Get an item element by its id.

        :param itemElementId:
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbItemElement = self.itemHandler.getItemElementById(
            session, itemElementId)
        return dbItemElement.getCdbObject()

    @CdbDbApi.executeTransaction
    def addSource(self, sourceName, description, contactInfo, url, **kwargs):
        """
        Add a source record.

        Sources are various vendors that various items could be obtained from.

        :param sourceName:
        :param description:
        :param contactInfo:
        :param url:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbSource = self.sourceHandler.addSource(session, sourceName,
                                                description, contactInfo, url)
        return dbSource.getCdbObject()

    @CdbDbApi.executeQuery
    def getSources(self, **kwargs):
        """
        Get all records of sources.

        :param kwargs:
        :return: CDbObject List of sources in the db.
        """
        session = kwargs['session']
        dbSources = self.sourceHandler.getSources(session)
        return self.toCdbObjectList(dbSources)

    @CdbDbApi.executeTransaction
    def addItemSource(self, itemId, sourceName, partNumber, cost, description,
                      isVendor, isManufacturer, contactInfo, url, **kwargs):
        """
        Add an item source record.

        :param itemId:
        :param sourceName:
        :param partNumber:
        :param cost:
        :param description:
        :param isVendor:
        :param isManufacturer:
        :param contactInfo:
        :param url:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """

        session = kwargs['session']
        dbItemSource = self.itemHandler.addItemSource(session, itemId,
                                                      sourceName, partNumber,
                                                      cost, description,
                                                      isVendor, isManufacturer,
                                                      contactInfo, url)
        return dbItemSource.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItemCategory(self, name, description, domainName, **kwargs):
        """
        Add an item category

        items in particular domain could have different categories.

        :param name:
        :param description:
        :param domainName:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItemCategory = self.itemHandler.addItemCategory(
            session, name, description, domainName)
        return dbItemCategory.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItemProject(self, itemProjectName, description, **kwargs):
        """
        Add an item project.

        Items are assigned to projects.

        :param itemProjectName:
        :param description:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItemCategory = self.itemHandler.addItemProject(
            session, itemProjectName, description)
        return dbItemCategory.getCdbObject()

    @CdbDbApi.executeQuery
    def getItemProjects(self, **kwargs):
        """
        Get all item project records in the db.

        :param kwargs:
        :return: CDBObject List of item projects.
        """
        session = kwargs['session']
        dbItemProjects = self.itemHandler.getItemProjects(session)
        return self.toCdbObjectList(dbItemProjects)

    @CdbDbApi.executeTransaction
    def addItemItemProject(self, itemId, itemProjectName, **kwargs):
        """
        Assign an item to a particular project.

        :param itemId:
        :param itemProjectName:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """

        session = kwargs['session']
        dbItemCategory = self.itemHandler.addItemItemProject(
            session, itemId, itemProjectName)
        return dbItemCategory.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItemType(self, name, description, domainName, **kwargs):
        """
        Add an item type record.

        items in particular domain could have different types.

        :param name:
        :param description:
        :param domainName:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItemType = self.itemHandler.addItemType(session, name, description,
                                                  domainName)
        return dbItemType.getCdbObject()

    @CdbDbApi.executeQuery
    def getItemCategory(self, name, **kwargs):
        """
        Get an item category by its name.

        :param name:
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbItemCategory = self.itemHandler.getItemCategoryByName(session, name)
        return dbItemCategory.getCdbObject()

    @CdbDbApi.executeQuery
    def getItemType(self, name, domainName, **kwargs):
        """
        Get an item type by its name and domain name.

        :param name:
        :param domainName:
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbItemType = self.itemHandler.getItemTypeByName(
            session, name, domainName)
        return dbItemType.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItemItemCategory(self, itemId, categoryName, **kwargs):
        """
        Assign an item category to a particular item.

        :param itemId:
        :param categoryName:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItemType = self.itemHandler.addItemItemCategory(
            session, itemId, categoryName)
        return dbItemType.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItemItemType(self, itemId, typeName, **kwargs):
        """
        Assign an item type to a particular item.

        :param itemId:
        :param typeName:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItemType = self.itemHandler.addItemItemType(session, itemId,
                                                      typeName)
        return dbItemType.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItemElementLog(self,
                          itemElementId,
                          text,
                          enteredByUserId,
                          effectiveFromDateTime,
                          effectiveToDateTime,
                          logTopicName,
                          enteredOnDateTime=None,
                          systemLogLevelName=None,
                          **kwargs):
        """
        Add a log to a particular item element.

        NOTE: items have logs through their 'self element'.

        :param itemElementId:
        :param text:
        :param enteredByUserId:
        :param effectiveFromDateTime:
        :param effectiveToDateTime:
        :param logTopicName:
        :param enteredOnDateTime:
        :param systemLogLevelName:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItemElementLog = self.itemHandler.addItemElementLog(
            session, itemElementId, text, enteredByUserId,
            effectiveFromDateTime, effectiveToDateTime, logTopicName,
            enteredOnDateTime, systemLogLevelName)
        return dbItemElementLog.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItemElementProperty(self,
                               itemElementId,
                               propertyTypeName,
                               tag,
                               value,
                               units,
                               description,
                               enteredByUserId,
                               isUserWriteable,
                               isDynamic,
                               displayValue,
                               targetValue,
                               enteredOnDateTime=None,
                               **kwargs):
        """
        Add a property to a particular item element.

        NOTE: items have properties through their 'self element'.

        :param itemElementId:
        :param propertyTypeName:
        :param tag:
        :param value:
        :param units:
        :param description:
        :param enteredByUserId:
        :param isUserWriteable:
        :param isDynamic:
        :param displayValue:
        :param targetValue:
        :param enteredOnDateTime:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItemElementProperty = self.itemHandler.addItemElementProperty(
            session, itemElementId, propertyTypeName, tag, value, units,
            description, enteredByUserId, isUserWriteable, isDynamic,
            displayValue, targetValue, enteredOnDateTime)
        return dbItemElementProperty.getCdbObject()

    @CdbDbApi.executeQuery
    def getSelfElementByItemId(self, itemId, **kwargs):
        """
        Get an item self element by the id of the item.

        :param itemId:
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbItemElement = self.itemHandler.getSelfElementByItemId(
            session, itemId)
        return dbItemElement.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItemElementRelationship(self, firstItemElementId,
                                   secondItemElementId, firstItemConnectorId,
                                   secondItemConnectorId, linkItemElementId,
                                   relationshipTypeName, relationshipDetails,
                                   resourceTypeName, label, description,
                                   **kwargs):
        """
        Add an item element relationship.

        :param firstItemElementId:
        :param secondItemElementId:
        :param firstItemConnectorId:
        :param secondItemConnectorId:
        :param linkItemElementId:
        :param relationshipTypeName:
        :param relationshipDetails:
        :param resourceTypeName:
        :param label:
        :param description:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItemElementRelationship = self.itemHandler.addItemElementRelationship(
            session, firstItemElementId, secondItemElementId,
            firstItemConnectorId, secondItemConnectorId, linkItemElementId,
            relationshipTypeName, relationshipDetails, resourceTypeName, label,
            description)
        return dbItemElementRelationship.toCdbObject()

    @CdbDbApi.executeQuery
    def getItemsWithPropertyType(self,
                                 propertyTypeName,
                                 itemDomainName=None,
                                 itemDerivedFromItemId=None,
                                 propertyValueMatch=None,
                                 **kwargs):
        """
        Fetches items that have a particular property type.

        :param propertyTypeName:
        :param itemDomainName:
        :param itemDerivedFromItemId:
        :param propertyValueMatch:
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbItems = self.itemHandler.getItemsWithPropertyTypeName(
            session, propertyTypeName, itemDomainName, itemDerivedFromItemId,
            propertyValueMatch)
        return self.toCdbObjectList(dbItems)
Esempio n. 6
0
class ItemDbApi(CdbDbApi):
    """
    DB APIs that allow updates to entities related to items.
    """
    def __init__(self):
        CdbDbApi.__init__(self)
        self.entityTypeHandler = EntityTypeHandler()
        self.domainHandler = DomainHandler()
        self.itemHandler = ItemHandler()
        self.sourceHandler = SourceHandler()
        self.relationshipTypeHandler = RelationshipTypeHandler()
        self.permissionHandler = PermissionHandler()

    @CdbDbApi.executeQuery
    def getItemsOfDomain(self, domainName, **kwargs):
        session = kwargs['session']
        itemList = self.itemHandler.getItemsOfDomain(session, domainName)

        return self.toCdbObjectList(itemList)

    @CdbDbApi.executeQuery
    def getItemsOfDomainWithoutParents(self, domainName, **kwargs):
        session = kwargs['session']
        itemList = self.itemHandler.getItemsOfDomainWithoutParents(
            session, domainName)

        return self.toCdbObjectList(itemList)

    @CdbDbApi.executeQuery
    def getItemsDerivedFromItem(self, derivedItemId, **kwargs):
        session = kwargs['session']
        itemList = self.itemHandler.getItemsDerivedFromItem(
            session, derivedItemId)

        return self.toCdbObjectList(itemList)

    @CdbDbApi.executeQuery
    def verifyPermissionsForWriteToItemElement(self, username, itemElementId,
                                               **kwargs):
        """
        Check permissions for a specific item element.

        :param username:
        :param itemElementId:
        :param kwargs:
        :raises InvalidSession: when user does not have permission.
        :return: (Boolean) true if user has permissions.
        """
        session = kwargs['session']
        result = self.permissionHandler.verifyPermissionsForWriteToItemElement(
            session, username, itemElementId=itemElementId)
        return result

    @CdbDbApi.executeTransaction
    def addEntityType(self, name, description, **kwargs):
        """
        Add an entity type record.

        :param name:
        :param description:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbEntityType = self.entityTypeHandler.addEntityType(
            session, name, description)
        return dbEntityType.getCdbObject()

    @CdbDbApi.executeQuery
    def getEntityTypeByName(self, name, **kwargs):
        """
        Get an entity type record by its name.

        :param name: entity type name.
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbEntityType = self.entityTypeHandler.findEntityTypeByName(
            session, name)
        return dbEntityType.getCdbObject()

    @CdbDbApi.executeTransaction
    def addAllowedChildEntityType(self, parentEntityTypeName,
                                  childEntityTypeName, **kwargs):
        """
        Add an allowed child entity type record

        :param parentEntityTypeName:
        :param childEntityTypeName:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbEntityType = self.entityTypeHandler.addAllowedChildEntityType(
            session, parentEntityTypeName, childEntityTypeName)
        return dbEntityType.getCdbObject()

    @CdbDbApi.executeQuery
    def getDomainByName(self, name, **kwargs):
        """
        Get an item Domain by its name.

        :param name: name of item domain
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbDomain = self.domainHandler.findDomainByName(session, name)
        return dbDomain.getCdbObject()

    @CdbDbApi.executeTransaction
    def addAllowedEntityTypeDomain(self, domainName, entityTypeName, **kwargs):
        """
        Add an allowed entity type for a domain record.

        :param domainName:
        :param entityTypeName:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbAllowedEntityTypeDomain = self.domainHandler.addAllowedEntityType(
            session, domainName, entityTypeName)
        return dbAllowedEntityTypeDomain.getCdbObject()

    @CdbDbApi.executeTransaction
    def addDomain(self, name, description, **kwargs):
        """
        Add an item domain record.

        :param name:
        :param description:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbDomain = self.domainHandler.addDomain(session, name, description)
        return dbDomain.getCdbObject()

    @CdbDbApi.executeQuery
    def getDomains(self, **kwargs):
        """
        Get a list of all domains.

        :param kwargs:
        :return:
        """
        session = kwargs['session']
        dbDomainList = self.domainHandler.getDomains(session)
        return self.toCdbObjectList(dbDomainList)

    @CdbDbApi.executeTransaction
    def addRelationshipTypeHandler(self, name, description, **kwargs):
        """
        Add an item relationship type handler.

        :param name:
        :param description:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbRelationshipTypeHandler = self.relationshipTypeHandler.addRelationshipTypeHandler(
            session, name, description)
        return dbRelationshipTypeHandler.getCdbObject()

    @CdbDbApi.executeQuery
    def getRelationshipTypeHandlerByName(self, name, **kwargs):
        """
        Get an item relationship type handler by its name.

        :param name:
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbRelationshipTypeHandler = self.relationshipTypeHandler.getRelationshipTypeHandlerByName(
            session, name)
        return dbRelationshipTypeHandler.getCdbObject()

    @CdbDbApi.executeTransaction
    def addRelationshipType(self, name, description,
                            relationshipTypeHandlerName, **kwargs):
        """
        Add an item relationship type record.

        :param name:
        :param description:
        :param relationshipTypeHandlerName:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbRelationshipType = self.relationshipTypeHandler.addRelationshipType(
            session, name, description, relationshipTypeHandlerName)
        return dbRelationshipType.getCdbObject()

    @CdbDbApi.executeQuery
    def getRelationshipTypeByName(self, name, **kwargs):
        """
        Get an item relationship type record by its name.

        :param name:
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbRelationshipType = self.relationshipTypeHandler.getRelationshipTypeByName(
            session, name)
        return dbRelationshipType.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItem(self,
                domainName,
                name,
                createdByUserId,
                ownerUserId,
                ownerGroupId,
                itemProjectName,
                itemIdentifier1=None,
                itemIdentifier2=None,
                qrId=None,
                description=None,
                isGroupWriteable=True,
                createdOnDataTime=None,
                lastModifiedOnDateTime=None,
                derivedFromItemId=None,
                entityTypeNames=None,
                **kwargs):
        """
        Add an item record.

        :param domainName:
        :param name:
        :param createdByUserId:
        :param ownerUserId:
        :param ownerGroupId:
        :param itemIdentifier1:
        :param itemIdentifier2:
        :param qrId:
        :param isGroupWriteable:
        :param createdOnDataTime:
        :param lastModifiedOnDateTime:
        :param derivedFromItemId:
        :param entityTypeNames:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItem = self.itemHandler.addItem(
            session, domainName, name, createdByUserId, ownerUserId,
            ownerGroupId, itemProjectName, itemIdentifier1, itemIdentifier2,
            qrId, description, isGroupWriteable, createdOnDataTime,
            lastModifiedOnDateTime, derivedFromItemId, entityTypeNames)
        return dbItem.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItemElement(self,
                       name,
                       parentItemId,
                       containedItemId,
                       isRequired,
                       description,
                       createdByUserId,
                       ownerUserId,
                       ownerGroupId,
                       isGroupWriteable,
                       createdOnDataTime=None,
                       lastModifiedOnDateTime=None,
                       **kwargs):
        """
        Add an item element record.

        :param name:
        :param parentItemId:
        :param containedItemId:
        :param isRequired:
        :param description:
        :param createdByUserId:
        :param ownerUserId:
        :param ownerGroupId:
        :param isGroupWriteable:
        :param createdOnDataTime:
        :param lastModifiedOnDateTime:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItemElement = self.itemHandler.addItemElement(
            session, name, parentItemId, containedItemId, isRequired,
            description, createdByUserId, ownerUserId, ownerGroupId,
            isGroupWriteable, createdOnDataTime, lastModifiedOnDateTime)
        return dbItemElement.getCdbObject()

    @CdbDbApi.executeTransaction
    def updateItemElement(self,
                          itemElementId,
                          lastModifiedUserId,
                          containedItemId=-1,
                          isRequired=-1,
                          name=None,
                          description=None,
                          ownerUserId=None,
                          ownerGroupId=None,
                          isGroupWriteable=None,
                          **kwargs):
        """
        Update an item element record.

        :param itemElementId:
        :param lastModifiedUserId:
        :param containedItemId:
        :param isRequired:
        :param name:
        :param description:
        :param ownerUserId:
        :param ownerGroupId:
        :param isGroupWriteable:
        :return:
        """

        session = kwargs['session']
        dbItemElement = self.itemHandler.updateItemElement(
            session, itemElementId, lastModifiedUserId, containedItemId,
            isRequired, name, description, ownerUserId, ownerGroupId,
            isGroupWriteable)

        return dbItemElement.getCdbObject()

    @CdbDbApi.executeQuery
    def getItemById(self, itemId, **kwargs):
        """
        Get an item record by its id.

        :param itemId:
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbItem = self.itemHandler.getItemById(session, itemId)
        return dbItem.getCdbObject()

    @CdbDbApi.executeQuery
    def getItemByQrId(self, itemQrId, **kwargs):
        """
        Get an item record by its id.

        :param itemQrId:
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbItem = self.itemHandler.getItemByQrId(session, itemQrId)
        return dbItem.getCdbObject()

    @CdbDbApi.executeQuery
    def getItemByUniqueAttributes(self, domainId, name, itemIdentifier1,
                                  itemIdentifier2, derivedFromItemId,
                                  **kwargs):
        """
        Get an item record based on its unique attributes.

        :param domainId:
        :param name:
        :param itemIdentifier1:
        :param itemIdentifier2:
        :param derivedFromItemId:
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbItem = self.itemHandler.getItemByUniqueAttributes(
            session, domainId, name, itemIdentifier1, itemIdentifier2,
            derivedFromItemId)
        return dbItem.getCdbObject()

    @CdbDbApi.executeQuery
    def getItemElementsByItemId(self, itemId, **kwargs):
        """
        Get a list of item elements for a particular item.

        :param itemId:
        :param kwargs:
        :return: CdbObject List of item elements of a particular item.
        """
        session = kwargs['session']
        dbItemElements = self.itemHandler.getItemElementsByItemId(
            session, itemId)
        return self.toCdbObjectList(dbItemElements)

    @CdbDbApi.executeQuery
    def getItemElementById(self, itemElementId, **kwargs):
        """
        Get an item element by its id.

        :param itemElementId:
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbItemElement = self.itemHandler.getItemElementById(
            session, itemElementId)
        return dbItemElement.getCdbObject()

    @CdbDbApi.executeTransaction
    def addSource(self, sourceName, description, contactInfo, url, **kwargs):
        """
        Add a source record.

        Sources are various vendors that various items could be obtained from.

        :param sourceName:
        :param description:
        :param contactInfo:
        :param url:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbSource = self.sourceHandler.addSource(session, sourceName,
                                                description, contactInfo, url)
        return dbSource.getCdbObject()

    @CdbDbApi.executeQuery
    def getSources(self, **kwargs):
        """
        Get all records of sources.

        :param kwargs:
        :return: CDbObject List of sources in the db.
        """
        session = kwargs['session']
        dbSources = self.sourceHandler.getSources(session)
        return self.toCdbObjectList(dbSources)

    @CdbDbApi.executeTransaction
    def addItemSource(self, itemId, sourceName, partNumber, cost, description,
                      isVendor, isManufacturer, contactInfo, url, **kwargs):
        """
        Add an item source record.

        :param itemId:
        :param sourceName:
        :param partNumber:
        :param cost:
        :param description:
        :param isVendor:
        :param isManufacturer:
        :param contactInfo:
        :param url:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """

        session = kwargs['session']
        dbItemSource = self.itemHandler.addItemSource(session, itemId,
                                                      sourceName, partNumber,
                                                      cost, description,
                                                      isVendor, isManufacturer,
                                                      contactInfo, url)
        return dbItemSource.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItemCategory(self, name, description, domainName, **kwargs):
        """
        Add an item category

        items in particular domain could have different categories.

        :param name:
        :param description:
        :param domainName:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItemCategory = self.itemHandler.addItemCategory(
            session, name, description, domainName)
        return dbItemCategory.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItemProject(self, itemProjectName, description, **kwargs):
        """
        Add an item project.

        Items are assigned to projects.

        :param itemProjectName:
        :param description:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItemCategory = self.itemHandler.addItemProject(
            session, itemProjectName, description)
        return dbItemCategory.getCdbObject()

    @CdbDbApi.executeQuery
    def getItemProjects(self, **kwargs):
        """
        Get all item project records in the db.

        :param kwargs:
        :return: CDBObject List of item projects.
        """
        session = kwargs['session']
        dbItemProjects = self.itemHandler.getItemProjects(session)
        return self.toCdbObjectList(dbItemProjects)

    @CdbDbApi.executeTransaction
    def addItemItemProject(self, itemId, itemProjectName, **kwargs):
        """
        Assign an item to a particular project.

        :param itemId:
        :param itemProjectName:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """

        session = kwargs['session']
        dbItemCategory = self.itemHandler.addItemItemProject(session,
                                                             itemProjectName,
                                                             itemId=itemId)
        return dbItemCategory.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItemType(self, name, description, domainName, **kwargs):
        """
        Add an item type record.

        items in particular domain could have different types.

        :param name:
        :param description:
        :param domainName:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItemType = self.itemHandler.addItemType(session, name, description,
                                                  domainName)
        return dbItemType.getCdbObject()

    @CdbDbApi.executeQuery
    def getItemCategory(self, name, **kwargs):
        """
        Get an item category by its name.

        :param name:
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbItemCategory = self.itemHandler.getItemCategoryByName(session, name)
        return dbItemCategory.getCdbObject()

    @CdbDbApi.executeQuery
    def getItemType(self, name, domainName, **kwargs):
        """
        Get an item type by its name and domain name.

        :param name:
        :param domainName:
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbItemType = self.itemHandler.getItemTypeByName(
            session, name, domainName)
        return dbItemType.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItemItemCategory(self, itemId, categoryName, **kwargs):
        """
        Assign an item category to a particular item.

        :param itemId:
        :param categoryName:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItemType = self.itemHandler.addItemItemCategory(
            session, itemId, categoryName)
        return dbItemType.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItemItemType(self, itemId, typeName, **kwargs):
        """
        Assign an item type to a particular item.

        :param itemId:
        :param typeName:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItemType = self.itemHandler.addItemItemType(session, itemId,
                                                      typeName)
        return dbItemType.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItemElementLog(self,
                          itemElementId,
                          text,
                          enteredByUserId,
                          effectiveFromDateTime=None,
                          effectiveToDateTime=None,
                          logTopicName=None,
                          enteredOnDateTime=None,
                          systemLogLevelName=None,
                          **kwargs):
        """
        Add a log to a particular item element.

        NOTE: items have logs through their 'self element'.

        :param itemElementId:
        :param text:
        :param enteredByUserId:
        :param effectiveFromDateTime:
        :param effectiveToDateTime:
        :param logTopicName:
        :param enteredOnDateTime:
        :param systemLogLevelName:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItemElementLog = self.itemHandler.addItemElementLog(
            session, itemElementId, text, enteredByUserId,
            effectiveFromDateTime, effectiveToDateTime, logTopicName,
            enteredOnDateTime, systemLogLevelName)
        return dbItemElementLog.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItemElementProperty(self,
                               itemElementId,
                               propertyTypeName,
                               tag=None,
                               value=None,
                               units=None,
                               description=None,
                               enteredByUserId=None,
                               isUserWriteable=False,
                               isDynamic=False,
                               displayValue=None,
                               targetValue=None,
                               enteredOnDateTime=None,
                               **kwargs):
        """
        Add a property to a particular item element.

        NOTE: items have properties through their 'self element'.

        :param itemElementId:
        :param propertyTypeName:
        :param tag:
        :param value:
        :param units:
        :param description:
        :param enteredByUserId:
        :param isUserWriteable:
        :param isDynamic:
        :param displayValue:
        :param targetValue:
        :param enteredOnDateTime:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItemElementProperty = self.itemHandler.addItemElementProperty(
            session, itemElementId, propertyTypeName, tag, value, units,
            description, enteredByUserId, isUserWriteable, isDynamic,
            displayValue, targetValue, enteredOnDateTime)
        return dbItemElementProperty.getCdbObject()

    @CdbDbApi.executeTransaction
    def addItemElementImageProperty(self, itemElementId, enteredByUserId,
                                    generatedName, fileName, **kwargs):
        """
	    Stores a property value reference to a file an image file stored in the CDB storage directory.
	    
	    :param itemElementId: 
	    :param enteredByUserId: 
	    :param generatedName: 
	    :param fileName: 
	    :param kwargs: 
	    :return: (CdbObject) newly added record.:return: (CdbObject) newly added record.
	    """
        session = kwargs['session']
        dbItemElementProperty = self.itemHandler.addItemElementImageProperty(
            session, itemElementId, enteredByUserId, generatedName, fileName)

        return dbItemElementProperty.getCdbObject()

    @CdbDbApi.executeQuery
    def getAvailableInventoryItemStatuses(self, **kwargs):
        """
        Fetches allowed values for item status property

        :param kwargs:
        :return:
        """
        session = kwargs['session']
        allowedValues = self.itemHandler.getAvailableItemStatuses(session)
        return self.toCdbObjectList(allowedValues)

    @CdbDbApi.executeTransaction
    def updateInventoryItemStatus(self, itemId, statusName, enteredByUserId,
                                  **kwargs):
        """
        Updates the internal property of item status

        :param itemId:
        :param statusName:
        :param kwargs:
        :return:
        """
        session = kwargs['session']
        dbPropertyValue = self.itemHandler.updateItemStatus(
            session, itemId, statusName, enteredByUserId)
        return dbPropertyValue.toCdbObject()

    @CdbDbApi.executeQuery
    def getInventoryItemStatus(self, itemId, **kwargs):
        """
        Get the internal property for item status

        :param itemId:
        :param kwargs:
        :return:
        """
        session = kwargs['session']
        dbPropertyValue = self.itemHandler.getItemStatus(session, itemId)
        return dbPropertyValue.toCdbObject()

    @CdbDbApi.executeQuery
    def getSelfElementByItemId(self, itemId, **kwargs):
        """
        Get an item self element by the id of the item.

        :param itemId:
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbItemElement = self.itemHandler.getSelfElementByItemId(
            session, itemId)
        return dbItemElement.getCdbObject()

    @CdbDbApi.executeQuery
    def getFirstItemElementRelationshipList(self, relationshipTypeName,
                                            itemElementId, **kwargs):
        """
        Fetches a list of relationships for item element listed as first_item_element in the relationship table.

        :param relationshipTypeName:
        :param itemElementId:
        :return:
        """
        session = kwargs['session']

        dbItemElementRelationshipList = self.itemHandler.getItemElementRelationshipListByRelationshipTypeNameAndFirstItemElementId(
            session, relationshipTypeName, itemElementId)
        return self.toCdbObjectList(dbItemElementRelationshipList)

    @CdbDbApi.executeTransaction
    def addValidItemElementRelationship(self,
                                        firstItemElementId,
                                        secondItemElementId,
                                        relationshipTypeName,
                                        enteredByUserId,
                                        relationshipDetails=None,
                                        description=None,
                                        **kwargs):
        """
        Add a simple item element relationship with checks. (To be used from the web service)

        :param firstItemElementId:
        :param secondItemElementId:
        :param relationshipTypeName:
        :param description:
        :param kwargs:
        :return:
        """
        session = kwargs['session']

        dbItemElementRelationship = self.itemHandler.addValidItemElementRelationship(
            session, firstItemElementId, secondItemElementId,
            relationshipTypeName, enteredByUserId, relationshipDetails,
            description)

        return dbItemElementRelationship.toCdbObject()

    @CdbDbApi.executeTransaction
    def addItemElementRelationship(self, firstItemElementId,
                                   secondItemElementId, firstItemConnectorId,
                                   secondItemConnectorId, linkItemElementId,
                                   relationshipTypeName, relationshipDetails,
                                   resourceTypeName, label, description,
                                   **kwargs):
        """
        Add an item element relationship. Unrestricted to be used only by the developer.

        :param firstItemElementId:
        :param secondItemElementId:
        :param firstItemConnectorId:
        :param secondItemConnectorId:
        :param linkItemElementId:
        :param relationshipTypeName:
        :param relationshipDetails:
        :param resourceTypeName:
        :param label:
        :param description:
        :param kwargs:
        :return: (CdbObject) newly added record.
        """
        session = kwargs['session']
        dbItemElementRelationship = self.itemHandler.addItemElementRelationship(
            session, firstItemElementId, secondItemElementId,
            firstItemConnectorId, secondItemConnectorId, linkItemElementId,
            relationshipTypeName, relationshipDetails, resourceTypeName, label,
            description)
        return dbItemElementRelationship.toCdbObject()

    @CdbDbApi.executeQuery
    def getItemsWithPropertyType(self,
                                 propertyTypeName,
                                 itemDomainName=None,
                                 itemDerivedFromItemId=None,
                                 propertyValueMatch=None,
                                 **kwargs):
        """
        Fetches items that have a particular property type.

        :param propertyTypeName:
        :param itemDomainName:
        :param itemDerivedFromItemId:
        :param propertyValueMatch:
        :param kwargs:
        :return: (CdbObject) resulting record.
        """
        session = kwargs['session']
        dbItems = self.itemHandler.getItemsWithPropertyTypeName(
            session, propertyTypeName, itemDomainName, itemDerivedFromItemId,
            propertyValueMatch)
        return self.toCdbObjectList(dbItems)

    @CdbDbApi.executeQuery
    def getParentItems(self, itemId, **kwargs):
        """
        Fetches a list of items who contained the item specified as input.

        :param itemId:
        :param kwargs:
        :return:
        """
        session = kwargs['session']
        dbItems = self.itemHandler.getParentItems(session, itemId)
        return self.toCdbObjectList(dbItems)
Esempio n. 7
0
class ItemHandler(CdbDbEntityHandler):

    CDB_ADMIN_GROUP_NAME = 'CDB_ADMIN'

    def __init__(self):
        CdbDbEntityHandler.__init__(self)
        self.entityInfoHandler = EntityInfoHandler()
        self.domainHandler = DomainHandler()
        self.entityTypeHandler = EntityTypeHandler()
        self.sourceHandler = SourceHandler()
        self.logHandler = LogHandler()
        self.propertyValueHandler = PropertyValueHandler()
        self.relationshipTypeHandler = RelationshipTypeHandler()
        self.resourceTypeHandler = ResourceTypeHandler()
        self.userInfoHandler = UserInfoHandler()

    def verifyPermissionsForWriteToItemElement(self,
                                               session,
                                               userId,
                                               itemElementId=None,
                                               dbItemElementObject=None):
        if dbItemElementObject is None and itemElementId is None:
            raise InvalidArgument(
                "At least the item element id or item element object must be provided."
            )
        if dbItemElementObject is None:
            dbItemElementObject = self.getItemElementById(
                session, itemElementId)
        else:
            itemElementId = dbItemElementObject.id
        dbUserInfo = self.userInfoHandler.getUserInfoById(session, userId)

        dbEntityInfo = dbItemElementObject.entityInfo
        ownerUserId = dbEntityInfo.ownerUserInfo.id

        if ownerUserId == userId:
            return True

        ownerGroupWriteable = dbEntityInfo.is_group_writeable
        ownerUserGroupId = dbEntityInfo.ownerUserGroup.id
        for userGroup in dbUserInfo.userGroupList:
            if ownerGroupWriteable:
                if ownerUserGroupId == userGroup.id:
                    return True
            if userGroup.name == self.CDB_ADMIN_GROUP_NAME:
                return True

        raise InvalidSession(
            "User %s does not have permissions to modify item element %s" %
            (userId, itemElementId))

    def getItemById(self, session, id):
        return self._findDbObjById(session, Item, id)

    def getItemByQrId(self, session, qrId):
        entityDisplayName = self._getEntityDisplayName(Item)

        try:
            dbItem = session.query(Item).filter(Item.qr_id == qrId).one()
            return dbItem
        except NoResultFound as ex:
            raise ObjectNotFound('No %s with QR-Id: %s found.' %
                                 (entityDisplayName, qrId))

    def getItemElementsByName(self, session, name):
        return self._findDbObjByName(session, ItemElement, name)

    def getItemElementById(self, session, id):
        return self._findDbObjById(session, ItemElement, id)

    def getItemElementsByItemId(self, session, itemId):
        entityDisplayName = self._getEntityDisplayName(ItemCategory)

        try:
            dbItemElements = session.query(ItemElement).filter(
                ItemElement.parent_item_id == itemId).all()
            return dbItemElements
        except NoResultFound as ex:
            raise ObjectNotFound('No %s with item id: %s found.' %
                                 (entityDisplayName, itemId))

    def addItemCategory(self, session, itemCategoryName, description,
                        domainName):
        entityDisplayName = self._getEntityDisplayName(ItemCategory)

        self.logger.debug('Adding %s %s' %
                          (entityDisplayName, itemCategoryName))

        dbDomain = self.domainHandler.findDomainByName(session, domainName)

        try:
            self.getItemCategoryByName(session, itemCategoryName, dbDomain.id)
            raise ObjectAlreadyExists(
                '%s %s for domain %s already exists.' %
                (entityDisplayName, itemCategoryName, dbDomain.name))
        except ObjectNotFound as ex:
            # ok
            pass

        # Create Entity Db Object
        dbItemCategory = ItemCategory(name=itemCategoryName)
        if description:
            dbItemCategory.description = description

        dbItemCategory.domain = dbDomain

        session.add(dbItemCategory)
        session.flush()

        self.logger.debug('Inserted %s id %s' %
                          (entityDisplayName, dbItemCategory.id))
        return dbItemCategory

    def addItemProject(self, session, itemProjectName, description):
        return self._addSimpleNameDescriptionTable(session, ItemProject,
                                                   itemProjectName,
                                                   description)

    def getItemProjects(self, session):
        self.logger.debug('Retrieving item projects.')
        dbItemProjects = session.query(ItemProject).all()
        return dbItemProjects

    def addItemType(self, session, itemTypeName, description, domainName):
        entityDisplayName = self._getEntityDisplayName(ItemType)

        self.logger.debug('Adding %s %s' % (entityDisplayName, itemTypeName))

        dbDomain = self.domainHandler.findDomainByName(session, domainName)

        try:
            self.getItemTypeByName(session, itemTypeName, dbDomain.id)
            raise ObjectAlreadyExists(
                '%s %s for domain %s already exists.' %
                (entityDisplayName, itemTypeName, dbDomain.name))
        except ObjectNotFound as ex:
            # ok
            pass

        # Create Entity Db Object
        dbItemType = ItemType(name=itemTypeName)
        if description:
            dbItemType.description = description

        dbItemType.domain = dbDomain

        session.add(dbItemType)
        session.flush()

        self.logger.debug('Inserted %s id %s' %
                          (entityDisplayName, dbItemType.id))
        return dbItemType

    def getItemCategoryByName(self, session, name, domainId):
        entityDisplayName = self._getEntityDisplayName(ItemCategory)

        try:
            dbItem = session.query(ItemCategory).filter(ItemCategory.name==name)\
                .filter(ItemCategory.domain_id == domainId).one()
            return dbItem
        except NoResultFound as ex:
            raise ObjectNotFound('No %s with name: %s, domain id: %s exists.' %
                                 (entityDisplayName, name, domainId))

    def getItemProjectByName(self, session, itemProjectName):
        return self._findDbObjByName(session, ItemProject, itemProjectName)

    def getItemTypeByName(self, session, name, domainId):
        entityDisplayName = self._getEntityDisplayName(ItemType)

        try:
            dbItem = session.query(ItemType).filter(ItemType.name==name)\
                .filter(ItemType.domain_id == domainId).one()
            return dbItem
        except NoResultFound as ex:
            raise ObjectNotFound('No %s with name: %s, domain id: %s exists.' %
                                 (entityDisplayName, name, domainId))

    def getItemConnectorById(self, session, id):
        return self._findDbObjById(session, ItemConnector, id)

    def getItemElementRelationshipById(self, session, id):
        return self._findDbObjById(session, ItemElementRelationship, id)

    def getItemByUniqueAttributes(self, session, domainId, name,
                                  itemIdentifier1, itemIdentifier2,
                                  derivedFromItemId):
        entityDisplayName = self._getEntityDisplayName(Item)

        try:
            dbItem = session.query(Item).filter(Item.domain_id==domainId)\
                .filter(Item.name==name)\
                .filter(Item.item_identifier1==itemIdentifier1)\
                .filter(Item.item_identifier2==itemIdentifier2)\
                .filter(Item.derived_from_item_id==derivedFromItemId).one()
            return dbItem
        except NoResultFound as ex:
            raise ObjectNotFound(
                'No %s with name: %s, item identifier 1: %s, item identifier 2: %s in domain id %s exists.'
                % (entityDisplayName, name, itemIdentifier1, itemIdentifier1,
                   domainId))

    def addItem(self,
                session,
                domainName,
                name,
                derivedFromItemId,
                itemIdentifier1,
                itemIdentifier2,
                entityTypeNames,
                qrId,
                description,
                createdByUserId,
                ownerUserId,
                ownerGroupId,
                isGroupWriteable,
                createdOnDataTime=None,
                lastModifiedOnDateTime=None):

        dbItems = session.query(Item).filter(Item.name == name).all()
        for item in dbItems:
            if item.item_identifier1 == itemIdentifier1 \
                        and item.item_identifier2 == itemIdentifier2 \
                        and item.domain.name == domainName \
                        and item.derived_from_item_id == derivedFromItemId:
                raise ObjectAlreadyExists('Item with name %s already exists.' %
                                          name)

        # Create entity info
        entityInfoArgs = (createdByUserId, ownerUserId, ownerGroupId,
                          isGroupWriteable, createdOnDataTime,
                          lastModifiedOnDateTime)

        # Create item
        dbItem = Item(name=name)
        dbItem.domain = self.domainHandler.findDomainByName(
            session, domainName)
        dbItem.derived_from_item_id = derivedFromItemId
        dbItem.qr_id = qrId
        dbItem.item_identifier1 = itemIdentifier1
        dbItem.item_identifier2 = itemIdentifier2

        session.add(dbItem)
        session.flush()

        # Add self element
        self.addItemElement(session, None, dbItem.id, None, False, description,
                            *entityInfoArgs)

        self.logger.debug('Inserted item id %s' % dbItem.id)
        if entityTypeNames is not None:
            if type(entityTypeNames) is list:
                for entityTypeName in entityTypeNames:
                    self.addItemEntityType(session, None, entityTypeName,
                                           dbItem)
            elif type(entityTypeNames) is str:
                self.addItemEntityType(session, None, entityTypeNames, dbItem)

        return dbItem

    def getSelfElementByItemId(self, session, itemId):
        entityDisplayName = self._getEntityDisplayName(ItemElement)
        try:
            dbItemElement = session.query(ItemElement)\
                .filter(ItemElement.parent_item_id==itemId)\
                .filter(ItemElement.name==None)\
                .filter(ItemElement.derived_from_item_element_id==None).one()
            return dbItemElement
        except NoResultFound as ex:
            raise ObjectNotFound('No %s with id %s exists.' %
                                 (entityDisplayName, id))

    def getItemsOfDomain(self, session, domainName):
        entityDisplayName = self._getEntityDisplayName(Item)
        try:
            query = session.query(Item).join(Domain)
            query = query.filter(Domain.name == domainName)

            dbItems = query.all()
            return dbItems

        except NoResultFound as ex:
            raise ObjectNotFound("No %ss with domain %s found." %
                                 (entityDisplayName, domainName))

    def getItemsDerivedFromItem(self, session, derivedItemId):
        entityDisplayName = self._getEntityDisplayName(Item)

        try:
            query = session.query(Item).join(Domain)
            query = query.filter(Item.derived_from_item_id == derivedItemId)

            dbItems = query.all()
            return dbItems
        except NoResultFound as ex:
            raise ObjectNotFound("No %ss derived from item id %s found." %
                                 (entityDisplayName, derivedItemId))

    def getItemsWithPropertyTypeName(self,
                                     session,
                                     propertyTypeName,
                                     itemDomainName=None,
                                     itemDerivedFromItemId=None,
                                     propertyValueMatch=None):
        entityDisplayName = self._getEntityDisplayName(Item)
        try:
            query = session.query(Item)\
                .join(ItemElement.parentItem)\
                .join(ItemElementProperty)\
                .join(PropertyValue)\
                .join(PropertyType)\
                .filter(PropertyType.name == propertyTypeName)

            if itemDerivedFromItemId is not None:
                query = query.filter(
                    Item.derived_from_item_id == itemDerivedFromItemId)

            if propertyValueMatch is not None:
                query = query.filter(PropertyValue.value == propertyValueMatch)

            if itemDomainName is not None:
                query = query.join(Domain)
                query = query.filter(Domain.name == itemDomainName)

            dbItems = query.all()
            return dbItems

        except NoResultFound as ex:
            raise ObjectNotFound("No %ss with property type %s found." %
                                 (entityDisplayName, propertyTypeName))

    def addItemEntityType(self, session, itemId, entityTypeName, item=None):
        dbItemEntityType = ItemEntityType()

        if item:
            dbItemEntityType.item = item
        else:
            dbItemEntityType.item = self.getItemById(session, itemId)

        dbItemEntityType.entityType = self.entityTypeHandler.findEntityTypeByName(
            session, entityTypeName)

        session.add(dbItemEntityType)
        session.flush()

        self.logger.debug('Inserted Item Entity Type for item id %s' %
                          dbItemEntityType.item.id)

        return dbItemEntityType

    def addItemElement(self,
                       session,
                       name,
                       parentItemId,
                       containedItemId,
                       isRequired,
                       description,
                       createdByUserId,
                       ownerUserId,
                       ownerGroupId,
                       isGroupWriteable,
                       createdOnDataTime=None,
                       lastModifiedOnDateTime=None):
        dbItemElements = session.query(ItemElement).filter(
            ItemElement.name == name).all()
        for element in dbItemElements:
            if element.parent_item_id == parentItemId and element.name == name:
                raise ObjectAlreadyExists(
                    'Item Element with name %s already exists.' % name)

        parentSelfElement = self.getSelfElementByItemId(session, parentItemId)
        self.verifyPermissionsForWriteToItemElement(
            session, createdByUserId, dbItemElementObject=parentSelfElement)

        # Create entity info
        dbEntityInfo = self.entityInfoHandler.createEntityInfo(
            session, createdByUserId, ownerUserId, ownerGroupId,
            isGroupWriteable, createdOnDataTime, lastModifiedOnDateTime)

        # Create item
        dbItemElement = ItemElement(name=name, description=description)
        dbItemElement.entityInfo = dbEntityInfo
        if parentItemId:
            dbItemElement.parentItem = self.getItemById(session, parentItemId)
        if containedItemId:
            dbItemElement.containedItem = self.getItemById(
                session, containedItemId)

        entityInfo = parentSelfElement.entityInfo
        parentSelfElement.entityInfo = self.entityInfoHandler.updateEntityInfo(
            session, entityInfo, createdByUserId)

        session.add(parentSelfElement)
        session.add(dbItemElement)
        session.flush()
        self.logger.debug('Inserted item Element id %s' % dbItemElement.id)

        return dbItemElement

    def addItemSource(self, session, itemId, sourceName, partNumber, cost,
                      description, isVendor, isManufacturer, contactInfo, url):
        dbItem = self.getItemById(session, itemId)
        dbSource = self.sourceHandler.findSourceByName(session, sourceName)

        dbItemSource = ItemSource()
        dbItemSource.item = dbItem
        dbItemSource.source = dbSource
        if partNumber:
            dbItemSource.part_number = partNumber
        if cost:
            dbItemSource.cost = cost
        if description:
            dbItemSource.description = description
        if isVendor:
            dbItemSource.is_vendor = isVendor
        if isManufacturer:
            dbItemSource.is_manufacturer = isManufacturer
        if contactInfo:
            dbItemSource.contact_info = contactInfo
        if url:
            dbItemSource.url = url

        session.add(dbItemSource)
        session.flush()
        self.logger.debug('Inserted item source %s' % dbItemSource.id)

        return dbItemSource

    def addItemItemCategory(self, session, itemId, itemCategoryName):
        dbItem = self.getItemById(session, itemId)
        domainId = dbItem.domain.id

        dbCategory = self.getItemCategoryByName(session, itemCategoryName,
                                                domainId)

        dbItemItemCategory = ItemItemCategory()
        dbItemItemCategory.item = dbItem
        dbItemItemCategory.category = dbCategory

        session.add(dbItemItemCategory)
        session.flush()

        self.logger.debug('Added category %s for item id %s' %
                          (itemCategoryName, itemId))

        return dbItemItemCategory

    def addItemItemProject(self, session, itemId, itemProjectName):
        dbItem = self.getItemById(session, itemId)

        dbProject = self.getItemProjectByName(session, itemProjectName)

        dbItemItemProject = ItemItemProject()
        dbItemItemProject.item = dbItem
        dbItemItemProject.project = dbProject

        session.add(dbItemItemProject)
        session.flush()

        self.logger.debug('Added category %s for item id %s' %
                          (itemProjectName, itemId))

        return dbItemItemProject

    def addItemItemType(self, session, itemId, itemTypeName):
        dbItem = self.getItemById(session, itemId)
        domainId = dbItem.domain.id

        dbType = self.getItemTypeByName(session, itemTypeName, domainId)

        dbItemItemType = ItemItemType()
        dbItemItemType.item = dbItem
        dbItemItemType.type = dbType

        session.add(dbItemItemType)

        session.flush()
        self.logger.debug('Added type %s for item id %s' %
                          (itemTypeName, itemId))
        return dbItemItemType

    def addItemElementLog(self,
                          session,
                          itemElementId,
                          text,
                          enteredByUserId,
                          effectiveFromDateTime,
                          effectiveToDateTime,
                          logTopicName,
                          enteredOnDateTime=None,
                          systemLogLevelName=None):
        dbItemElement = self.getItemElementById(session, itemElementId)
        self.verifyPermissionsForWriteToItemElement(
            session, enteredByUserId, dbItemElementObject=dbItemElement)
        dbLog = self.logHandler.addLog(session, text, enteredByUserId,
                                       effectiveFromDateTime,
                                       effectiveToDateTime, logTopicName,
                                       enteredOnDateTime)

        if systemLogLevelName is not None:
            self.logHandler.addSystemLog(session, dbLog, systemLogLevelName)

        dbItemElementLog = ItemElementLog()
        dbItemElementLog.itemElement = dbItemElement
        dbItemElementLog.log = dbLog

        entityInfo = dbItemElement.entityInfo
        dbItemElement.entityInfo = self.entityInfoHandler.updateEntityInfo(
            session, entityInfo, enteredByUserId)

        session.add(dbItemElement)
        session.add(dbItemElementLog)
        session.flush()
        self.logger.debug('Added log for itemElement id %s' % (itemElementId))
        return dbItemElementLog

    def addItemElementProperty(self,
                               session,
                               itemElementId,
                               propertyTypeName,
                               tag,
                               value,
                               units,
                               description,
                               enteredByUserId,
                               isUserWriteable,
                               isDynamic,
                               displayValue,
                               targetValue,
                               enteredOnDateTime=None):
        dbItemElement = self.getItemElementById(session, itemElementId)
        self.verifyPermissionsForWriteToItemElement(
            session, enteredByUserId, dbItemElementObject=dbItemElement)
        dbPropertyValue = self.propertyValueHandler.createPropertyValue(
            session, propertyTypeName, tag, value, units, description,
            enteredByUserId, isUserWriteable, isDynamic, displayValue,
            targetValue, enteredOnDateTime)

        session.add(dbPropertyValue)

        dbItemElementProperty = ItemElementProperty()
        dbItemElementProperty.itemElement = dbItemElement
        dbItemElementProperty.propertyValue = dbPropertyValue

        entityInfo = dbItemElement.entityInfo
        dbItemElement.entityInfo = self.entityInfoHandler.updateEntityInfo(
            session, entityInfo, enteredByUserId)

        session.add(dbItemElement)
        session.add(dbItemElementProperty)

        session.flush()

        self.logger.debug(
            'Added property value (type: %s) for item element id %s' %
            (propertyTypeName, itemElementId))
        return dbItemElementProperty

    def addItemElementRelationship(self, session, firstItemElementId,
                                   secondItemElementId, firstItemConnectorId,
                                   secondItemConnectorId, linkItemElementId,
                                   relationshipTypeName, relationshipDetails,
                                   resourceTypeName, label, description):
        if firstItemElementId is None:
            raise InvalidArgument(
                "First item element Id must be specified for a item element relationship"
            )

        firstItemElement = self.getItemElementById(session, firstItemElementId)

        dbItemElementRelationship = ItemElementRelationship()
        dbItemElementRelationship.firstItemElement = firstItemElement

        if secondItemElementId is not None:
            secondItemElement = self.getItemElementById(
                session, secondItemElementId)
            dbItemElementRelationship.secondItemElement = secondItemElement

        relationshipType = self.relationshipTypeHandler.getRelationshipTypeByName(
            session, relationshipTypeName)
        dbItemElementRelationship.relationshipType = relationshipType
        dbItemElementRelationship.relationship_details = relationshipDetails
        dbItemElementRelationship.label = label
        dbItemElementRelationship.description = description

        if firstItemConnectorId:
            dbItemElementRelationship.firstItemConnector = self.getItemConnectorById(
                firstItemConnectorId)
        if secondItemConnectorId:
            dbItemElementRelationship.secondItemConnector = self.getItemConnectorById(
                secondItemConnectorId)
        if linkItemElementId:
            dbItemElementRelationship.linkItemElement = self.getItemElementById(
                linkItemElementId)
        if resourceTypeName:
            dbItemElementRelationship.resourceType = self.resourceTypeHandler.getResourceTypeByName(
                session, resourceTypeName)

        session.add(dbItemElementRelationship)
        session.flush()

        entityDisplayName = self._getEntityDisplayName(ItemElementRelationship)
        self.logger.debug('Inserted %s %s' %
                          (entityDisplayName, dbItemElementRelationship.id))

        return dbItemElementRelationship

    def addItemElementRelationshipHistory(
            self, session, itemRelationshipId, firstItemElementId,
            secondItemElementId, firstItemConnectorId, secondItemConnectorId,
            linkItemElementId, relationshipDetails, resourceTypeName, label,
            description, enteredByUserId, enteredOnDateTime):
        firstItemElement = self.getItemElementById(session, firstItemElementId)
        secondItemElement = self.getItemElementById(session,
                                                    secondItemElementId)
        dbItemElementRelationship = self.getItemElementRelationshipById(
            session, itemRelationshipId)

        dbItemElementRelationshipHistory = ItemElementRelationshipHistory()
        dbItemElementRelationshipHistory.firstItemElement = firstItemElement
        dbItemElementRelationshipHistory.secondItemElement = secondItemElement
        dbItemElementRelationshipHistory.itemElementRelationship = dbItemElementRelationship
        dbItemElementRelationshipHistory.relationship_details = relationshipDetails
        dbItemElementRelationshipHistory.label = label
        dbItemElementRelationshipHistory.description = description
        dbItemElementRelationshipHistory.enteredByUserInfo = self.userInfoHandler.getUserInfoById(
            session, enteredByUserId)
        dbItemElementRelationshipHistory.entered_on_date_time = enteredOnDateTime

        if firstItemConnectorId:
            dbItemElementRelationshipHistory.firstItemConnector = self.getItemConnectorById(
                firstItemConnectorId)
        if secondItemConnectorId:
            dbItemElementRelationshipHistory.secondItemConnector = self.getItemConnectorById(
                secondItemConnectorId)
        if linkItemElementId:
            dbItemElementRelationshipHistory.linkItemElement = self.getItemElementById(
                linkItemElementId)
        if resourceTypeName:
            dbItemElementRelationshipHistory.resourceType = self.resourceTypeHandler.getResourceTypeByName(
                session, resourceTypeName)

        session.add(dbItemElementRelationshipHistory)
        session.flush()

        entityDisplayName = self._getEntityDisplayName(
            ItemElementRelationshipHistory)
        self.logger.debug(
            'Inserted %s %s' %
            (entityDisplayName, dbItemElementRelationshipHistory.id))

        return dbItemElementRelationshipHistory
Esempio n. 8
0
 def __init__(self):
     CdbDbEntityHandler.__init__(self)
     self.entityTypeHandler = EntityTypeHandler()