예제 #1
0
def getReferenceValue(parent, field, value, fd, nameLists, userInfo):
    if 'pickObjectPath' in fd:
        pickObjectPath = fd['pickObjectPath'];
        if pickObjectPath.startswith("parent") and pickObjectPath[6] in ">:=<":
            pickObjectPath = "#"+parent.parent.id+pickObjectPath[6:];
    else:
        pickObjectPath = fd['ofKindID']
        
    # append a qualifier for the specified text to the pickObjectPath
    if 'ofKindID' in fd:
        type = Instance.objects.get(pk=fd['ofKindID'])
    else:
        l = pathparser.selectAllObjects(pickObjectPath, userInfo=userInfo, securityFilter=userInfo.findFilter)
        type = l[0].typeID
        
    verbs = list(filter(lambda verb: verb[2] == terms.textEnum or verb[2] == terms.firstTextEnum, nameLists.getNameUUIDs(type)))
    
    field, dataType, descriptorType = verbs[0]
    if isTranslationField(fd):
        languageCode, text = parseTranslation(value)
    else:
        text = value
    pickObjectPath += '[' + field.getDescription() + '="' + text + '"]'
    
    l = pathparser.selectAllObjects(pickObjectPath, userInfo=userInfo, securityFilter=userInfo.findFilter)
    if len(l):
        return l[0]
    else:
        raise RuntimeError("Unrecognized Reference Value in %s: %s(%s)" % (str(parent), str(field), value))
예제 #2
0
def showPathway(request, email):
    LogRecord.emit(request.user, 'pathAdvisor/showPathway', email)
    
    template = loader.get_template('consentrecords/userHome.html')
    args = {
        'user': request.user,
        'backURL': '/',
    }
    
    if request.user.is_authenticated():
        user = Instance.getUserInstance(request.user)
        if not user:
            return HttpResponse("user is not set up: %s" % request.user.get_full_name())
        args['userID'] = user.id
        
    if settings.FACEBOOK_SHOW:
        args['facebookIntegration'] = True
    
    containerPath = '_user[_email=%s]' % email
    userInfo = UserInfo(request.user)
    objs = pathparser.selectAllObjects(containerPath, userInfo=userInfo, securityFilter=userInfo.findFilter)
    if len(objs) > 0:
        args['state'] = 'pathway%s' % objs[0].id

    context = RequestContext(request, args)
        
    return HttpResponse(template.render(context))
예제 #3
0
    def deleteInstances(user, data):
        try:
            path = data.get('path', None)

            if path:
                # The client time zone offset, stored with the transaction.
                timezoneoffset = data['timezoneoffset']

                with transaction.atomic():
                    transactionState = TransactionState(user, timezoneoffset)
                    descriptionCache = []
                    nameLists = NameList()
                    userInfo = UserInfo(user)
                    for uuObject in pathparser.selectAllObjects(
                            path,
                            userInfo=userInfo,
                            securityFilter=userInfo.administerFilter):
                        if uuObject.parent:
                            raise RuntimeError(
                                "can only delete root instances directly")
                        uuObject.deleteOriginalReference(transactionState)
                        uuObject.deepDelete(transactionState)
            else:
                return JsonResponse({
                    'success': False,
                    'error': "path was not specified in delete"
                })
            results = {'success': True}
        except Exception as e:
            logger = logging.getLogger(__name__)
            logger.error("%s" % traceback.format_exc())
            results = {'success': False, 'error': str(e)}

        return JsonResponse(results)
예제 #4
0
    def getCellData(user, data):
        pathparser.currentTimestamp = datetime.datetime.now()
        try:
            path = data.get('path', None)
        
            if not path:
                return JsonResponse({'success':False, 'error': "path was not specified in getData"})
            
            # The field name for the values to find within the container object
            fieldName = data.get('fieldName', None)
        
            if fieldName is None:
                return JsonResponse({'success':False, 'error': 'the fieldName was not specified'})
            else:
                field = terms[fieldName]
                
            language = data.get('language', None)

            userInfo=UserInfo(user)
            uuObjects = pathparser.selectAllObjects(path=path, userInfo=userInfo, securityFilter=userInfo.readFilter)
            values = uuObjects[0].getReadableSubValues(field, userInfo)
            fieldsDataDictionary = {}
            p = [api._getValueData(v, fieldsDataDictionary, language, userInfo) for v in values]        
        
            results = {'success':True, 'objects': p}
        except Exception as e:
            logger = logging.getLogger(__name__)
            logger.error("%s" % traceback.format_exc())
            logger.error("getData data:%s" % str(data))
            
            results = {'success':False, 'error': str(e)}
        
        return JsonResponse(results)
