Individual information in the DTO for the logged-in user - java

My controller returns the DTO of the Movie object
public class Movie {
private final String title;
private final MovieType type;
private final List<LanguageType> languages;
private final List<CountryType> countries;
...
}
This is the standard movie object I'm returning after calling / movies / {id}. However, I would like to return the rating of the logged in user along with this video. As is the case with, for example, other services like IMDB. When you enter the movie site, this is only a general rating, but if you log in to your account and rate the video, your rating will be given on the video page. So I thought to add to the DTO Movie object the box yourRating where your rating will be given if you are logged in and rated the video. It would look like this way
public class Movie {
private final String title;
private final MovieType type;
private final List<LanguageType> languages;
private final List<CountryType> countries;
private final Float yourRating; \\ Twoja ocena
...
}
I created a thread about it on SO and the user there suggested to create a new UserMovie object inheriting from Movie and having only one additional field of yourRating.
I wanted to ask you if this is how it should look like, that the offline user / movies / {id} returns DTO Movie, and the currently logged DTO UserMovie object (inherits all Movie fields + yourRating field). Is it necessary to separate in such a way individual data for the logged in user.

Related

Find all RealmObjects that have inside a list a given RealmObject

Lets say I have this class (it already has an id property but it's already auto generated by realm):
public class User extends RealmObject {
private String name;
private String username;
}
And another one that has a list of Users inside:
public class Ride extends RealmObject {
private String tripName;
private String rideType;
private RealmList<User> usersJoined;
}
I just want to do a query to realm to get a list of Rides where the user is inside. I found another question like this but in that case the asker already has the object that have the whole list and he just need to find the user inside that spefic object property list, but in my case I want to get the Rides where the user (that I already know) is inside. Thank you in advanced!
Finally fixed using stream().filter :
RealmResults<Ride> rides = realm.where(Ride.class).findAll();
List<Ride> = rides.stream().filter(ride -> ride.getUsersJoined().contains(givenUser)).collect(Collectors.toList())

JavaFX: Bindings with presentation model

My JavaFX application should look like this:
Now I want to make sure that the detail view adapts as soon as I select another person from the table view.
My classes so far:
public class Person {
private final StringProperty name = new SimpleStringProperty();
private final StringProperty title = new SimpleStringProperty();
private final IntegerProperty age = new SimpleIntegerProperty();
public Person(String name, String title, int age) {
setName(name);
setTitle(title);
setAge(age);
}
// Getters and Setters
}
public class PresentationModel {
private final ObservableList<Person> persons = FXCollections.observableArrayList();
private final ObjectProperty<Person> selectedPerson = new SimpleObjectProperty<>();
public PresentationModel() {
// add some users to persons list
}
// Getters/Setters
}
In the UI class with the table I have set up a listener like this:
personsTable.getSelectionModel().selectedItemProperty().addListener((observable, oldPerson, newPerson) -> {
model.setSelectedPerson(newPerson);
});
And in the UI class with the details view I have set up a binding:
nameLabel.textProperty().bind(model.getSelectedPerson().nameProperty());
The PresentationModel model attribute is created once with the start of the application and than passed through the constructors to all the UI classes.
But this bind is not working as expected.
What can I change so the binding works correctly and the property changes?
The binding doesn't work, because getSelectedPerson just returns the current selected person, and isn't recomputed if the selected person changes.
Using just the standard API, you can do
nameLabel.textProperty().bind(Bindings.selectString(
model.selectedPersonProperty(), "name"));
This API is a little unsatisfactory in a number of ways. For one, there is no compile-time checking that the selectedPersonProperty() has a nameProperty(), and that it is of the correct type. Secondly, it uses reflection, which doesn't perform well in the case that you call it very frequently (which does not apply here). Finally, if the selected person is null, this will dump lots of superfluous warnings to standard output (despite the fact that the API documentation indicates this is a supported use case!!!).
An alternative is provided by the ReactFX framework:
nameLabel.textProperty().bind(Val.selectVar(
model.selectedPersonProperty(), Person::nameProperty));

Dynamically create form for super and subclasses

Suppose that we have classes:
public class BasicCustomer {
private String name;
private String email;
----getters and setters omited----
}
public class CustomerWithDog extends BasicCustomer{
private String dogName;
private String dogRace;
----getters and setters omited----
}
public class CustomerWithCat extends BasicCustomer{
private String catName;
private String catRace;
----getters and setters omited----
}
Only when customer is logged in, I can deduce which type he is.
Question:
is there a way to dynamically create form with appropriate fields for specific type of customer (CustomerWithCat should see form that have inputs for name, email, catName and catRace)?
If I use java.lang.reflect.Field class to get fields from class, then I should use Field.setAccessible(true) (because fields are private) which, on the other hand violate encapsulation (and gets around getters and setters, which is not what I want).
I look at:
How to create dynamic JSF form fields
solution no.1, but I don't understand how to populate value attributes because if user is BasicCustomer then it can't reference fields from CustomerWithCat even if they are not rendered.

Java object extensions

So i'm in the process of building a movie hiring system and have come to conclusion that I want to have a class of movies (which have specific movie data stored) and then another class which will have objects which extend the specific movies (eg, copies of Star wars: the new Hope) each with their own unique ID.
How do I setup my classes so that the information for each unique movie is inherited by the copy objects? (will extending my movieCopy class by my movies class achieve what I'm trying to do? Because I was thinking that would just extend the variables of the movie class, rather than the specific attributes of each object of the movie class.
Sorry in advance for any communication errors. Please feel free to ask if you need me to clarify something.
Structure I'm trying to achieve:
Movie (class)
MovieCopy(class)
MovieCopy <- attributes of the specific movie are inherited in each copy of the movie
Your MovieCopy class (DVD, Bluray, ...) could just contain a member variable storing the associated Movie instance (actual film with title, description, ...). That way you have access to all the meta data without any awkward inheritance.
class Movie {
private long id;
private String title;
private LocalDate release;
private String contentDescription;
Movie(long id, String title) {
this.id = id;
this.title = title;
}
...
}
class MovieCopy {
private long copyId;
private Movie movie;
private LocalDate lastHired;
private LocalDate latestReturn;
MovieCopy(long id, Movie movie) {
this.copyId = id;
this.move = movie;
}
...
}
EDIT - You would populate your collection of movies like this:
Movie starWars4 = new Movie(1, "Star Wars 4");
MovieCopy starWarsDvd1 = new MovieCopy(1, starWars4);
MovieCopy starWarsDvd2 = new MovieCopy(2, starWars4);
MovieCopy starWarsDvd3 = new MovieCopy(3, starWars4);
As a result you have three copies of the same Movie.
In your case, inheritance is not very suitable. What you are trying to do is create objects. You don't even need a MovieCopy class. You store the specific details of each movie in the movie objects.
Let's assume that your movie class has a name and a durationInMinutes fields and they both have getters and setters. If you want to create a new movie copy, you can do this:
Movie movie = new Movie ();
movie.setName("Star Wars");
movie.setDurationInMinutes (150);
And then you can refer to Star Wars using the variable name --- movie.
You might have other fields in your Movie class but you get the idea, right?
Let me show you when to use inheritance: if you have a kind of movie that has some attributes that ordinary movies don't have, which I can't give you an example because there is only one kind of movie.

How to design objects for simple school application [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I want to create simple school application that provides grades,notes,presence,etc. for students,teachers and parents. I'm trying to design objects for this problem and I'm little bit confused - because I'm not very experienced in class designing. Some of my present objects are :
class PersonalData() {
private String name;
private String surename;
private Calendar dateOfBirth;
[...]
}
class Person {
private PersonalData personalData;
}
class User extends Person {
private String login;
private char[] password;
}
class Student extends Person {
private ArrayList<Counselor> counselors = new ArrayList<>();
}
class Counselor extends Person {
private ArrayList<Student> children = new ArrayList<>();
}
class Teacher extends Person {
private ArrayList<ChoolClass> schoolClasses = new ArrayList<>();
private ArrayList<Subject> subjects = new ArrayList<>();
}
This is of course a general idea. But I'm sure it's not the best way. For example I want that one person could be a Teacher and also a Parent(Counselor) and present approach makes me to have two Person objects. I want that user after successful logging in get all roles that it has (Student or Teacher or (Teacher & Parent) ). I think I should make and use some interfaces but I'm not sure how to do this right. Maybe like this:
interface Role {
}
interface TeacherRole implements Role {
void addGrade( Student student, Grade grade, [...] );
}
class Teacher implements TeacherRole {
private Person person;
[...]
}
class User extends Person{
ArrayList<Role> roles = new ArrayList<>();
}
Please if anyone could help me to make this right or maybe just point me to some literature/article that covers practical objects design.
In a system like this, it seems like you can create a User class that has all the personal properties as well as account information in it:
public class User
{
// personal properties
private String name;
private String surname;
private Calendar dateOfBirth;
// account properties;
private String login;
private String password; // note that string may be more convenient than char[]
// role properties
public ArrayList<Role> roles;
...
public bool hasRole(Role role) // or isInRole(Role role)
{ // implementation here. }
}
Then you have your Role object:
public class Role
{
private String name;
private String description;
}
Note that there is only one role class that could be any of teacher, student, parent, etc. Since the Role class is generic, we do not have functions in it such as addGrade(), since that is specific to a teacher.
When the user logs in with proper credentials, such a system would already know the roles associated with the user. Usually, role-specific tabs, links, and other UI elements would show (or not show) depending on the role. This is where you check to see if the user logged in is in a particular role (user.hasRole(...)). For each UI element whose visibility is determined by the role, you would have to have an if (user.hasRole(...)).
In regard to the composition issues, this system is one that heavily relies on relationship between objects. Let's consider the relationship between students and counselors - a counselor has students assigned to him/her. Likewise, any given student has many counselors. You've got a many-many relationship which calls for a structure that keeps track of the combination of unique student-counselor pairs:
public class StudentCounselor
{
public User student;
public User counselor;
}
And who keeps track of all of this? Most likely the system itself, not another user.
public class SystemAdministration
{
public static ArrayList<StudentCounselor> studentCounselors = new ArrayList<StudentCounselor>();
public static void addStudentCounselor(User student, User counselor)
{
// Check to see first that the student-counselor combo doesn't exist
studentCounselors.addItem(student, counselor);
// addItem may not be the precise name of the function in ArrayList.
}
// function to obtain all students of a counselor
public static ArrayList<User> getStudentsOfCounselor(User counselor)
{
// iterate through the studentCounselors ArrayList and pick only
// the Student-Counselor whose counselor is the same counselor
// as the one passed into this function.
// Then extract the student property out of the fitting
// Student-Counselor.
// Return the list of students.
}
public static ArrayList<User> getCounselorsOfStudent(User student)
{
// Similar as above, but the other way around.
}
}
You would do similar for your other relationships - parent-student, teacher-sections, etc. The SystemAdministration class is NOT a role, but the entity responsible for providing you with all the data.
As a suggestion, consider the Section object:
public class Section
{
public User teacher; // who teaches it
public Course course; // what is the subject, because > 1 teacher might teach the same one.
public TimeBlock timeBlock; // when is this section administered?
public Venue venue; // what room or what facility
}
You would have to create the TimeBlock and Venue classes. This structure, when put in an ArrayList will be able to answer the questions: "As a teacher, what sections will I teach?" and that answers the question "what subjects, when, and where will I teach them?"
As for the student, you'll need the StudentSection "combo" class:
public class StudentSection
{
public Section section;
public User student;
}
When put in an ArrayList of the SystemAdministrator class, now you can iterate through the list to extract what sections are assigned to a student (aka, the student's schedule), and likewise, who are the students of a given section.
Note that we don't have a list of related items in the User class except roles. To obtain any data, info about the logged-in user and his/her roles should be sufficient as long as you have all the data and access functions in a global (in this case SystemAdministration) structure.
There is no "right" design; it all depends on how you plan to interact with these classes/interfaces. Try to sketch the methods you intend to call, in the most natural possible way, and work from those to understand what a good layout for your classes could be. If you feel brave, try learning the Test Driven Development methodology; writing actual unit tests before the "real" code can help make your mind on the class structures.
As a general suggestion, try to avoid inheritance, and favor composition instead. Having an array of Role elements is a step towards that direction; try to understand you plan to interact with these roles, and add methods accordingly.

Categories

Resources