示例#1
0
    def load(self, type, path):
        path = path + ".json"
        objectsList = IterableDataStruct()
        try:
            with open(path) as file:
                for line in file:
                    jsonObj = json.loads(line.strip("'"))

                    for key in jsonObj:
                        if type == "Client":
                            crtObj = Client(jsonObj[key]["name"])
                            crtObj.setManuallyClientId(int(key))
                        if type == "Movie":
                            crtObj = Movie(jsonObj[key]["title"],
                                           jsonObj[key]["description"],
                                           jsonObj[key]["genre"])
                            crtObj.setManuallyMovieId(int(key))
                        if type == "Rental":
                            crtObj = Rental(jsonObj[key]["movieId"],
                                            jsonObj[key]["clientId"],
                                            jsonObj[key]["rentedDate"],
                                            jsonObj[key]["dueDate"],
                                            jsonObj[key]["returnedDate"])
                            crtObj.setManuallyRentalId(int(key))

                        objectsList.append(crtObj)

        except IOError as e:
            print(e)

        return objectsList
示例#2
0
class RentalRepository():
    def __init__(self):
        '''
        Instantiate the Repo list
        '''
        self._rentalList = IterableDataStruct()
        self._rentedMoviesCounter = {}
        self._rentedClientsCounter = {}
        self._state = IterableDataStruct()

    def rentMovie(self, rental):
        '''
         Adds a rental request to the list
        :param rental: Rental Object
        '''
        if not self.canUserRent(rental):
            raise RuntimeError(
                "User cannot rent movie due to the fact that is untrustworty")
            return

        if (type(rental) == Rental):
            self._rentalList.append(rental)
            self.incrementRentedMoviesCounter(rental)
            self.incrementRentedClientsCounter(rental)
            #print(str(rental.getClientId()) + " request added to the rental log")
        else:
            raise TypeError("Invalid rental format")

    def returnMovie(self, rental):
        '''
            Removes a rental request from the list
            :param rental: Rental Object
        '''
        ok = False
        for crt in self._rentalList:
            if crt.getClientId() == rental.getClientId() and crt.getMovieId(
            ) == rental.getMovieId():
                crt.setReturnedDate(rental.getReturnedDate())
                ok = True

        if ok != True:
            raise RuntimeError("Operation could not have been executed")

    def canUserRent(self, rental):
        '''
        :param rental: Rental Object
        :return: True or False if the user can or can't rent movies
        '''
        for crt in self._rentalList:
            if crt.getClientId() == rental.getClientId(
            ) and crt.getReturnedDate() != "" and crt.getReturnedDate(
            ) > crt.getDueDate():
                return False
        return True

    def mostRentedMovies(self):
        '''
        :return: A list containing the most Rented Movies
        '''
        rentedMovies = {}
        for crt in self._rentalList:
            try:
                rentedMovies[crt.getMovieId()] += 1
            except Exception:
                rentedMovies[crt.getMovieId()] = 1

        return sorted(rentedMovies.items(),
                      key=operator.itemgetter(1),
                      reverse=True)

    def mostActiveClients(self):
        '''
        :return: A list containing the most Active Clients
        '''
        clientsWhoRented = {}
        for crt in self._rentalList:
            try:
                clientsWhoRented[crt.getClientId()] += 1
            except Exception:
                clientsWhoRented[crt.getClientId()] = 1

        return sorted(clientsWhoRented.items(),
                      key=operator.itemgetter(1),
                      reverse=True)

    def rentalsAndMoviesCurrentlyRented(self):
        '''
        :return: A list containing the movies that are currently rented (and by what clients)
        '''
        rtrn = {}

        for crt in self._rentalList:
            if crt.getReturnedDate() == "":
                if crt.getClientId() not in rtrn.keys():
                    rtrn[crt.getClientId()] = []
                    rtrn[crt.getClientId()].append(crt.getMovieId())
                else:
                    rtrn[crt.getClientId()].append(crt.getMovieId())

        return rtrn

    def sortF(self, x):
        return ((x.getReturnedDate() - x.getDueDate()).days)

    def currentlyRentedUnreturnedMovies(self):
        '''
        :return: a list containing all the movies that are currently rented and unreturned
        '''
        rtrn = []
        for crt in self._rentalList:
            if crt.getReturnedDate() == "":
                continue

            if crt.getReturnedDate() > crt.getDueDate():
                rtrn.append(crt)

        #auxObj = sorted(rtrn, key = lambda x: ((x.getReturnedDate() - x.getDueDate()).days), reverse = True)
        auxObj = IterableDataStruct().sort(rtrn, self.sortF)
        return auxObj

    def incrementRentedMoviesCounter(self, rental):
        '''
        increments the Rented Movie Counter
        :param rental: Rental Object
        '''
        try:
            if rental.getMovieId() in self._rentedMoviesCounter.keys():
                self._rentedMoviesCounter[rental.getMovieId(
                )] = self._rentedMoviesCounter[rental.getMovieId()] + 1
            else:
                self._rentedMoviesCounter[rental.getMovieId()] = 1
        except Exception:
            pass

    def getRentedMovieCounter(self, rental):
        '''
        :param rental: Rental Object
        :return: an integer
        '''
        try:
            return self._rentedMoviesCounter[rental.getMovieId()]
        except Exception:
            pass

    def incrementRentedClientsCounter(self, rental):
        '''
        Increments the Rented Clients Counter
        :param rental: Rental Object
        '''
        if rental.getClientId() in self._rentedClientsCounter.keys():
            self._rentedClientsCounter[rental.getClientId(
            )] = self._rentedClientsCounter[rental.getClientId()] + 1
        else:
            self._rentedClientsCounter[rental.getClientId()] = 1

    def getRentedClientsCounter(self, rental):
        '''
        Getter for the rented Clients counter
        :param rental: Rental Object
        :return: an integer
        '''
        return self._rentedClientsCounter[rental.getClientId()]

    def removeByClientId(self, clientId):
        '''
        :param clientId: Integer
        '''
        i = 0
        while i < len(self._rentalList):
            if self._rentalList[i].getClientId() == clientId:
                self._rentalList.pop(i)
                i = i - 2
            i = i + 1

        #Delete the ClientsCounter
        try:
            del (self._rentedClientsCounter[clientId])
        except Exception as e:
            pass

    def replaceClient(self, clientOld, clientNew):
        '''
        Replaces a client with another one
        :param clientOld: Client object
        :param clientNew: Client object
        '''

        #Change the ids in rentalList
        for i in range(len(self._rentalList)):
            if self._rentalList[i].getClientId() == clientOld.getClientId():
                self._rentalList[i].setClientId(clientNew.getClientId())

        #change the ids in rentedClientsCounter
        try:
            aux = self._rentedClientsCounter[clientOld.getClientId()]
            del (self._rentedClientsCounter[clientOld.getClientId()])
            self._rentedClientsCounter[clientNew.getClientId()] = aux
        except Exception as e:
            pass

    def removeByMovieId(self, movieId):
        '''
        :param movieId: Integer representing the movie id
        '''
        i = 0
        while i < len(self._rentalList):
            if self._rentalList[i].getMovieId() == movieId:
                self._rentalList.pop(i)
                i = i - 2
            i = i + 1

        #Delete the MoviesCounter
        try:
            del (self._rentedMoviesCounter[movieId])
        except Exception:
            pass

    def replaceMovie(self, movieOld, movieNew):
        '''
         Replaces a movie with another one
         :param movieOld: movieObject
         :param movieNew: movieObject
         '''
        for i in range(len(self._rentalList)):
            if self._rentalList[i].getMovieId() == movieOld.getMovieId():
                self._rentalList[i].setMovieId(movieOld.getMovieId())

        try:
            aux = self._rentedMoviesCounter[movieOld.getMovieId()]
            del (self._rentedMoviesCounter[movieOld.getMovieId()])
            self._rentedMoviesCounter[movieNew.getMovieId()] = aux
        except Exception:
            pass

    def __str__(self):
        '''
        :return: a nicely formatted string ready to be printed
        '''
        msg = "\nCLIENT ID | MOVIE ID | RENTED DATE | DUE DATE | RETURNED DATE\n"
        for crt in self._rentalList:
            msg = msg + str(crt.getClientId()) + ": " + str(
                crt.getMovieId()) + ", " + str(
                    crt.getRentedDate()) + ", " + str(
                        crt.getDueDate()) + ", " + str(crt.getReturnedDate())
            msg += "\n"
        return msg

    def __len__(self):
        '''
        :return: the number of elements in the rentalList
        '''
        return len(self._rentalList)

    def __iter__(self):
        for elem in self._rentalList:
            yield elem