예제 #5
0
    def selectAll(user, data):
        try:
            path = data.get("path", None)
            start = int(data.get("start", "0"))
            end = int(data.get("end", "0"))
            userInfo = UserInfo(user)
            language = None

            if not path:
                raise ValueError("path was not specified")

            uuObjects = pathparser.selectAllObjects(path, userInfo=userInfo, securityFilter=userInfo.findFilter)\
                            .select_related('description')\
                            .order_by('description__text', 'id')

            if end > 0:
                uuObjects = uuObjects[start:end]
            elif start > 0:
                uuObjects = uuObjects[start:]

            p = [i.getReferenceData(userInfo, language) for i in uuObjects]
            results = {'success': True, 'objects': p}
        except Exception as e:
            logger = logging.getLogger(__name__)
            logger.error("%s" % traceback.format_exc())
            results = {'success': False, 'error': str(e)}

        return JsonResponse(results)
예제 #6
0
 def deleteInstances(user, data):
     try:
         path = data.get('path', None)
     
         if path:
             # The client time zone offset, stored with the transaction.
             timezoneoffset = data['timezoneoffset']
     
             with transaction.atomic():
                 transactionState = TransactionState(user, timezoneoffset)
                 descriptionCache = []
                 nameLists = NameList()
                 userInfo=UserInfo(user)
                 for uuObject in pathparser.selectAllObjects(path, userInfo=userInfo, securityFilter=userInfo.administerFilter):
                     if uuObject.parent:
                         raise RuntimeError("can only delete root instances directly")
                     uuObject.deleteOriginalReference(transactionState)
                     uuObject.deepDelete(transactionState)
         else:   
             return JsonResponse({'success':False, 'error': "path was not specified in delete"})
         results = {'success':True}
     except Exception as e:
         logger = logging.getLogger(__name__)
         logger.error("%s" % traceback.format_exc())
         results = {'success':False, 'error': str(e)}
         
     return JsonResponse(results)
예제 #7
0
def showPathway(request, email):
    LogRecord.emit(request.user, 'pathAdvisor/showPathway', email)

    template = loader.get_template('consentrecords/userHome.html')
    args = {
        'user': request.user,
        'backURL': '/',
    }

    if request.user.is_authenticated():
        user = Instance.getUserInstance(request.user)
        if not user:
            return HttpResponse("user is not set up: %s" %
                                request.user.get_full_name())
        args['userID'] = user.id

    if settings.FACEBOOK_SHOW:
        args['facebookIntegration'] = True

    containerPath = '_user[_email=%s]' % email
    userInfo = UserInfo(request.user)
    objs = pathparser.selectAllObjects(containerPath,
                                       userInfo=userInfo,
                                       securityFilter=userInfo.findFilter)
    if len(objs) > 0:
        args['state'] = 'pathway%s' % objs[0].id

    context = RequestContext(request, args)

    return HttpResponse(template.render(context))
예제 #8
0
 def selectAll(user, data):
     try:
         path = data.get("path", None)
         start = int(data.get("start", "0"))
         end = int(data.get("end", "0"))
         userInfo = UserInfo(user)
         language=None
     
         if not path:
             raise ValueError("path was not specified")
     
         uuObjects = pathparser.selectAllObjects(path, userInfo=userInfo, securityFilter=userInfo.findFilter)\
                         .select_related('description')\
                         .order_by('description__text', 'id')
         
         if end > 0:
             uuObjects = uuObjects[start:end]
         elif start > 0:
             uuObjects = uuObjects[start:]
         
         p = [i.getReferenceData(userInfo, language) for i in uuObjects]                                                
         results = {'success':True, 'objects': p}
     except Exception as e:
         logger = logging.getLogger(__name__)
         logger.error("%s" % traceback.format_exc())
         results = {'success':False, 'error': str(e)}
     
     return JsonResponse(results)
