Exemple #1
0
 def post(self):
     args = request.get_json()
     operation = args['operation']
     data = args['data']
     LOGGER.debug('Muscle request received %s', args)
     try:
         if operation == 'create':
             if data.get('name') is None:
                 raise InvalidResourceCreationError('name', 'Muscle')
             if data.get('imageURLs') is None:
                 data.update({'imageURLs': []})
             duplicate_check_query = db.muscle.find_one(
                 filter={"name": data.get('name')})
             if duplicate_check_query is not None:
                 raise DuplicateResourceCreationError(
                     data.get('name'), 'Muscle')
             new_id = db.muscle.insert_one(data).inserted_id
             return json.loads(str(Response(success=True,
                                            data=str(new_id))))
         elif operation == 'update':
             raise NotImplementedError
         elif operation == 'query':
             name_field = data.get('name')
             limit = data.get('find')
             if limit is None:
                 limit = 0
             criteria = {}
             if name_field is not None:
                 criteria = {"name": utils.translate_query(name_field)}
             results = []
             for result in db.muscle.find(filter=criteria, limit=limit):
                 results.append(utils.bson_to_json(result))
             LOGGER.debug('response sent %s',
                          str(Response(success=True, data=results)))
             return json.loads(str(Response(success=True, data=results)))
     except InvalidRequestError as e:
         return json.loads(str(ErrorResponse(e)))
     except InvalidResourceCreationError as e:
         return json.loads(str(ErrorResponse(e)))
     except InvalidOperationError as e:
         return json.loads(str(ErrorResponse(e)))
     except InvalidResourceParameterError as e:
         return json.loads(str(ErrorResponse(e)))
     except DuplicateResourceCreationError as e:
         return json.loads(str(ErrorResponse(e)))
Exemple #2
0
    def post(self):
        try:
            args = request.get_json()
            operation = args.get('operation')
            data = args.get('data')
            if operation is None:
                raise InvalidRequestError('operation')
            if data is None:
                raise InvalidRequestError('data')
            if operation == 'create':
                if data.get('name') is None:
                    raise InvalidResourceCreationError('name', 'CategoryTag')
                new_id = db.category_type.insert_one(data).inserted_id
                return json.loads(str(Response(success=True,
                                               data=str(new_id))))

            elif operation == 'update':
                raise NotImplementedError
            elif operation == 'query':
                name_field = data.get('name')
                limit = data.get('find')
                if limit is None:
                    limit = 0
                criteria = {}
                if name_field is not None:
                    criteria = {"name": utils.translate_query(name_field)}
                results = []
                for result in db.category_type.find(filter=criteria,
                                                    limit=limit):
                    results.append(utils.bson_to_json(result))
                return json.loads(str(Response(success=True, data=results)))
            else:
                raise InvalidOperationError(operation)

        except InvalidRequestError as e:
            return json.loads(str(ErrorResponse(e)))
        except InvalidResourceCreationError as e:
            return json.loads(str(ErrorResponse(e)))
        except InvalidOperationError as e:
            return json.loads(str(ErrorResponse(e)))