示例#3
0
class MovieRepository():
    def __init__(self):
        '''
        Instantiates the MovieRepository with an empty list of movies
        '''
        self._movieList = IterableDataStruct()

    def addMovie(self, movie):
        '''
        Add a movie to the list
        :param movie: Movie Object
        '''
        if (type(movie) == Movie):
            self._movieList.append(movie)
            #print(movie.getTitle() + " added to the movie list")
        else:
            raise TypeError("Invalid movie format")

    def removeMovie(self, movie):
        '''
        Removes a movie from the list
        :param movie: Movie Object
        '''
        searchedIndex = self.findMovie(movie)
        if searchedIndex == -1:
            raise RuntimeError("Requested movie does not exist")

        self._movieList.pop(searchedIndex)

    def replaceMovie(self, movieOld, movieNew):
        '''
        Replaces a movie with anther one
        :param movieOld: Movie Object
        :param movieNew: Movie Object
        '''
        searchedIndex = self.findMovie(movieOld)
        if searchedIndex == -1:
            raise RuntimeError("Requested movie does not exist")

        self._movieList[searchedIndex] = movieNew

    def findMovies(self, movie):
        '''
        Finds multiple movies by multiple attributes
        :param movie: Movie Object
        :return: the list of movies that are found
        '''
        result = MovieRepository()

        for i in range(len(self._movieList)):
            #Search by case-insensitive + partial name
            if Utils().findPartial(self._movieList[i].getTitle(),
                                   movie.getTitle()):
                result.addMovie(self._movieList[i])
                continue
            #Search by case-insensitive + partial description
            if Utils().findPartial(self._movieList[i].getDescription(),
                                   movie.getDescription()):
                result.addMovie(self._movieList[i])
                continue
            #Search by case-insensitive + partial genre
            if Utils().findPartial(self._movieList[i].getGenre(),
                                   movie.getGenre()):
                result.addMovie(self._movieList[i])

        return result

    def findMovie(self, movie):
        '''
        Finds just only one movie (exact match)
        :param movie: a movie object
        :return: an integer representing the id or -1 if it is not found
        '''
        for i in range(len(self._movieList)):
            if self._movieList[i].getTitle() == movie.getTitle():
                return i
        return -1

    def getMovieIdByName(self, title):
        '''
        :param title: string
        :return: an integer representing the id or an exception is raised if it is nout found
        '''
        for crt in self._movieList:
            if crt.getTitle() == title:
                return crt.getMovieId()

        raise RuntimeError("Movie not found")

    def getMovieById(self, id):
        '''
        :param id: an integer representing the movie id
        :return: a movie object
        '''
        for crt in self._movieList:
            if crt.getMovieId() == id:
                return crt

        raise RuntimeError("Movie not found")

    def __iter__(self):
        '''
        Enables capability of iteration over the Repo
        '''
        for elem in self._movieList:
            yield elem

    def __str__(self):
        '''
        :return: a nicely formatted string with the elements from the Repo
        '''
        msg = "\nID | TITLE | GENRE\n"
        for crt in self._movieList:
            msg += str(crt.getMovieId()) + ": " + str(
                crt.getTitle()) + ",  " + str(crt.getGenre())
            msg += "\n"
        return msg

    def __len__(self):
        '''
        :return: the number of elements from the repo
        '''
        return len(self._movieList)