예제 #9
0
 def addValue(user, data):
     try:
         # The path to the container object.
         containerPath = data.get('path', None)
     
         # The field name for the new value within the container object
         fieldName = data.get('fieldName', None)
     
         if fieldName is None:
             return JsonResponse({'success':False, 'error': 'the fieldName was not specified'})
         elif terms.isUUID(fieldName):
             field = Instance.objects.get(pk=fieldName, deleteTransaction__isnull=True)
         else:
             field = terms[fieldName]
         
         # A value added to the container.
         valueUUID = data.get('valueUUID', None)
     
         if valueUUID is None:
             return JsonResponse({'success':False, 'error': 'the value was not specified'})
         
         referenceValue = Instance.objects.get(pk=valueUUID)
         
         # The index of the value within the container.
         indexString = data.get('index', None)
     
         # The client time zone offset, stored with the transaction.
         timezoneoffset = data['timezoneoffset']
     
         with transaction.atomic():
             transactionState = TransactionState(user, timezoneoffset)
             
             if containerPath:
                 userInfo = UserInfo(user)
                 containers = pathparser.selectAllObjects(containerPath, userInfo=userInfo, securityFilter=userInfo.findFilter)
                 if len(containers) > 0:
                     container = containers[0]
                 else:
                     raise RuntimeError("Specified path is not recognized")
             else:
                 raise RuntimeError("the container path was not specified")
             container.checkWriteValueAccess(user, field, valueUUID)
 
             if indexString:
                 newIndex = container.updateElementIndexes(field, int(indexString), transactionState)
             else:
                 newIndex = container.getNextElementIndex(field)
 
             item = container.addReferenceValue(field, referenceValue, newIndex, transactionState)
             if item.isDescriptor:
                 Instance.updateDescriptions([container], NameList())
                 
         results = {'success':True, 'id': item.id}
     except Exception as e:
         logger = logging.getLogger(__name__)
         logger.error("%s" % traceback.format_exc())
         results = {'success':False, 'error': str(e)}
         
     return JsonResponse(results)
예제 #10
0
    def getData(user, data):
        pathparser.currentTimestamp = datetime.datetime.now()
        try:
            path = data.get('path', None)
            if path.startswith('::NewExperience:'):
                return api.getNewExperienceChoices(user, data)
            
            start = int(data.get("start", "0"))
            end = int(data.get("end", "0"))
        
            if not path:
                return JsonResponse({'success':False, 'error': "path was not specified in getData"})
            
            fieldString = data.get('fields', "[]")
            fields = json.loads(fieldString)
            
            language = data.get('language', None)

            userInfo=UserInfo(user)
            uuObjects = pathparser.selectAllObjects(path=path, userInfo=userInfo, securityFilter=userInfo.readFilter)
            
            # preload the typeID, parent, value_set and description to improve performance.
            valueQueryset = userInfo.findValueFilter(Value.objects.filter(deleteTransaction__isnull=True))\
                .order_by('position')\
                .select_related('field')\
                .select_related('field__id')\
                .select_related('referenceValue')\
                .select_related('referenceValue__description')

            uuObjects = uuObjects.select_related('typeID').select_related('parent')\
                                 .select_related('description')\
                                 .prefetch_related(Prefetch('value_set',
                                                            queryset=valueQueryset,
                                                            to_attr='values'))
            
            uuObjects = uuObjects.order_by('description__text', 'id');
            if end > 0:
                uuObjects = uuObjects[start:end]
            elif start > 0:
                uuObjects = uuObjects[start:]
                                                            
            fieldsDataDictionary = {}
            p = [api._getCells(uuObject, fields, fieldsDataDictionary, language, userInfo) for uuObject in uuObjects]        
        
            results = {'success':True, 'data': p}
        except Exception as e:
            logger = logging.getLogger(__name__)
            logger.error("%s" % traceback.format_exc())
            logger.error("getData data:%s" % str(data))
            
            results = {'success':False, 'error': str(e)}
        
        return JsonResponse(results)
