def register_all(): client = repo.get_instance(INSTANCE) app_keys = client.get_by_query(COLECTION_APP_KEYS, {}) for item in app_keys: if item.get('token') is not None: register_app(item['id'], item['token'])
def dumpColections(): try: client = repo.get_instance(RLZ_INSTANCE) client.clean_collection(COLECTION_RULES) client.clean_collection(COLECTION_ENTITYS) client.clean_collection(COLECTION_CATALOGS) client.clean_collection(COLECTION_TABLES) client.clean_collection(COLECTION_SIMULATIONS) client.clean_collection(COLECTION_LISTS) client.clean_collection(COLECTION_FUNCTIONS) client.clean_collection(COLECTION_FORMULAS) client.clean_collection(COLECTION_INSTRUMENTS) client.clean_collection(COLECTION_DRLS) except Exception as e: getLogger('arg_log').exception(e) raise e
def getData(id): try: client = repo.get_instance(INSTANCE) array = client.get_query_and_fields(COLLECTION_AUDITORY, {'this_id': id}, { 'data': 1, 'tabla': 1 }) if array is None or array == []: return json.dumps({ 'success': False, 'response': None, 'message': 'Exito' }), 404 return json.dumps({ 'success': True, 'response': array[0], 'message': 'Exito' }), 200 except Exception as e: getLogger('arg_log').exception(e) return json.dumps({ 'success': False, 'response': None, 'message': e.message }), 200
def get_rule_by_catalog_name(catalog_name, order): repo_client = repo.get_instance("rules") catalog = repo_client.get_by_query("rule_spec", {"instance.name": catalog_name}) str_rule = "" for rule in catalog[0]["instance"]["rules"]: halt = "" if rule["halt"]: halt = "kcontext.halt();" str_rule = str_rule + ''' rule \"{0}\" no-loop true dialect "mvel" salience {4} when {1} then {2} {3} end '''.format(rule["name"], base64.b64decode(rule["condition"]), base64.b64decode(rule["action"]), halt, order) return str_rule
def update_intance_form(message): try: repo_client = repo.get_instance("rules") sc = repo_client.get_by_id("scenarios", message["scenario_id"]) cont = 0 finded = False for form in sc["forms"]: if form["instance_id"] == message["form"]["instance_id"]: form["data"] = message["form"]["data"] finded = True break cont += 1 if finded: sc["forms"][cont] = form repo_client.update_by_field("scenarios", message["scenario_id"], "forms", sc["forms"]) return jsonify(success=True, msg="La operacion se ha realizado con exito") except Exception, ex: current_app.logger.exception(ex) return jsonify( success=False, msg="Lo sentimos pero ha ocurrido un error en el sistema"), 500
def execute(self, message): #current_app.logger.debug(message) try: message['spec']['tasks'][3]['forms'][0]['spec']['payload'][4][ 'gr_vista_patron']['properties']['showby'] = False message['spec']['tasks'][3]['forms'][0]['spec']['payload'][5][ 'gr_limvista_patron']['properties']['showby'] = False message['spec']['tasks'][3]['forms'][0]['spec']['payload'][2][ 'gr_visita']['properties']['showby'] = False message['spec']['tasks'][3]['forms'][0]['spec']['payload'][3][ 'gr_limvisita']['properties']['showby'] = False gr_tecnica = message['instance']['current_task']['forms'][0][ 'data']['gr_esptec'] #current_app.logger.debug(gr_tecnica) for linea in gr_tecnica: if 'ch_presmuesesptec' in linea and linea[ 'ch_presmuesesptec'] == 'SI': message['spec']['tasks'][3]['forms'][0]['spec']['payload'][ 4]['gr_vista_patron']['properties']['showby'] = True message['spec']['tasks'][3]['forms'][0]['spec']['payload'][ 5]['gr_limvista_patron']['properties']['showby'] = True if 'ch_realizarvisesptec' in linea and linea[ 'ch_realizarvisesptec'] == 'SI': message['spec']['tasks'][3]['forms'][0]['spec']['payload'][ 2]['gr_visita']['properties']['showby'] = True message['spec']['tasks'][3]['forms'][0]['spec']['payload'][ 3]['gr_limvisita']['properties']['showby'] = True repo_client = repo.get_instance("workflow") repo_client.update("instances", message['id'], message) return False, 'EXITO' except Exception, e: return False, 'Se produjo error durante la validacion ' + str(e)
def save(object_to_audit, token, object_id, collection_name, tp='I'): reqData = requestData() message = { "this_id": str(uuid.uuid1()), "nombre_fantasia": token.get('system'), "clave_principal": str(object_id), "iporigen": reqData.get('remote_addr'), "autenticador": token.get('authmethod'), "dependencia": token.get('dependencia_desc'), "cuit_organismo_autenticador": token.get('cuit_organismo_autenticador'), "cuit_organismo_usuario": token.get('cuit_organismo_usuario'), "codigo_usuario": token.get('uid'), "nombre_usuario": token.get('cn'), "roles": token.get('roles'), "tabla": collection_name, "data": object_to_audit, "tipo_accion": action_type[tp], "entorno_ejecucion": 'ONLINE', "tipo_metodo": reqData.get('method'), "url_metodo": reqData.get('url'), "fecha_hora": str(datetime.datetime.now().isoformat()) } getLogger('arg_audit').info(json.dumps(message)) repo_client = repo.get_instance("auditoria_arg2") repo_client.save_audit('audit', message)
def save_domain(class_spec): ''' Save a all domain clases (not an individual classes) @param: we spect something like this: { "header": {}, "instance": { "name": "Dui", "description": "Declaracion Unica de Importacion", "package": "bo.aduana.importacion.selectividad", "properties": [ { "name": "razon_social", "data_type": "string", "collection": false, "visibility": "public" }, { "name": "nit", "data_type": "string", "collection": false, "visibility": "public" }, { "name": "hijos", "data_type": "Persona", "collection": false, "visibility": "public" } ] } } ''' repo_client = repo.get_instance("rules") if class_spec.get("id") is None: '''Asume is an update ''' if len( repo_client.get_by_query( "domain_classes", {"instance.name": class_spec["instance"]["name"]})) != 0: raise BussinessException( "Lo sentimos pero el nombre de clase que intenta ingresar ya existe." ) message = {} message["id"] = repo_client.save("domain_classes", class_spec) return message else: repo_client.update("domain_classes", class_spec["id"], class_spec) '''
def get_statics_list(): ''' Return a json list of static_list Args: None ''' repo_client = repo.get_instance("rules") return repo_client.get_by_query("static_list", {})
def existName(name): try: client = repo.get_instance(INSTANCE) info = client.get_by_field(COLECTION_APP_KEYS, "name", name) if info: d = info[0] else: return False return d['name'] == name except Exception as e: getLogger('arg_log').exception(e) return False
def deleteSnapshot(id): try: client = repo.get_instance(INSTANCE) obj = client.get_by_id(COLECTION_SNAPSHOTS, id) if obj is None: return json.dumps( {'message': 'No se ha encontrado el Snapshot solicitado'}), 404 roles = getRoles() if ('user' not in obj or obj['user'] != getUserName()) and 'ADMINISTRADOR' not in roles: response = { 'response': None, 'success': False, 'message': 'No puede realizar la eliminación de un snapshot que no le pertenece' } else: filename = secure_filename(obj['name'] + '.json') folder = current_app.config['FILE_STORAGE_SNAPSHOTS'] + '/' os.remove(os.path.join(folder, filename)) client.remove(COLECTION_SNAPSHOTS, id) response = { 'response': None, 'message': 'El Snapshot ' + obj['name'] + ' ha sido borrado', 'success': True } except IOError as ie: getLogger('arg_log').exception(ie) if ie.errno == 2: message = 'No se ha podido obtener acceso al archivo de snapshot, por favor contacte a su administrador de sistema' else: message = 'I/O problem ' + str(ie.strerror) response = {'message': message, 'success': False, 'response': None} except Exception as e: getLogger('arg_log').exception(e) response = {'response': None, 'success': False, 'message': e.message} finally: return json.dumps(response), 200
def get_domain_by_catalog_name(catalog_name): repo_client = repo.get_instance("rules") catalog = repo_client.get_by_query("rule_spec", {"instance.name": catalog_name}) domain = [] for entity in catalog[0]["instance"]["entities"]: result = repo_client.get_by_query("domain_classes", {"instance.name": entity["id"]}) domain.append(result[0]["instance"]) message = {"domain": domain} return message
def getAllSnapshots(): try: client = repo.get_instance(INSTANCE) array = client.get_by_query(COLECTION_SNAPSHOTS, {}) response = {'message': 'Exito', 'success': True, 'response': array} except Exception as e: getLogger('arg_log').exception(e) response = { 'message': 'Ocurrio un error ' + e.message, 'success': False, 'response': [] } return json.dumps(response), 200
def all_keys(): try: list = [] client = repo.get_instance(INSTANCE) list = client.get_by_query(COLECTION_APP_KEYS, {}) response = {'message': 'Exito', 'success': True, 'response': list} except Exception as e: getLogger('arg_log').exception(e) response['message'] = e.message response['success'] = False return json.dumps(response), 200
def restore(snap): try: client = repo.get_instance(RLZ_INSTANCE) if 'rules' in snap and snap['rules'] is not None: for rule in snap['rules']: client.saveRlz(COLECTION_RULES, rule) if 'entitys' in snap and snap['entitys'] is not None: for entity in snap['entitys']: client.saveRlz(COLECTION_ENTITYS, entity) if 'tables' in snap and snap['tables'] is not None: for table in snap['tables']: client.saveRlz(COLECTION_TABLES, table) if 'functions' in snap and snap['functions'] is not None: for function in snap['functions']: client.saveRlz(COLECTION_FUNCTIONS, function) if 'formulas' in snap and snap['formulas'] is not None: for formula in snap['formulas']: client.saveRlz(COLECTION_FORMULAS, formula) if 'lists' in snap and snap['lists'] is not None: for li in snap['lists']: client.saveRlz(COLECTION_LISTS, li) if 'catalogs' in snap and snap['catalogs'] is not None: for catalog in snap['catalogs']: client.saveRlz(COLECTION_CATALOGS, catalog) if 'simulations' in snap and snap['simulations'] is not None: for simulation in snap['simulations']: client.saveRlz(COLECTION_SIMULATIONS, simulation) if 'instruments' in snap and snap['instruments'] is not None: for instrument in snap['instruments']: client.saveRlz(COLECTION_INSTRUMENTS, instrument) if 'drls' in snap and snap['drls'] is not None: for drl in snap['drls']: client.saveRlz(COLECTION_DRLS, drl) except Exception, e: getLogger('arg_log').exception(e) raise e
def editSnapshot(id): try: client = repo.get_instance(INSTANCE) obj = client.get_by_id(COLECTION_SNAPSHOTS, id) if obj is None: return json.dumps( {'message': 'No se ha encontrado el Snapshot solicitado'}), 404 data = json.loads(request.data) roles = getRoles() if ('user' not in obj or obj['user'] != getUserName()) and 'ADMINISTRADOR' not in roles: response = { 'response': None, 'success': False, 'message': 'No puede realizar la edición de un snapshot que no le pertenece' } else: obj['description'] = data['description'] client.updateRlz(COLECTION_SNAPSHOTS, id, obj) response = { 'response': None, 'message': 'Operacion exitosa', 'success': True } except IOError as ie: getLogger('arg_log').exception(ie) if ie.errno == 2: message = 'No se ha podido obtener acceso al archivo de snapshot, por favor contacte a su administrador de sistema' else: message = 'I/O problem ' + str(ie.strerror) response = {'message': message, 'success': False, 'response': None} except Exception as e: getLogger('arg_log').exception(e) response = {'response': None, 'success': False, 'message': e.message} finally: return json.dumps(response), 200
def delete_key(kid): try: client = repo.get_instance(INSTANCE) client.remove(COLECTION_APP_KEYS, kid) remove_app(kid) response = {'message': 'Exito al eliminar la app key', 'success': True} except Exception as e: getLogger('arg_log').exception(e) response['message'] = e.message response['success'] = False return json.dumps(response), 200
def save_static_list(list_spec): repo_client = repo.get_instance("rules") if list_spec.get("id") is None: if len( repo_client.get_by_query( "static_list", {"instance.name": list_spec["instance"]["name"]})) != 0: raise BussinessException( "Lo sentimos pero el nombre de lista que intenta ingresar ya existe." ) message = {} message["id"] = repo_client.save("static_list", list_spec) return message else: repo_client.update("static_list", list_spec["id"], list_spec)
def getRegisteredUsers(): try: client = repo.get_instance(INSTANCE) array = client.get_query_and_fields(COLLECTION_AUDITORY, {}, {'nombre_usuario': 1}) response = list( set([x['nombre_usuario'] for x in array if x is not None])) return json.dumps({ 'success': True, 'response': response, 'message': 'Exito' }), 200 except Exception as e: getLogger('arg_log').exception(e) return json.dumps({ 'success': False, 'response': None, 'message': e.message }), 200
def execute(self, message): #current_app.logger.debug(len(message['instance']['current_task']['forms'][0]['data']['gr_oferentes'])) msg = {} msg['gr_unicooferente'] = {} msg['gr_unicooferente']['ch_unicooferente_unicooferente'] = 'NO' try: for task in message['spec']['tasks']: if len(task['forms']) != 0 and task['forms'][0]['spec'][ 'header']['code'] == 'LPU_EMI_OCA_CUADRO_COMPARATIVO': for grupo in task['forms'][0]['spec']['payload']: if 'gr_unicooferente' in grupo: grupo['gr_unicooferente']['properties'][ 'showby'] = False if len(message['instance']['current_task']['forms'] [0]['data']['gr_oferentes']) == 1: grupo['gr_unicooferente']['properties'][ 'showby'] = True repo_client = repo.get_instance("workflow") repo_client.update("instances", message['id'], message) except Exception, e: return False, 'ERROR desconocido 1* !!!! ' + str(e)
def create_scenario(message): ''' Create a New Scenario given a JSON message (like this) { "name" : "Escenario de prueba", "owner" : "dev_user", "preload_plugin" : null, "catalogs":[{ "service_id" : "catalog", "idPadre" : 0, "id" : "Asigancion directa de canal", "text" : "Asigancion directa de canal de importacion" }] } ''' new_scenario = { "name": message["name"], "owner": message["owner"], "forms": [], "preload_plugin": message["preload_plugin"], "catalogs": message["catalogs"] } entities = [] for c_id in message["catalogs"]: entities += [ x for x in get_domain_by_catalog_name(c_id["id"])["domain"] if x not in entities ] new_scenario["domain"] = entities repo_client = repo.get_instance("rules") id_scenario = repo_client.save("scenarios", new_scenario) return id_scenario
def initDerog(): today_date = datetime.fromtimestamp( time()).strftime('%Y-%m-%dT%H:%M:%S.%fZ') client = repo.get_instance({'instance': 'rulz'}) objs = client.get_by_query('instruments', {}) if objs is None or len(objs) == 0: return for obj in objs: ending_date = '' if 'ending_date' in obj and (type(obj['ending_date']) is str or type(obj['ending_date']) is unicode): ending_date = obj['ending_date'] current_app.logger.debug(ending_date) if ending_date == today_date: derogate(obj)
def wrap_drools_constants(static_list): #current_app.logger.debug(static_list) query_array = [] for sl in static_list: query_array.append(sl["id"]) repo_client = repo.get_instance("rules") result_list = repo_client.get_by_query( "static_list", {"instance.name": { "$in": query_array }}) list_literal = "" for sl in result_list: value_literal = "" for value in sl["instance"]["values"]: value_literal += ",\"{0}\"".format(value) list_literal += sl["instance"][ "name"] + " : String[] = new String[]{" + value_literal[1:] + "}\n" return list_literal
def searchData(): try: data = json.loads(request.data) params = buildSearchParams(data) client = repo.get_instance(INSTANCE) array = client.get_query_and_fields(COLLECTION_AUDITORY, params, FIELDS_TO_SEARCH) response = getParsedList(array) return json.dumps({ 'success': True, 'response': response, 'message': 'Exito' }), 200 except Exception as e: getLogger('arg_log').exception(e) return json.dumps({ 'success': False, 'response': None, 'message': e.message }), 200
def remove_domain(id_domain): repo_client = repo.get_instance("rules") repo_client.remove("domain_classes", id_domain)
def get_scenario_by_id(id): repo_client = repo.get_instance("rules") return repo_client.get_by_id("scenarios", id)
def get_scenarios(): repo_client = repo.get_instance("rules") return repo_client.get_by_query("scenarios", {})
def import_bulk_rule_spec(message): repo_client = repo.get_instance("rules") repo_client.clean_collection("rule_spec") repo_client.populate_collection("rule_spec", message)
def remove_rule_spec(id): repo_client = repo.get_instance("rules") rs = repo_client.get_by_id("rule_spec", id) repo_client.remove("rule_spec", id)
def get_rules_spec(): repo_client = repo.get_instance("rules") return repo_client.get_by_query("rule_spec", {})