class GameUserRepository: def __init__(self): self.__mongo_configuration = MongoConfiguration() self.__database = self.__mongo_configuration.database self.__game_user_collection = self.__database.game_user_collection self.__logger = Logger().get_logger() def add_game_user(self, game_user: GameUser) -> GameUser: self.__logger.info(f"Inserting new user in the system {game_user.login}") self.__game_user_collection.insert_one(game_user.to_mongo_dict())
class GameUserBusiness: def __init__(self): self.__logger = Logger().get_logger() self.__repository = GameUserRepository() self.__auth_business = AuthBusiness() def add_game_user(self, game_user: GameUser, user: User): self.__logger.info( f"User Business add new Game User {game_user.login}") self.__auth_business.verify_credentials(user) self.__repository.add_game_user(game_user)
class AccessTokenBusiness: def __init__(self): self.__logger = Logger().get_logger() self.__access_token = str() def create_access_token(self, user: UserLogin): self.__logger.info(f"Generating access token for user: {user.user_id}") access_token_hash = hashlib.sha256() access_token_hash.update(bytes(user.login, "utf-8")) access_token_hash.update(bytes(str(user.password), "utf-8")) access_token_hash.update(bytes(str(datetime.datetime.now()), "utf-8")) self.__access_token = access_token_hash.hexdigest() return self.__access_token
class ReaderFromFile(DataProvider): """ This class allow to provide data read from file. Args : :param dimension: int that represent dimention of the vector that will be in the data. :param file_name: Name of file containing the data. """ def __init__(self, dimension, file_path): DataProvider.__init__(self, dimension) self.file_path = file_path self.logger = Logger('ReaderFromFile') #@overrides(DataProvider) def get_points(self): # We test if the file exist path_file = Path(self.file_path) self.logger.info('We get the points from' + str(path_file)) if not path_file.is_file(): self.logger.error('The file does not exist') raise Exception("The file does not exist" + str(path_file)) data_file = pd.read_csv(str(path_file)) line_counter = -1 try: for i, row in enumerate(data_file.values): line_counter += 1 coodinates = [ Decimal(int(elem)) for index, elem in enumerate(row) if index != 0 ] # We get a dimension problem. if len(coodinates) != self.dimension: self.logger.error( 'The dimension is not correct, expected : ' + str(len(coodinates)) + str(self.dimension)) raise Exception("The dimension of the point at line " + str(line_counter) + " is not correct") self.point_list.append(Point(coodinates)) except Exception as e: self.logger.error("Probleme during reading line " + str(line_counter)) raise e return self.point_list
class UserController: def __init__(self): self.__user_bussiness = UserBusiness() self.__logger = Logger().get_logger() def add_new_user(self, user_json: dict): self.__logger.info(f"Adding an new user") Validator.validate_user_dict_add_user(user_json) user = UserLogin(None, user_json["name"], user_json["login"], user_json["password"]) new_user = self.__user_bussiness.add_new_user(user) new_user_json = dumps(new_user, cls=JsonObjectEncoder) return Response(new_user_json, status=201) def get_users(self): self.__logger.info("GET all users from configuration") users = self.__user_bussiness.get_users() users_json = dumps(users, cls=JsonObjectEncoder) return Response(users_json, status=200) def get_user_by_id(self, user_id): self.__logger.info(f"GET user data from id: {user_id}") user = self.__user_bussiness.get_user_by_id(user_id) user_json = dumps(user, cls=JsonObjectEncoder) return Response(user_json, status=200) def login(self, login_json: dict): self.__logger.info(f"Login user: {login_json['login']}") Validator.validate_user_dict_login(login_json) user = UserLogin(None, None, login_json["login"], login_json["password"]) user = self.__user_bussiness.authenticate(user) user = self.__user_bussiness.get_access_token(user) user_json = dumps(user.access_token_to_dict()) return Response(user_json, status=200) def validate_token(self, access_token_json: dict): self.__logger.info( f"Validating access token user: {access_token_json['login']}") Validator.validate_user_dict_validate_access_token(access_token_json) user = UserLogin(None, None, access_token_json["login"], "") user.access_token = access_token_json["access_token"] self.__user_bussiness.get_user_by_login(user.login) self.__user_bussiness.validate_access_token(user) user_json = dumps(user.access_token_validate_to_dict()) return Response(user_json, status=200)
def main(): """ loop throught all config file and display result. :return: """ logger = Logger('Main') logger.info('begin operation on bloom filter') # --------------------------------------------------------------- # Get parameters from config file list_visualisation = [] dic_response = create_bloom_filters(logger, METHOD) list_visualisation.append(dic_response[Constants.DIS_INPUTS]) list_visualisation.append(dic_response[Constants.DIS_TESTS]) list_visualisation.append(dic_response[Constants.DIS_DOUBLE]) list_visualisation.append(dic_response[ARF_METHOD]) visualize_curve(list_visualisation, "dimension", " Rate false positive (%)", "DELTA "+str(DELTA) + " N and tests "+ str(SIZE_DATA)+" Dim "+str(DIM)+" DOMAIN "+str(DOMAIN))
def main(): """ loop throught all config file and display result. :return: """ logger = Logger('Main') logger.info('begin operation on bloom filter') # --------------------------------------------------------------- # Get parameters from config file list_visualisation = [] for config_file in os.listdir(PATH_CONFIG): print(config_file) list_visualisation.append( run_test_on_bloom_filter(logger, PATH_CONFIG, config_file)) visualize_curve(list_visualisation, "ratio m/n", " rate false positive (%)", "Comparaison discretization method in Dimension 2")
def main(): """ loop throught all config file and display result. :return: """ logger = Logger('Main') logger.info('begin operation on bloom filter') # --------------------------------------------------------------- # Get parameters from config file list_visualisation = [] a = create_bloom_filters(logger) list_visualisation.append(("dis_input", a[0], a[1][0])) list_visualisation.append(("dis_test", a[0], a[1][1])) list_visualisation.append(("dis_double", a[0], a[1][2])) #list_visualisation.append(("dis_circle", a[0], a[1][3])) list_visualisation.append(("arf", a[0], a[1][3])) #list_visualisation.append(("dis_none", a[0], a[1][3])) visualize_curve( list_visualisation, "delta", " rate false positive (%)", "Dimension: " + str(DIMENSION) + " size_set n: " + str(SIZE_DATA) + " rate size_bloom/size_set n/m: " + str(RATE_M_N) + " domain: " + str(DOMAIN) + " number_of tests: " + str(TESTS))
class Arf(): """ This class is an implementation of Arf. Args : :param lambda_error: float representing how each coordinates of the points should be ceil or floor. """ def __init__(self, path): self.path = path self.logger = Logger('Arf') self.compile() def compile(self): """ Compile the C++ Code :return: """ executable = os.path.join(self.path, MAKE_FILE) self.logger.info('Compile C++ code to : '+str(executable)) print(executable) if os.path.isfile(executable): try: old_path = os.getcwd() # Change the current directory os.chdir(os.path.join(old_path, self.path)) # clean the repo output = subprocess.check_output([MAKE_COMMAND, CLEAN], stderr=None) self.logger.debug('Make clean') # compile c++ code except subprocess.CalledProcessError as e: self.logger.error('Impossible to make clean') try : output = subprocess.check_output([MAKE_COMMAND], stderr=subprocess.STDOUT) self.logger.debug('Make') # reset the olde path. os.chdir(old_path) except subprocess.CalledProcessError as e: os.chdir(old_path) raise(e) else: raise Exception("Impossible to compile Arf code") def execute_program(self, argv): """ Call the c++ program. :param argv: :return: """ size = None false_positive = None executable = os.path.join(self.path, NAME_EXECUTABLE) print if os.path.isfile(executable): try: old_path = os.getcwd() # Change the current directory os.chdir(os.path.join(old_path, self.path)) # clean the repo command = './' + " ".join([NAME_EXECUTABLE] + argv) self.logger.debug("size: "+ argv[4]) output = subprocess.check_output(command, shell=True, stderr=subprocess.PIPE) outputs = str(output).split("*"); size = outputs[1] false_positive = outputs[3] # Reset the directory os.chdir(old_path) except subprocess.CalledProcessError as e: self.logger.error(e.output) self.logger.error("Impossible to run Node program") else: raise Exception("Impossible to find Node program") return size, false_positive
class UserRepository: def __init__(self): self.__logger = Logger().get_logger() self.__mongo_configuration = MongoConfiguration() self.__database = self.__mongo_configuration.database self.__user_collection = self.__database.user_collection self.__user_collection.create_index("login", unique=True) def add_new_user(self, user: UserLogin) -> UserLogin: self.__logger.info(f"Inserting new user: {user.login}") mongo_object_id = self.__user_collection.insert_one( user.to_mongo_dict()).inserted_id user.user_id = str(mongo_object_id) return user def get_users(self) -> list: self.__logger.info("Getting users from configuration") users = list() for document in self.__user_collection.find(): user_id = str(document['_id']) name = str(document['name']) user = User(user_id, name) users.append(user) return users def get_user_by_login(self, login: str) -> UserLogin: self.__logger.info(f"Getting user by login: {login}") user = None for document in self.__user_collection.find({"login": login}): user_id = str(document["_id"]) user_name = str(document["name"]) user_login = str(document["login"]) user_password = str(document["password"]) user_access_token = str(document["access_token"]) user = UserLogin(user_id, user_name, user_login, "") user.password = user_password user.access_token = user_access_token return user def get_user_by_id(self, user_id: str) -> UserLogin: self.__logger.info(f"Getting user by id: {user_id}") user = None for document in self.__user_collection.find({"_id": ObjectId(user_id)}): user_id = str(document["_id"]) user_name = str(document["name"]) user_login = str(document["login"]) user_password = str(document["password"]) user_access_token = str(document["access_token"]) user = UserLogin(user_id, user_name, user_login, "") user.password = user_password user.access_token = user_access_token return user def set_access_token(self, user: UserLogin) -> bool: self.__logger.info( f"Setting new access token for user: {user.user_id}") update_user = {"_id": ObjectId(user.user_id)} update_data = {"$set": {"access_token": user.access_token}} updated_data = self.__user_collection.update_one( update_user, update_data) return updated_data.raw_result['updatedExisting']
class UserBusiness: def __init__(self): self.__user_repository = UserRepository() self.__access_token_business = AccessTokenBusiness() self.__logger = Logger().get_logger() def add_new_user(self, user: UserLogin): self.__logger.info( f"Validating the insertion of new user: {user.login}") existent_user = self.__user_repository.get_user_by_login(user.login) if existent_user is not None: raise UserAlreadyExistsException() new_user = self.__user_repository.add_new_user(user) self.__logger.info(f"New user ID: {new_user.user_id}") return new_user def get_users(self): users = self.__user_repository.get_users() return users def get_user_by_id(self, user_id: str): user = self.__user_repository.get_user_by_id(user_id) if user is None: raise UserNotFoundException() return user def get_user_by_login(self, login: str): user = self.__user_repository.get_user_by_login(login) if user is None: raise UserNotFoundException() return user def authenticate(self, user: UserLogin): self.__logger.info( f"Login process for user - Authentication: {user.login}") user_login_information = self.__user_repository.get_user_by_login( user.login) if user_login_information is None: raise AuthenticationException() if Validator.is_wrong_credentials(user, user_login_information): raise AuthenticationException() return user_login_information def get_access_token(self, user: UserLogin): self.__logger.info( f"Login process for user - Access Token: {user.user_id}") access_token = self.__access_token_business.create_access_token(user) user.access_token = access_token created = self.__user_repository.set_access_token(user) if not created: raise AccessTokenException() return user def validate_access_token(self, user: UserLogin): self.__logger.info(f"Validating access token for user: {user.login}") user_login_information = self.__user_repository.get_user_by_login( user.login) if Validator.is_wrong_access_token(user, user_login_information): raise NonValidAccessTokenException()