예제 #11
0
    def getValues(user, data):
        try:
            path = data.get("path", None)
            if not path:
                return JsonResponse({
                    'success': False,
                    'error': 'the path was not specified'
                })

            userInfo = UserInfo(user)
            language = None

            # The element name for the type of element that the new value is to the container object
            fieldName = data.get('fieldName', None)

            if fieldName is None:
                return JsonResponse({
                    'success': False,
                    'error': 'the fieldName was not specified'
                })
            elif terms.isUUID(fieldName):
                field = Instance.objects.get(pk=fieldName,
                                             deleteTransaction__isnull=True)
            else:
                field = terms[fieldName]

            # A value with the container.
            value = data.get('value', None)

            if value is None:
                return JsonResponse({
                    'success': False,
                    'error': 'the value was not specified'
                })

            containers = pathparser.selectAllObjects(
                path=path,
                userInfo=userInfo,
                securityFilter=userInfo.findFilter)
            m = map(lambda i: i.findValues(field, value), containers)
            p = map(lambda v: v.getReferenceData(userInfo, language=language),
                    itertools.chain.from_iterable(m))

            results = {'success': True, 'objects': [i for i in p]}
        except Exception as e:
            logger = logging.getLogger(__name__)
            logger.error("%s" % traceback.format_exc())
            results = {'success': False, 'error': str(e)}

        return JsonResponse(results)
예제 #12
0
def getReferenceValue(parent, field, value, fd, nameLists, userInfo):
    if 'pickObjectPath' in fd:
        pickObjectPath = fd['pickObjectPath']
        if pickObjectPath.startswith("parent") and pickObjectPath[6] in ">:=<":
            pickObjectPath = "#" + parent.parent.id + pickObjectPath[6:]
    else:
        pickObjectPath = fd['ofKindID']

    # append a qualifier for the specified text to the pickObjectPath
    if 'ofKindID' in fd:
        type = Instance.objects.get(pk=fd['ofKindID'])
    else:
        l = pathparser.selectAllObjects(pickObjectPath,
                                        userInfo=userInfo,
                                        securityFilter=userInfo.findFilter)
        type = l[0].typeID

    verbs = list(
        filter(
            lambda verb: verb[2] == terms.textEnum or verb[2] == terms.
            firstTextEnum, nameLists.getNameUUIDs(type)))

    field, dataType, descriptorType = verbs[0]
    if isTranslationField(fd):
        languageCode, text = parseTranslation(value)
    else:
        text = value
    pickObjectPath += '[' + field.getDescription() + '="' + text + '"]'

    l = pathparser.selectAllObjects(pickObjectPath,
                                    userInfo=userInfo,
                                    securityFilter=userInfo.findFilter)
    if len(l):
        return l[0]
    else:
        raise RuntimeError("Unrecognized Reference Value in %s: %s(%s)" %
                           (str(parent), str(field), value))
예제 #13
0
    def getCellData(user, data):
        pathparser.currentTimestamp = datetime.datetime.now()
        try:
            path = data.get('path', None)

            if not path:
                return JsonResponse({
                    'success':
                    False,
                    'error':
                    "path was not specified in getData"
                })

            # The field name for the values to find within the container object
            fieldName = data.get('fieldName', None)

            if fieldName is None:
                return JsonResponse({
                    'success': False,
                    'error': 'the fieldName was not specified'
                })
            else:
                field = terms[fieldName]

            language = data.get('language', None)

            userInfo = UserInfo(user)
            uuObjects = pathparser.selectAllObjects(
                path=path,
                userInfo=userInfo,
                securityFilter=userInfo.readFilter)
            values = uuObjects[0].getReadableSubValues(field, userInfo)
            fieldsDataDictionary = {}
            p = [
                api._getValueData(v, fieldsDataDictionary, language, userInfo)
                for v in values
            ]

            results = {'success': True, 'objects': p}
        except Exception as e:
            logger = logging.getLogger(__name__)
            logger.error("%s" % traceback.format_exc())
            logger.error("getData data:%s" % str(data))

            results = {'success': False, 'error': str(e)}

        return JsonResponse(results)
