def userResponseBodyValidation(self):
     """
     A function to evaluate whether the JSON body sent to the client conforms to the proper input standard.
     :return: Boolean: True meaning the body is valid, False meaning the body is not valid
     """
     try:
         reasoner_validator.validate_Response(self.userResponseBody)
         return {"isValid": True, "error": None}
     except ValidationError as e:
         return {"isValid": False, "error": e}
Example #2
0
    def userResponseBodyIsValid(body: dict):
        """
        A function to evaluate whether the JSON body received from the client conforms to the proper input standard.
        :param body: A dictionary representing a JSON body
        :return: Boolean: True meaning the body is valid, False meaning the body is not valid
        """

        try:
            reasoner_validator.validate_Response(body)
            return True
        except Exception as e:
            return False
Example #3
0
def main():

    #### Parse command line options
    import argparse
    argparser = argparse.ArgumentParser(
        description='CLI testing of the ResponseCache class')
    argparser.add_argument(
        '--verbose',
        action='count',
        help='If set, print more information about ongoing processing')
    argparser.add_argument(
        'response_id',
        type=str,
        nargs='*',
        help='Integer number of a response to read and display')
    params = argparser.parse_args()

    #### Query and print some rows from the reference tables
    if len(params.response_id) == 0 or len(params.response_id) > 1:
        eprint("Please specify a single ARS response UUID")
        return

    response_id = params.response_id[0]

    response_content = requests.get(
        'https://ars.transltr.io/ars/api/messages/' + response_id,
        headers={'accept': 'application/json'})
    status_code = response_content.status_code

    if status_code != 200:
        eprint(
            "Cannot fetch from ARS a response corresponding to response_id=" +
            str(response_id))
        return

    #### Unpack the response content into a dict
    try:
        response_dict = response_content.json()
    except:
        eprint("Cannot decode ARS response_id=" + str(response_id) +
               " to a Translator Response")
        return

    if 'fields' in response_dict and 'actor' in response_dict[
            'fields'] and str(response_dict['fields']['actor']) == '9':
        eprint(
            "The supplied response id is a collection id. Please supply the UUID for a response"
        )
        return

    if 'fields' in response_dict and 'data' in response_dict['fields']:
        envelope = response_dict['fields']['data']
        if envelope is None:
            envelope = {}
            return envelope

        #### Perform a validation on it
        try:
            validate_Response(envelope)
            eprint('Returned message is valid')

        except ValidationError as error:
            eprint('ERROR: TRAPI validator reported an error: ' + str(error))
            if params.verbose:
                print(json.dumps(envelope, sort_keys=True, indent=2))

    return
