<commit_before>import sys, argparse, json
from functools import wraps

from bottle import post, run, Response, request, abort, HTTPError

from openehr.utils import get_logger
from openehr.utils.services import get_service_configuration
from openehr.ehr.services.dbmanager.dbservices import DBServices
from openehr.ehr.services.dbmanager.dbservices.wrappers import PatientRecord, ClinicalRecord
import openehr.ehr.services.dbmanager.errors as pyehr_errors


class DBService(object):

    def __init__(self, driver, host, database, patients_repository=None,
                 ehr_repository=None, port=None, user=None, passwd=None):
        self.logger = get_logger('db_service_daemon')
        self.dbs = DBServices(driver, host, database, patients_repository,
                              ehr_repository, port, user, passwd, self.logger)
        #######################################################
        # Web Service methods
        #######################################################
        post('/patient/add')(self.save_patient)
        post('/patient/hide')(self.hide_patient)
        post('/patient/delete')(self.delete_patient)
        post('/patient/get')(self.get_patient)
        post('/patient/load_ehr_records')(self.load_ehr_records)
        post('/ehr/add')(self.save_ehr_record)
        post('/ehr/hide')(self.hide_ehr_record)
        post('/ehr/delete')(self.delete_ehr_record)

    def exceptions_handler(f):
        @wraps(f)
        def wrapper(inst, *args, **kwargs):
            try:
                return f(inst, *args, **kwargs)
            except pyehr_errors.DBManagerNotConnectedError:
                msg = 'Unable to connect to backend engine'
                inst._error(msg, 500)
            except pyehr_errors.UnknownDriverError, ude:
                inst._error(str(ude), 500)
            except HTTPError:
                #if an abort was called in wrapped function, raise the generated HTTPError
                raise
            except Exception, e:
                import traceback
                inst.logger.error(traceback.print_stack())
                msg = 'Unexpected error: %s' % e.message
                inst._error(msg, 500)
        return wrapper

    def _error(self, msg, error_code):
        self.logger.error(msg)
        body = {
            'SUCCESS': False,
            'ERROR': msg
        }
        abort(error_code, json.dumps(body))

    def _missing_mandatory_field(self, field_label):
        msg = 'Missing mandatory field, can\'t continue with the request'
        self._error(msg, 400)

    def _success(self, body, return_code=200):
        return Response(json.dumps(body), return_code)

    def _get_bool(self, str_val):
        if str_val.upper() == 'TRUE':
            return True
        elif str_val.upper() == 'FALSE':
            return False
        else:
            raise ValueError('Can\'t convert to boolean value %s' % str_val)

    @exceptions_handler
    def save_patient(self):
        """
        Create a new PatientRecord from the given values. Returns the saved record in
        its JSON encoding
        """
        params = request.forms
        try:
            record_id = params.get('patient_id')
            if not record_id:
                self._missing_mandatory_field('patient_id')
            patient_record_conf = {<commit_msg>properly handling JSON return data<commit_after>import sys, argparse, json
from functools import wraps

from bottle import post, run, response, request, abort, HTTPError

from openehr.utils import get_logger
from openehr.utils.services import get_service_configuration
from openehr.ehr.services.dbmanager.dbservices import DBServices
from openehr.ehr.services.dbmanager.dbservices.wrappers import PatientRecord, ClinicalRecord
import openehr.ehr.services.dbmanager.errors as pyehr_errors


class DBService(object):

    def __init__(self, driver, host, database, patients_repository=None,
                 ehr_repository=None, port=None, user=None, passwd=None):
        self.logger = get_logger('db_service_daemon')
        self.dbs = DBServices(driver, host, database, patients_repository,
                              ehr_repository, port, user, passwd, self.logger)
        #######################################################
        # Web Service methods
        #######################################################
        post('/patient/add')(self.save_patient)
        post('/patient/hide')(self.hide_patient)
        post('/patient/delete')(self.delete_patient)
        post('/patient/get')(self.get_patient)
        post('/patient/load_ehr_records')(self.load_ehr_records)
        post('/ehr/add')(self.save_ehr_record)
        post('/ehr/hide')(self.hide_ehr_record)
        post('/ehr/delete')(self.delete_ehr_record)

    def exceptions_handler(f):
        @wraps(f)
        def wrapper(inst, *args, **kwargs):
            try:
                return f(inst, *args, **kwargs)
            except pyehr_errors.DBManagerNotConnectedError:
                msg = 'Unable to connect to backend engine'
                inst._error(msg, 500)
            except pyehr_errors.UnknownDriverError, ude:
                inst._error(str(ude), 500)
            except HTTPError:
                #if an abort was called in wrapped function, raise the generated HTTPError
                raise
            except Exception, e:
                import traceback
                inst.logger.error(traceback.print_stack())
                msg = 'Unexpected error: %s' % e.message
                inst._error(msg, 500)
        return wrapper

    def _error(self, msg, error_code):
        self.logger.error(msg)
        body = {
            'SUCCESS': False,
            'ERROR': msg
        }
        abort(error_code, json.dumps(body))

    def _missing_mandatory_field(self, field_label):
        msg = 'Missing mandatory field, can\'t continue with the request'
        self._error(msg, 400)

    def _success(self, body, return_code=200):
        response.content_type = 'application/json'
        response.status = return_code
        return body

    def _get_bool(self, str_val):
        if str_val.upper() == 'TRUE':
            return True
        elif str_val.upper() == 'FALSE':
            return False
        else:
            raise ValueError('Can\'t convert to boolean value %s' % str_val)

    @exceptions_handler
    def save_patient(self):
        """
        Create a new PatientRecord from the given values. Returns the saved record in
        its JSON encoding
        """
        params = request.forms
        try:
            record_id = params.get('patient_id')
            if not record_id:
                self._missing_mandatory_field('patient_id')
            patient_record_conf = {
{'fraction_non_alphanumeric': 0.1242410780393899, 'fraction_numerical': 0.00444247001332741, 'mean_word_length': 2.404233870967742, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5485635', 'n_tokens_mistral': 1897, 'n_tokens_neox': 1843, 'n_words': 437}