示例#4
0
class ClientRepository():
    def __init__(self):
        '''
        Instantiate the class with an empty lists of clients
        '''
        self._clientList = IterableDataStruct()

    def addClient(self, client):
        '''
        Adds a client
        :param client: Client Object
        '''
        if self.findClient(client) != -1:
            raise RuntimeError("There already exists a user with this name")

        if (type(client) == Client):
            #print(client.getName() + " added to the client list")
            self._clientList.append(client)
        else:
            raise TypeError("Invalid client format")

    def removeClient(self, client):
        '''
        Removes a client
        :param client: Client Object
        '''
        searchedIndex = self.findClient(client)
        if searchedIndex == -1:
            raise RuntimeError("Client does not exist, can't remove")

        self._clientList.pop(searchedIndex)

    def replaceClient(self, clientOld, clientNew):
        '''
        Replaces a client with a new client
        :param clientOld: Client Object
        :param clientNew: Client Object
        '''
        searchedIndex = self.findClient(clientOld)
        if searchedIndex == -1:
            raise RuntimeError("Client does not exist")

        self._clientList[searchedIndex] = clientNew

    def findClients(self, client):
        '''
      Finds multiple clients by multiple attributes
      :param client: Client Object
      :return: a list of clients
      '''
        result = ClientRepository()

        #Search by case-insensitive name + partial names
        for i in range(len(self._clientList)):
            if Utils().findPartial(self._clientList[i].getName(),
                                   client.getName()):
                result.addClient(self._clientList[i])

        return result

    def findClient(self, client):
        '''
        Finds just one client
        :param client:  Client Object
        :return: an integer representing the found client id or -1 if it is not found
        '''
        for i in range(len(self._clientList)):
            if self._clientList[i].getName() == client.getName():
                return i
        return -1

    def getClientIdByName(self, name):
        '''
        :param name: string
        :return: Client Object or excepton is raised if it is not found
        '''
        for crt in self._clientList:
            if crt.getName() == name:
                return crt.getClientId()

        raise RuntimeError("Client not found")

    def getClientById(self, id):
        '''
        :param id: integer
        :return: Client Object that was found
        '''
        for crt in self._clientList:
            if crt.getClientId() == id:
                return crt

        raise RuntimeError("Client not found")

    def __iter__(self):
        for elem in self._clientList:
            yield elem

    def __str__(self):
        '''
        Prints all the repo
        :return: a nicely formatted string
        '''
        msg = "\nID | NAME\n"
        for crt in self._clientList:
            msg += str(crt.getClientId()) + " : " + str(crt.getName())
            msg += "\n"
        return msg

    def __len__(self):
        '''
        :return: the number of clients in the Repo
        '''
        return len(self._clientList)