Example #4
0
    def get_response(self, response_id):
        session = self.session

        if response_id is None:
            return ({
                "status": 400,
                "title": "response_id missing",
                "detail": "Required attribute response_id is missing from URL",
                "type": "about:blank"
            }, 400)

        response_id = str(response_id)

        #### Check to see if this is an integer. If so, it is a local response id
        match = re.match(r'\d+\s*$', response_id)
        if match:
            #### Find the response
            stored_response = session.query(Response).filter(
                Response.response_id == int(response_id)).first()
            if stored_response is not None:
                response_dir = os.path.dirname(
                    os.path.abspath(__file__)) + '/../../../data/responses_1_0'
                response_filename = f"{stored_response.response_id}.json"
                response_path = f"{response_dir}/{response_filename}"
                try:
                    with open(response_path) as infile:
                        return json.load(infile)
                except:
                    eprint(
                        f"ERROR: Unable to read response from file '{response_path}'"
                    )
                    return

            else:
                return ({
                    "status":
                    404,
                    "title":
                    "Response not found",
                    "detail":
                    "There is no response corresponding to response_id=" +
                    str(response_id),
                    "type":
                    "about:blank"
                }, 404)

        #### Otherwise, see if it is an ARS style response_id
        if len(response_id) > 30:
            response_content = requests.get(
                'https://ars.transltr.io/ars/api/messages/' + response_id,
                headers={'accept': 'application/json'})
            status_code = response_content.status_code

            if status_code != 200:
                return ({
                    "status":
                    404,
                    "title":
                    "Response not found",
                    "detail":
                    "Cannot fetch from ARS a response corresponding to response_id="
                    + str(response_id),
                    "type":
                    "about:blank"
                }, 404)

            #### Unpack the response content into a dict
            try:
                response_dict = response_content.json()
            except:
                return ({
                    "status":
                    404,
                    "title":
                    "Error decoding Response",
                    "detail":
                    "Cannot decode ARS response_id=" + str(response_id) +
                    " to a Translator Response",
                    "type":
                    "about:blank"
                }, 404)

            if 'fields' in response_dict and 'actor' in response_dict[
                    'fields'] and str(response_dict['fields']['actor']) == '9':
                response_content = requests.get(
                    'https://ars.transltr.io/ars/api/messages/' + response_id +
                    '?trace=y',
                    headers={'accept': 'application/json'})
                status_code = response_content.status_code

                if status_code != 200:
                    return ({
                        "status":
                        404,
                        "title":
                        "Response not found",
                        "detail":
                        "Failed attempting to fetch trace=y from ARS with response_id="
                        + str(response_id),
                        "type":
                        "about:blank"
                    }, 404)

                #### Unpack the response content into a dict and dump
                try:
                    response_dict = response_content.json()
                except:
                    return ({
                        "status":
                        404,
                        "title":
                        "Error decoding Response",
                        "detail":
                        "Cannot decode ARS response_id=" + str(response_id) +
                        " to a Translator Response",
                        "type":
                        "about:blank"
                    }, 404)

                return response_dict

            if 'fields' in response_dict and 'data' in response_dict['fields']:
                envelope = response_dict['fields']['data']
                if envelope is None:
                    envelope = {}
                    return envelope

                #### Actor lookup
                actor_lookup = {
                    '1': 'Aragorn',
                    '2': 'ARAX',
                    '3': 'BTE',
                    '4': 'NCATS',
                    '5': 'Robokop',
                    '6': 'Unsecret',
                    '7': 'Genetics',
                    '8': 'MolePro',
                    '10': 'Explanatory',
                    '11': 'ImProving',
                    '12': 'Cam',
                    '13': 'TextMining'
                }

                #Remove warning code hack
                #if 'logs' in envelope and envelope['logs'] is not None:
                #    for log in envelope['logs']:
                #        if isinstance(log,dict):
                #            if 'code' in log and log['code'] is None:
                #                log['code'] = '-'

                #### Perform a validation on it
                try:
                    validate_Response(envelope)
                    if 'description' not in envelope or envelope[
                            'description'] is None:
                        envelope['description'] = 'reasoner-validator: PASS'

                except ValidationError as error:
                    timestamp = str(datetime.now().isoformat())
                    if 'logs' not in envelope or envelope['logs'] is None:
                        envelope['logs'] = []
                    envelope['logs'].append({
                        "code":
                        'InvalidTRAPI',
                        "level":
                        "ERROR",
                        "message":
                        "TRAPI validator reported an error: " + str(error),
                        "timestamp":
                        timestamp
                    })
                    if 'description' not in envelope or envelope[
                            'description'] is None:
                        envelope['description'] = ''
                    envelope[
                        'description'] = 'ERROR: TRAPI validator reported an error: ' + str(
                            error) + ' --- ' + envelope['description']

                #### Try to add the reasoner_id
                if 'actor' in response_dict['fields'] and response_dict[
                        'fields']['actor'] is not None:
                    actor = str(response_dict['fields']['actor'])
                    if actor in actor_lookup:
                        if 'message' in envelope and 'results' in envelope[
                                'message'] and envelope['message'][
                                    'results'] is not None:
                            for result in envelope['message']['results']:
                                if 'reasoner_id' in result and result[
                                        'reasoner_id'] is not None:
                                    pass
                                else:
                                    result['reasoner_id'] = actor_lookup[actor]

                return envelope
            return ({
                "status":
                404,
                "title":
                "Cannot find Response (in 'fields' and 'data') in ARS response packet",
                "detail":
                "Cannot decode ARS response_id=" + str(response_id) +
                " to a Translator Response",
                "type":
                "about:blank"
            }, 404)

        return ({
            "status": 404,
            "title": "UnrecognizedResponse_idFormat",
            "detail": "Unrecognized response_id format",
            "type": "about:blank"
        }, 404)