Exemple #3
0
class QuerySearch(Resource):
    """Given a Solr query with object names, return a Solr query with SIMBAD identifiers"""
    scopes = []
    rate_limit = [1000, 60 * 60 * 24]
    decorators = [advertise('scopes', 'rate_limit')]

    def post(self):
        stime = time.time()
        # Get the supplied list of identifiers
        identifiers = []
        query = None
        itype = None
        name2id = {}
        try:
            query = request.json['query']
            input_type = 'query'
        except:
            current_app.logger.error(
                'No query was specified for the  object search')
            return {
                "Error": "Unable to get results!",
                "Error Info": "No identifiers/objects found in POST body"
            }, 200
        # If we get the request from BBB, the value of 'query' is actually an array
        if isinstance(query, list):
            solr_query = query[0]
        else:
            solr_query = query
        current_app.logger.info('Received object query: %s' % solr_query)
        # This query will be split up into two components: a SIMBAD and a NED object query
        simbad_query = solr_query.replace('object:', 'simbid:')
        ned_query = solr_query.replace('object:', 'nedid:')
        # Check if an explicit target service was specified
        try:
            target = request.json['target']
        except:
            target = 'all'
        # If we receive a (Solr) query string, we need to parse out the object names
        try:
            identifiers = get_objects_from_query_string(solr_query)
        except Exception, err:
            current_app.logger.error(
                'Parsing the identifiers out of the query string blew up!')
            return {
                "Error":
                "Unable to get results!",
                "Error Info":
                "Parsing the identifiers out of the query string blew up! (%s)"
                % str(err)
            }, 200
        identifiers = [
            iden for iden in identifiers
            if iden.lower() not in ['object', ':']
        ]
        # How many object names did we fid?
        id_num = len(identifiers)
        # Keep a list with the object names we found
        identifiers_orig = identifiers
        # If we did not find any object names, there is nothing to do!
        if id_num == 0:
            return {
                "Error": "Unable to get results!",
                "Error Info":
                "No identifiers/objects found in Solr object query"
            }, 200
        # Get translations
        simbad_query = ''
        ned_query = ''
        translated_query = ''
        if target.lower() in ['simbad', 'all']:
            name2simbid = {}
            for ident in identifiers:
                result = get_simbad_data([ident], 'objects')
                if 'Error' in result or 'data' not in result:
                    # An error was returned!
                    current_app.logger.error(
                        'Failed to find data for SIMBAD object {0}!: {1}'.
                        format(ident, result.get('Error Info', 'NA')))
                    name2simbid[ident] = 0
                    continue
                try:
                    SIMBADid = [
                        e.get('id', 0) for e in result['data'].values()
                    ][0]
                except:
                    SIMBADid = "0"
                name2simbid[ident] = SIMBADid
            simbad_query = translate_query(solr_query, identifiers,
                                           name2simbid, 'simbid:')
        if target.lower() in ['ned', 'all']:
            name2nedid = {}
            for ident in identifiers:
                result = get_ned_data([ident], 'objects')
                if 'Error' in result or 'data' not in result:
                    # An error was returned!
                    current_app.logger.error(
                        'Failed to find data for NED object {0}!: {1}'.format(
                            ident, result.get('Error Info', 'NA')))
                    name2nedid[ident] = 0
                    continue
                try:
                    NEDid = [e.get('id', 0)
                             for e in result['data'].values()][0]
                except:
                    NEDid = 0
                name2nedid[ident] = str(NEDid)
            ned_query = translate_query(solr_query, identifiers, name2nedid,
                                        'nedid:')

        if simbad_query and ned_query:
            translated_query = '({0}) OR ({1})'.format(simbad_query, ned_query)
        elif simbad_query:
            translated_query = simbad_query
        elif ned_query:
            translated_query = ned_query
        else:
            translated_query = 'simbid:0'

        return {'query': translated_query}
Exemple #4
0
 def post(self):
     args = request.get_json()
     operation = args['operation']
     data = args['data']
     LOGGER.debug('MuscleGroup request received %s', args)
     try:
         if operation == 'create':
             if data.get('name') is None:
                 raise InvalidResourceCreationError('name', 'MuscleGroup')
             if data.get('muscles') is None or data.get(
                     'muscles').__len__() < 1:
                 raise InvalidResourceCreationError('muscles',
                                                    'MuscleGroup')
             if data.get('imageURLs') is None:
                 data.update({'imageURLs': []})
             duplicate_check_query = db.muscle_group.find_one(
                 filter={"name": data.get('name')})
             if duplicate_check_query is not None:
                 raise DuplicateResourceCreationError(
                     data.get('name'), 'MuscleGroup')
             muscles = data['muscles']
             muscle_ids_to_save = []
             for muscle in muscles:
                 muscle_query = db.muscle.find_one(filter={"name": muscle})
                 if muscle_query is not None:
                     muscle_ids_to_save.append(muscle_query['_id'])
                 else:
                     new_muscle = {"name": muscle, "imageURLs": []}
                     muscle_ids_to_save.append(
                         db.muscle.insert_one(new_muscle).inserted_id)
             data['muscles'] = muscle_ids_to_save
             new_id = db.muscle_group.insert_one(data).inserted_id
             return json.loads(str(Response(success=True,
                                            data=str(new_id))))
         elif operation == 'update':
             raise NotImplementedError
         elif operation == 'query':
             name_field = data.get('name')
             muscles_field = data.get('muscles')
             limit = data.get('find')
             if limit is None:
                 limit = 0
             criteria = {}
             if name_field is not None:
                 criteria = {"name": utils.translate_query(name_field)}
             elif muscles_field is not None:
                 muscles_id_list = []
                 muscles_result = []
                 for muscle in muscles_field:
                     muscle_result = db.muscle.find_one(
                         filter={"name": muscle})
                     if muscle_result is None:
                         return []
                     else:
                         muscles_id_list.append(muscle_result['_id'])
                         muscles_result.append(muscle_result)
                 criteria = {"muscles": {"$all": muscles_id_list}}
             results = []
             for raw_result in db.muscle_group.find(filter=criteria,
                                                    limit=limit):
                 muscles = get_muscles_for_result(raw_result, 'muscles')
                 result = utils.bson_to_json(raw_result)
                 del result['muscles']
                 result.update({'muscles': muscles})
                 results.append(result)
             LOGGER.debug('response sent %s',
                          str(Response(success=True, data=results)))
             return json.loads(str(Response(success=True, data=results)))
     except InvalidRequestError as e:
         return json.loads(str(ErrorResponse(e)))
     except InvalidResourceCreationError as e:
         return json.loads(str(ErrorResponse(e)))
     except InvalidOperationError as e:
         return json.loads(str(ErrorResponse(e)))
     except InvalidResourceParameterError as e:
         return json.loads(str(ErrorResponse(e)))
     except DuplicateResourceCreationError as e:
         return json.loads(str(ErrorResponse(e)))