예제 #14
0
def _addElementData(parent, data, fieldData, nameLists, transactionState):
    # If the data is not a list, then treat it as a list of one item.
    if not isinstance(data, list):
        data = [data]

    i = 0
    ids = []
    field = Instance.objects.get(pk=fieldData["nameID"])
    userInfo=UserInfo(transactionState.user)
    for d in data:
        if not isinstance(d, dict):
            raise RuntimeError("%s field of type %s is not a dictionary: %s" % (field, parent.typeID, str(d)))
            
        if fieldData["dataTypeID"] == terms.objectEnum.id:
            if "objectAddRule" in fieldData and fieldData["objectAddRule"] == "_pick one":
                if "instanceID" in d:
                    # This is a reference to an object.
                    values = list(userInfo.findFilter(Instance.objects.filter(pk=d["instanceID"])))
                    if len(values):
                        parent.addReferenceValue(field, values[0], i, transactionState)
                    elif d["instanceID"] == parent.id and field == terms.primaryAdministrator:
                        # This is a special case of setting up the primary administrator. This
                        # is necessary when creating a user so that it can be bootstrapped.
                        parent.addReferenceValue(field, parent, i, transactionState)
                    else:
                        raise RuntimeError("find permission failed for %s" % field)
                elif "path" in d:
                    ids = pathparser.selectAllObjects(d["path"], userInfo=userInfo, securityFilter=userInfo.findFilter)
                    if len(ids):
                        parent.addReferenceValue(field, ids[-1], i, transactionState)
                    else:
                        raise RuntimeError("Path does not parse to an object: %s" % d["path"])
                else:
                    raise RuntimeError("%s field of type %s contains neither instanceID nor path: %s" % (field, parent.typeID, str(d)))
            else:
                if "cells" in d and "ofKindID" in fieldData:
                    ofKindObject = Instance.objects.get(pk=fieldData["ofKindID"])
                    create(ofKindObject, parent, field, -1, d["cells"], nameLists, transactionState)
                else:
                    raise RuntimeError("%s field of type %s not configured to contain data: %s" % (field, parent.typeID, str(d)))
        else:
            parent.addValue(field, d, i, transactionState)
        i += 1
예제 #15
0
 def getValues(user, data):
     try:
         path = data.get("path", None)
         if not path:
             return JsonResponse({'success':False, 'error': 'the path was not specified'})
             
         userInfo = UserInfo(user)
         language=None
     
         # The element name for the type of element that the new value is to the container object
         fieldName = data.get('fieldName', None)
     
         if fieldName is None:
             return JsonResponse({'success':False, 'error': 'the fieldName was not specified'})
         elif terms.isUUID(fieldName):
             field = Instance.objects.get(pk=fieldName, deleteTransaction__isnull=True)
         else:
             field = terms[fieldName]
         
         # A value with the container.
         value = data.get('value', None)
     
         if value is None:
             return JsonResponse({'success':False, 'error': 'the value was not specified'})
         
         containers = pathparser.selectAllObjects(path=path, userInfo=userInfo, securityFilter=userInfo.findFilter)
         m = map(lambda i: i.findValues(field, value), containers)
         p = map(lambda v: v.getReferenceData(userInfo, language=language), itertools.chain.from_iterable(m))
                         
         results = {'success':True, 'objects': [i for i in p]}
     except Exception as e:
         logger = logging.getLogger(__name__)
         logger.error("%s" % traceback.format_exc())
         results = {'success':False, 'error': str(e)}
     
     return JsonResponse(results)
예제 #16
0
        except ValueError:
            username = input('Email Address: ')
        except IndexError:
            username = input('Email Address: ')
    
        try:
            path = sys.argv[sys.argv.index('-path') + 1]
        except ValueError:
            path = input('Path: ')
        except IndexError:
            path = input('Path: ')
    
        password = getpass.getpass("Password: "******"%s\n" % traceback.format_exc())
