コード例 #1
0
def importAndCompareModelType(model, url, user, modelType):
    import threading
    from girderformindlogger.utility import firstLower

    if model is None:
        return (None, None)
    mt = model.get('@type', '')
    mt = mt[0] if isinstance(mt, list) else mt
    atType = mt.split('/')[-1].split(':')[-1]
    modelType = firstLower(atType) if len(atType) else modelType
    modelType = 'screen' if modelType.lower(
    ) == 'field' else 'protocol' if modelType.lower(
    ) == 'activityset' else modelType
    changedModel = ((atType != modelType and len(atType))
                    or (" " in modelType))
    modelType = firstLower(atType) if changedModel else modelType
    modelType = 'screen' if modelType.lower(
    ) == 'field' else 'protocol' if modelType.lower(
    ) == 'activityset' else modelType
    modelClass = MODELS()[modelType]()
    prefName = modelClass.preferredName(model)
    cachedDocObj = {}
    model = expand(url)
    print("Loaded {}".format(": ".join([modelType, prefName])))
    docCollection = getModelCollection(modelType)
    if modelClass.name in ['folder', 'item']:
        docFolder = FolderModel().createFolder(
            name=prefName,
            parent=docCollection,
            parentType='collection',
            public=True,
            creator=user,
            allowRename=True,
            reuseExisting=(modelType != 'applet'))
        if modelClass.name == 'folder':
            newModel = modelClass.setMetadata(
                docFolder,
                {modelType: {
                    **model, 'schema:url': url,
                    'url': url
                }})
        elif modelClass.name == 'item':
            newModel = modelClass.setMetadata(
                modelClass.createItem(name=prefName if prefName else str(
                    len(
                        list(FolderModel().childItems(FolderModel().load(
                            docFolder, level=None, user=user, force=True)))) +
                    1),
                                      creator=user,
                                      folder=docFolder,
                                      reuseExisting=True),
                {modelType: {
                    **model, 'schema:url': url,
                    'url': url
                }})
    formatted = _fixUpFormat(
        formatLdObject(newModel,
                       mesoPrefix=modelType,
                       user=user,
                       refreshCache=True))
    createCache(newModel, formatted, modelType, user)
    return (formatted, modelType)
コード例 #2
0
def loadFromSingleFile(document, user):
    if 'protocol' not in document or 'data' not in document['protocol']:
        raise ValidationException(
            'should contain protocol field in the json file.', )
    if 'activities' not in document['protocol']:
        raise ValidationException(
            'should contain activities field in the json file.', )

    contexts = document.get('contexts', {})

    protocol = {'protocol': {}, 'activity': {}, 'screen': {}}

    expandedProtocol = expandObj(contexts, document['protocol']['data'])
    protocol['protocol'][expandedProtocol['@id']] = {
        'expanded': expandedProtocol
    }

    protocolId = None
    for activity in document['protocol']['activities'].values():
        expandedActivity = expandObj(contexts, activity['data'])
        protocol['activity'][expandedActivity['@id']] = {
            'parentKey': 'protocol',
            'parentId': expandedProtocol['@id'],
            'expanded': expandedActivity
        }

        if 'items' not in activity:
            raise ValidationException(
                'should contain at least one item in each activity.', )

        for item in activity['items'].values():
            expandedItem = expandObj(contexts, item)
            protocol['screen'][expandedItem['@id']] = {
                'parentKey': 'activity',
                'parentId': expandedActivity['@id'],
                'expanded': expandedItem
            }

    for modelType in ['protocol', 'activity', 'screen']:
        modelClass = MODELS()[modelType]()
        docCollection = getModelCollection(modelType)

        for model in protocol[modelType].values():
            prefName = modelClass.preferredName(model['expanded'])

            if modelClass.name in ['folder', 'item']:
                docFolder = FolderModel().createFolder(
                    name=prefName,
                    parent=docCollection,
                    parentType='collection',
                    public=True,
                    creator=user,
                    allowRename=True,
                    reuseExisting=(modelType != 'applet'))

                metadata = {modelType: model['expanded']}

                tmp = model
                while tmp.get('parentId', None):
                    key = tmp['parentKey']
                    tmp = protocol[key][tmp['parentId']]
                    metadata['{}Id'.format(key)] = '{}/{}'.format(
                        MODELS()[key]().name, tmp['_id'])

                if modelClass.name == 'folder':
                    newModel = modelClass.setMetadata(docFolder, metadata)
                elif modelClass.name == 'item':
                    newModel = modelClass.setMetadata(
                        modelClass.createItem(
                            name=prefName if prefName else str(
                                len(
                                    list(FolderModel().childItems(
                                        FolderModel().load(docFolder,
                                                           level=None,
                                                           user=user,
                                                           force=True)))) + 1),
                            creator=user,
                            folder=docFolder,
                            reuseExisting=True), metadata)

                # we don't need this in the future because we will only using single-file-format
                modelClass.update({'_id': newModel['_id']},
                                  {'$set': {
                                      'loadedFromSingleFile': True
                                  }})
                if modelType != 'protocol':
                    formatted = _fixUpFormat(
                        formatLdObject(newModel,
                                       mesoPrefix=modelType,
                                       user=user,
                                       refreshCache=False))

                    createCache(newModel, formatted, modelType, user)
                model['_id'] = newModel['_id']

                if modelType == 'protocol':
                    protocolId = newModel['_id']

    return formatLdObject(ProtocolModel().load(protocolId, force=True),
                          mesoPrefix='protocol',
                          user=user,
                          refreshCache=False)