Exemple #5
0
 def post(self):
     args = request.get_json()
     operation = args['operation']
     data = args['data']
     LOGGER.debug('Equipment request received %s', args)
     try:
         if operation == 'create':
             equipment_type = data.get('type')
             detail = data.get('detail')
             images = data.get('imageURLs')
             if data.get('name') is None:
                 raise InvalidResourceCreationError('name', 'Equipment')
             if equipment_type is None:
                 raise InvalidResourceCreationError('equipment_type',
                                                    'Equipment')
             if detail is None:
                 data.update({"detail": ""})
             if images is None:
                 data.update({"imageURLs": []})
             duplicate_check_query = db.equipment.find_one(
                 filter={"name": data.get('name')})
             if duplicate_check_query is not None:
                 raise DuplicateResourceCreationError(
                     data.get('name'), 'Equipment')
             type_result = db.equipment_type.find_one(
                 {"name": equipment_type})
             if type_result is not None:
                 data['type'] = type_result['_id']
             else:
                 data['type'] = db.equipment_type.insert_one({
                     "name":
                     equipment_type
                 }).inserted_id
             new_equipment = db.equipment.insert_one(data)
             LOGGER.debug(new_equipment)
             new_id = new_equipment.inserted_id
             return json.loads(str(Response(success=True,
                                            data=str(new_id))))
         elif operation == 'update':
             raise NotImplementedError
         elif operation == 'query':
             name_field = data.get('name')
             type_field = data.get('type')
             limit = data.get('find')
             if limit is None:
                 limit = 0
             criteria = {}
             if name_field is not None and type_field is not None:
                 type_results = db.equipment_type.find(
                     filter={"name": utils.translate_query(type_field)})
                 and_criteria = [{
                     "name": utils.translate_query(name_field)
                 }]
                 type_criteria = []
                 for type_result in type_results:
                     type_criteria.append(
                         {"type": utils.bson_to_json(type_result)['_id']})
                 if type_criteria.__len__() > 0:
                     and_criteria.append({"$or": type_criteria})
                 criteria = {"$and": and_criteria}
             elif name_field is not None:
                 criteria = {"name": utils.translate_query(name_field)}
             elif type_field is not None:
                 type_results = db.equipment_type.find(
                     filter={"name": utils.translate_query(type_field)})
                 if type_results.count() == 0:
                     return []
                 type_criteria = []
                 for type_result in type_results:
                     type_criteria.append({"type": type_result['_id']})
                 if type_criteria.__len__() > 0:
                     criteria = {"$or": type_criteria}
             results = []
             for raw_result in db.equipment.find(filter=criteria,
                                                 limit=limit):
                 result = utils.bson_to_json(raw_result)
                 equipment_type_id = raw_result['type']
                 equipment_type = db.equipment_type.find_one(
                     filter={"_id": equipment_type_id})
                 del result['type']
                 result.update({'type': utils.bson_to_json(equipment_type)})
                 results.append(result)
             LOGGER.debug('response sent %s',
                          str(Response(success=True, data=results)))
             return json.loads(str(Response(success=True, data=results)))
     except InvalidRequestError as e:
         return json.loads(str(ErrorResponse(e)))
     except InvalidResourceCreationError as e:
         return json.loads(str(ErrorResponse(e)))
     except InvalidOperationError as e:
         return json.loads(str(ErrorResponse(e)))
     except InvalidResourceParameterError as e:
         return json.loads(str(ErrorResponse(e)))
     except DuplicateResourceCreationError as e:
         return json.loads(str(ErrorResponse(e)))