예제 #17
0
print ('##################################')
print ('# Test 11 ')
print ('# Tests getting data that contains a string and and object ')
print ('##################################')
a = ("Organization>_name[_text=BYCF]")
dd = pathparser.selectAllDescriptors(a)
print(dd)
print (str(api.getData(None, {'path': '#'+dd[0]['instanceID']} ).content))

print ('##################################')
print ('# Test 11 ')
print ('# Tests selectAll on a type name. ')
print ('##################################')
print (json.loads(api.selectAll(None, {'path': '_user'}).content.decode('utf-8')))

pathparser.selectAllObjects('Site[_name^=Jackson]')
pathparser.selectAllObjects('"Service Domain"')
pathparser.selectAllObjects('"Service Domain"[?]')
pathparser.selectAllObjects('_user[?*=ichael]')
pathparser.selectAllObjects('_user[(_name,_email)*=ichael]')
pathparser.selectAllObjects('_user["_first name"]')
pathparser.selectAllObjects('_user[("_first name","_last name")]')
pathparser.selectAllObjects('("Service Domain","Service")[_name=Education]')
pathparser.selectAllObjects('Site[_name^=Jackson][Offerings>Offering>Service[_name="Grade 8"]]')
pathparser.selectAllObjects('_user[_email^=michael]::reference(Experience,Enrollment)')
pathparser.selectAllObjects('_user[_email^=michael]::reference(Experience)::reference(Experiences)::reference(Session)::reference(Sessions)::reference(Offering)')
pathparser.selectAllObjects('_user::not(_user[_email^=michael])' +
	'::not(_user[_email^=michael]::reference("_access record")[_privilege=(_read,_write,_administer)]::reference(_user))')
pathparser.selectAllObjects('Offerings>Offering[_name="Grade 9"]')
pathparser.selectAllObjects('Organization[_name="Boston Public Schools"]>Sites>Site[Offerings>Offering[_name="Grade 9"]]')
pathparser.selectAllObjects('Organization[_name="Boston Public Schools"]>Sites>Site[Offerings>Offering[Service=%s]]'%\
    if len(sys.argv) > 1:
        username = sys.argv[1]
    else:
        username = input('Email Address: ')
    password = getpass.getpass("Password: "******"user was not authenticated")

    with transaction.atomic():
        transactionState = TransactionState(user, timezoneoffset)
        Terms.initialize(transactionState)

        a = pathparser.tokenize('Organization')
        uuObjects = pathparser.selectAllObjects(path=a,
                                                userInfo=UserInfo(user))
        uuObjects = list(
            filter(
                lambda i: not i.value_set.filter(field=Terms.publicAccess,
                                                 deletedvalue__isnull=True).
                exists(), uuObjects))
        print("%s organizations with missing public access values" %
              len(uuObjects))

        for i in uuObjects:
            i.addReferenceValue(Terms.publicAccess, Terms.readPrivilegeEnum, 0,
                                transactionState)

    print("Complete.")
예제 #19
0
    def addValue(user, data):
        try:
            # The path to the container object.
            containerPath = data.get('path', None)

            # The field name for the new value within the container object
            fieldName = data.get('fieldName', None)

            if fieldName is None:
                return JsonResponse({
                    'success': False,
                    'error': 'the fieldName was not specified'
                })
            elif terms.isUUID(fieldName):
                field = Instance.objects.get(pk=fieldName,
                                             deleteTransaction__isnull=True)
            else:
                field = terms[fieldName]

            # A value added to the container.
            valueUUID = data.get('valueUUID', None)

            if valueUUID is None:
                return JsonResponse({
                    'success': False,
                    'error': 'the value was not specified'
                })

            referenceValue = Instance.objects.get(pk=valueUUID)

            # The index of the value within the container.
            indexString = data.get('index', None)

            # The client time zone offset, stored with the transaction.
            timezoneoffset = data['timezoneoffset']

            with transaction.atomic():
                transactionState = TransactionState(user, timezoneoffset)

                if containerPath:
                    userInfo = UserInfo(user)
                    containers = pathparser.selectAllObjects(
                        containerPath,
                        userInfo=userInfo,
                        securityFilter=userInfo.findFilter)
                    if len(containers) > 0:
                        container = containers[0]
                    else:
                        raise RuntimeError("Specified path is not recognized")
                else:
                    raise RuntimeError("the container path was not specified")
                container.checkWriteValueAccess(user, field, valueUUID)

                if indexString:
                    newIndex = container.updateElementIndexes(
                        field, int(indexString), transactionState)
                else:
                    newIndex = container.getNextElementIndex(field)

                item = container.addReferenceValue(field, referenceValue,
                                                   newIndex, transactionState)
                if item.isDescriptor:
                    Instance.updateDescriptions([container], NameList())

            results = {'success': True, 'id': item.id}
        except Exception as e:
            logger = logging.getLogger(__name__)
            logger.error("%s" % traceback.format_exc())
            results = {'success': False, 'error': str(e)}

        return JsonResponse(results)
예제 #20
0
    def getData(user, data):
        pathparser.currentTimestamp = datetime.datetime.now()
        try:
            path = data.get('path', None)
            if path.startswith('::NewExperience:'):
                return api.getNewExperienceChoices(user, data)

            start = int(data.get("start", "0"))
            end = int(data.get("end", "0"))

            if not path:
                return JsonResponse({
                    'success':
                    False,
                    'error':
                    "path was not specified in getData"
                })

            fieldString = data.get('fields', "[]")
            fields = json.loads(fieldString)

            language = data.get('language', None)

            userInfo = UserInfo(user)
            uuObjects = pathparser.selectAllObjects(
                path=path,
                userInfo=userInfo,
                securityFilter=userInfo.readFilter)

            # preload the typeID, parent, value_set and description to improve performance.
            valueQueryset = userInfo.findValueFilter(Value.objects.filter(deleteTransaction__isnull=True))\
                .order_by('position')\
                .select_related('field')\
                .select_related('field__id')\
                .select_related('referenceValue')\
                .select_related('referenceValue__description')

            uuObjects = uuObjects.select_related('typeID').select_related('parent')\
                                 .select_related('description')\
                                 .prefetch_related(Prefetch('value_set',
                                                            queryset=valueQueryset,
                                                            to_attr='values'))

            uuObjects = uuObjects.order_by('description__text', 'id')
            if end > 0:
                uuObjects = uuObjects[start:end]
            elif start > 0:
                uuObjects = uuObjects[start:]

            fieldsDataDictionary = {}
            p = [
                api._getCells(uuObject, fields, fieldsDataDictionary, language,
                              userInfo) for uuObject in uuObjects
            ]

            results = {'success': True, 'data': p}
        except Exception as e:
            logger = logging.getLogger(__name__)
            logger.error("%s" % traceback.format_exc())
            logger.error("getData data:%s" % str(data))

            results = {'success': False, 'error': str(e)}

        return JsonResponse(results)
예제 #21
0
        except ValueError:
            username = input('Email Address: ')
        except IndexError:
            username = input('Email Address: ')

        try:
            path = sys.argv[sys.argv.index('-path') + 1]
        except ValueError:
            path = input('Path: ')
        except IndexError:
            path = input('Path: ')

        password = getpass.getpass("Password: "******"%s\n" % traceback.format_exc())
예제 #22
0
def _addElementData(parent, data, fieldData, nameLists, transactionState):
    # If the data is not a list, then treat it as a list of one item.
    if not isinstance(data, list):
        data = [data]

    i = 0
    ids = []
    field = Instance.objects.get(pk=fieldData["nameID"])
    userInfo = UserInfo(transactionState.user)
    for d in data:
        if not isinstance(d, dict):
            raise RuntimeError("%s field of type %s is not a dictionary: %s" %
                               (field, parent.typeID, str(d)))

        if fieldData["dataTypeID"] == terms.objectEnum.id:
            if "objectAddRule" in fieldData and fieldData[
                    "objectAddRule"] == "_pick one":
                if "instanceID" in d:
                    # This is a reference to an object.
                    values = list(
                        userInfo.findFilter(
                            Instance.objects.filter(pk=d["instanceID"])))
                    if len(values):
                        parent.addReferenceValue(field, values[0], i,
                                                 transactionState)
                    elif d["instanceID"] == parent.id and field == terms.primaryAdministrator:
                        # This is a special case of setting up the primary administrator. This
                        # is necessary when creating a user so that it can be bootstrapped.
                        parent.addReferenceValue(field, parent, i,
                                                 transactionState)
                    else:
                        raise RuntimeError("find permission failed for %s" %
                                           field)
                elif "path" in d:
                    ids = pathparser.selectAllObjects(
                        d["path"],
                        userInfo=userInfo,
                        securityFilter=userInfo.findFilter)
                    if len(ids):
                        parent.addReferenceValue(field, ids[-1], i,
                                                 transactionState)
                    else:
                        raise RuntimeError(
                            "Path does not parse to an object: %s" % d["path"])
                else:
                    raise RuntimeError(
                        "%s field of type %s contains neither instanceID nor path: %s"
                        % (field, parent.typeID, str(d)))
            else:
                if "cells" in d and "ofKindID" in fieldData:
                    ofKindObject = Instance.objects.get(
                        pk=fieldData["ofKindID"])
                    create(ofKindObject, parent, field, -1, d["cells"],
                           nameLists, transactionState)
                else:
                    raise RuntimeError(
                        "%s field of type %s not configured to contain data: %s"
                        % (field, parent.typeID, str(d)))
        else:
            parent.addValue(field, d, i, transactionState)
        i += 1
예제 #23
0
        sessionTerm = terms['Session']
        nameTerm = terms['_name']
        nameList = NameList()
        with open(sys.argv[1], 'r') as f:
            reader = csv.reader(f)
            for s in reader:
                orgName = s[0].strip()
                siteName = s[1].strip()
                streetName = s[2].strip()
                cityName = s[3].strip()
                stateName = s[4].strip()
                zipName = s[5].strip()
                grades = s[6:]
                statePath = '_term[_name=State]>enumerator[_name=' + stateName + ']'
                stateInstance = pathparser.selectAllObjects(
                    statePath,
                    userInfo=userInfo,
                    securityFilter=userInfo.findFilter)[0]

                schoolInstance = pathparser.selectAllObjects(
                    'Service[_name=School]',
                    userInfo=userInfo,
                    securityFilter=userInfo.findFilter)[0]
                educationInstance = pathparser.selectAllObjects(
                    'Service[_name=Education]',
                    userInfo=userInfo,
                    securityFilter=userInfo.findFilter)[0]

                orgs = Instance.objects.filter(
                    deleteTransaction__isnull=True,
                    typeID=orgTerm,
                    value__deleteTransaction__isnull=True,
예제 #24
0
    user = authenticate(username=username, password=password)

    with transaction.atomic():
        transactionState = TransactionState(user, timezoneoffset)

        f = Instance.objects.filter(typeID=terms['Inquiry'], deleteTransaction__isnull=True,
                                    value__field=terms.email,
                                    value__deleteTransaction__isnull=True)

        print ("Inquiry Count: %s" % f.count())
        userInfo = UserInfo(user)
        for inquiry in f:
            email = inquiry.value_set.get(field=terms.email,
                                        deleteTransaction__isnull=True)
            email.markAsDeleted(transactionState)
            path = '_user[_email="%s"]' % email.stringValue
            print("email: %s" % email.stringValue)
            l = pathparser.selectAllObjects(path, userInfo=userInfo, securityFilter=userInfo.findFilter)
            if len(l):
                inquiries = inquiry.parent
                if inquiries:
                    print("l: %s" % str(l))
                    transactionState = TransactionState(l[0].user, timezoneoffset)
                    inquiries.addReferenceValue(terms.user, l[0], 0, transactionState)
                    print("update inquiry for session %s: user %s" % (inquiry.parent.parent, l[0]))
                    inquiry.markAsDeleted(transactionState)
                else:
                    print("no parent for %s" % str(inquiry))