Exemple #6
0
class QuerySearch(Resource):

    """Given a Solr query with object names, return a Solr query with SIMBAD identifiers"""
    scopes = []
    rate_limit = [1000, 60 * 60 * 24]
    decorators = [advertise('scopes', 'rate_limit')]

    def post(self):
        stime = time.time()
        # Get the supplied list of identifiers
        query = None
        itype = None
        name2id = {}
        try:
            query = request.json['query']
            input_type = 'query'
        except:
            current_app.logger.error('No query was specified for the  object search')
            return {"Error": "Unable to get results!",
                    "Error Info": "No identifiers/objects found in POST body"}, 200
        # If we get the request from BBB, the value of 'query' is actually an array
        if isinstance(query, list):
            solr_query = query[0]
        else:
            solr_query = query
        translated_query = solr_query
        current_app.logger.info('Received object query: %s'%solr_query)
        # Check if an explicit target service was specified
        try:
            targets = [t.strip() for t in request.json['target'].lower().split(',')]
        except:
            targets = ['simbad', 'ned']
        # Get the object names and individual object queries from the Solr query
        try:
            object_names, object_queries = parse_query_string(solr_query)
        except Exception, err:
            current_app.logger.error('Parsing the identifiers out of the query string blew up!')
            return {"Error": "Unable to get results!",
                    "Error Info": "Parsing the identifiers out of the query string blew up! (%s)"%str(err)}, 200
        # If no object names were found, return
        if len(object_names) == 0:
            return {"Error": "Unable to get results!",
                    "Error Info": "No identifiers/objects found in Solr object query"}, 200
        # First we check if the object query was in fact a cone search. This would have been a queery of the form
        #  object:"80.89416667 -69.75611111:0.166666"
        # resulting in 1 entry in the variable object_queries (namely: ['object:"80.89416667 -69.75611111:0.166666"'])
        # and with 1 entry in object_names (namely: [u'80.89416667 -69.75611111:0.166666']).
        is_cone_search = False
        if len(object_queries) == 1:
            # We received a cone search, which needs to be translated into a query in terms of 'simbid' and 'nedid'
            try:
                RA, DEC, radius = parse_position_string(object_names[0])
                current_app.logger.info('Starting cone search at RA, DEC, radius: {0}, {1}, {2}'.format(RA, DEC, radius))
                is_cone_search = True
            except:
                pass
        # If this is a comne search, we go a different path
        if is_cone_search:
            result = {'simbad':[], 'ned':[]}
            simbad_fail = False
            ned_fail = False
            result['simbad'] = simbad_position_query(RA, DEC, radius)
            if 'Error' in result['simbad']:
                simbad_fail = result['simbad']['Error Info']
            result['ned'] = ned_position_query(RA, DEC, radius)
            if 'Error' in result['ned']:
                ned_fail = result['ned']['Error Info']
            # If both SIMBAD and NED errored out, return an error
            if simbad_fail and ned_fail:
                return {"Error": "Unable to get results!", 
                        "Error Info": "{0}, {1}".format(simbad_fail, ned_fail)}, 200
            # Form the query in terms on simbid and nedid:
            cone_components = []
            if len(result['simbad']) > 0:
                cone_components.append('simbid:({0})'.format(" OR ".join(result['simbad'])))
            if len(result['ned']) > 0:
                cone_components.append('nedid:({0})'.format(" OR ".join(result['ned'])))
            oquery = "({0})".format(" OR ".join(cone_components))
            translated_query = solr_query.replace(object_queries[0], oquery)
            return {'query': translated_query}
        # Create the translation map from the object names provided to identifiers indexed in Solr (simbid and nedid)
        name2id = get_object_translations(object_names, targets)
        # Now we have all necessary information to created the translated query
        translated_query = translate_query(solr_query, object_queries, targets, object_names, name2id)
 
        return {'query': translated_query}