By: Team F09-B1 Since: AUG 2017 Licence: MIT
- 1. Setting up
- 2. Design
- 3. Implementation
- 3.1. Undo/Redo mechanism
- 3.2. Logging
- 3.3. Configuration
- 3.4. Add Picture
- 3.5. Auto-complete Feature
- 3.6. Swap Room Command
- 3.7. Highlight Command
- 3.8. Temporary person mechanism
- 3.9. Import mechanism
- 3.10. Backup Command
- 3.11. Add Event Command
- 3.12. Delete Event Command
- 3.13. Switch Tab Command
- 3.14. Sort Command
- 3.15. RemoveTag Command
- 3.16. Deletebytag Command
- 3.17. PersonPanel Interface
- 3.18. Calendar Interface
- 3.19. UI Styling
- 3.20. Events and EventBook
- 4. Documentation
- 5. Testing
- 6. Dev Ops
- Appendix A: Suggested Programming Tasks to Get Started
- Appendix B: User Stories
- Appendix C: Use Cases
- Appendix D: Non Functional Requirements
- Appendix E: Glossary
-
JDK
1.8.0_60or laterℹ️Having any Java 8 version is not enough.
This app will not work with earlier versions of Java 8. -
IntelliJ IDE
ℹ️IntelliJ by default has Gradle and JavaFx plugins installed.
Do not disable them. If you have disabled them, go toFile>Settings>Pluginsto re-enable them.
-
Fork this repo, and clone the fork to your computer
-
Open IntelliJ (if you are not in the welcome screen, click
File>Close Projectto close the existing project dialog first) -
Set up the correct JDK version for Gradle
-
Click
Configure>Project Defaults>Project Structure -
Click
New…and find the directory of the JDK
-
-
Click
Import Project -
Locate the
build.gradlefile and select it. ClickOK -
Click
Open as Project -
Click
OKto accept the default settings -
Open a console and run the command
gradlew processResources(Mac/Linux:./gradlew processResources). It should finish with theBUILD SUCCESSFULmessage.
This will generate all resources required by the application and tests.
-
Run the
seedu.room.MainAppand try a few commands -
Run the tests to ensure they all pass.
This project follows oss-generic coding standards. IntelliJ’s default style is mostly compliant with ours but it uses a different import order from ours. To rectify,
-
Go to
File>Settings…(Windows/Linux), orIntelliJ IDEA>Preferences…(macOS) -
Select
Editor>Code Style>Java -
Click on the
Importstab to set the order-
For
Class count to use import with '*'andNames count to use static import with '*': Set to999to prevent IntelliJ from contracting the import statements -
For
Import Layout: The order isimport static all other imports,import java.*,import javax.*,import org.*,import com.*,import all other imports. Add a<blank line>between eachimport
-
Optionally, you can follow the UsingCheckstyle.adoc document to configure Intellij to check style-compliance as you write code.
After forking the repo, links in the documentation will still point to the se-edu/addressbook-level4 repo. If you plan to develop this as a separate product (i.e. instead of contributing to the se-edu/addressbook-level4) , you should replace the URL in the variable repoURL in DeveloperGuide.adoc and UserGuide.adoc with the URL of your fork.
Set up Travis to perform Continuous Integration (CI) for your fork. See UsingTravis.adoc to learn how to set it up.
Optionally, you can set up AppVeyor as a second CI (see UsingAppVeyor.adoc).
|
ℹ️
|
Having both Travis and AppVeyor ensures your App works on both Unix-based platforms and Windows-based platforms (Travis is Unix-based and AppVeyor is Windows-based) |
When you are ready to start coding,
-
Get some sense of the overall design by reading the Architecture section.
-
Take a look at the section Suggested Programming Tasks to Get Started.
Figure 2.1.1 : Architecture Diagram
The Architecture Diagram given above explains the high-level design of the App. Given below is a quick overview of each component.
|
💡
|
The .pptx files used to create diagrams in this document can be found in the diagrams folder. To update a diagram, modify the diagram in the pptx file, select the objects of the diagram, and choose Save as picture.
|
Main has only one class called MainApp. It is responsible for,
-
At app launch: Initializes the components in the correct sequence, and connects them up with each other.
-
At shut down: Shuts down the components and invokes cleanup method where necessary.
Commons represents a collection of classes used by multiple other components. Two of those classes play important roles at the architecture level.
-
EventsCenter: This class (written using Google’s Event Bus library) is used by components to communicate with other components using events (i.e. a form of Event Driven design) -
LogsCenter: Used by many classes to write log messages to the App’s log file.
The rest of the App consists of four components.
Each of the four components
-
Defines its API in an
interfacewith the same name as the Component. -
Exposes its functionality using a
{Component Name}Managerclass.
For example, the Logic component (see the class diagram given below) defines it’s API in the Logic.java interface and exposes its functionality using the LogicManager.java class.
Figure 2.1.2 : Class Diagram of the Logic Component
The Sequence Diagram below shows how the components interact for the scenario where the user issues the command delete 1.
Figure 2.1.3a : Component interactions for delete 1 command (part 1)
|
ℹ️
|
Note how the Model simply raises a ResidentBookChangedEvent when the Resident Book data are changed, instead of asking the Storage to save the updates to the hard disk.
|
The diagram below shows how the EventsCenter reacts to that event, which eventually results in the updates being saved to the hard disk and the status bar of the UI being updated to reflect the 'Last Updated' time.
Figure 2.1.3b : Component interactions for delete 1 command (part 2)
|
ℹ️
|
Note how the event is propagated through the EventsCenter to the Storage and UI without Model having to be coupled to either of them. This is an example of how this Event Driven approach helps us reduce direct coupling between components.
|
The sections below give more details of each component.
Figure 2.2.1 : Structure of the UI Component
API : Ui.java
The UI consists of a MainWindow that is made up of parts e.g.CommandBox, ResultDisplay, PersonListPanel, StatusBarFooter, BrowserPanel etc. All these, including the MainWindow, inherit from the abstract UiPart class.
The UI component uses JavaFx UI framework. The layout of these UI parts are defined in matching .fxml files that are in the src/main/resources/view folder. For example, the layout of the MainWindow is specified in MainWindow.fxml
The UI component,
-
Executes user commands using the
Logiccomponent. -
Binds itself to some data in the
Modelso that the UI can auto-update when data in theModelchange. -
Responds to events raised from various parts of the App and updates the UI accordingly.
Figure 2.3.1 : Structure of the Logic Component
Figure 2.3.2 : Structure of Commands in the Logic Component. This diagram shows finer details concerning XYZCommand and Command in Figure 2.3.1
API :
Logic.java
-
Logicuses theResidentBookParserclass to parse the user command. -
This results in a
Commandobject which is executed by theLogicManager. -
The command execution can affect the
Model(e.g. adding a person) and/or raise events. -
The result of the command execution is encapsulated as a
CommandResultobject which is passed back to theUi.
Given below is the Sequence Diagram for interactions within the Logic component for the execute("delete 1") API call.
Figure 2.3.1 : Interactions Inside the Logic Component for the delete 1 Command
Figure 2.4.1 : Structure of the Model Component
API : Model.java
The Model,
-
stores a
UserPrefobject that represents the user’s preferences. -
stores the Resident Book data.
-
exposes an unmodifiable
ObservableList<ReadOnlyPerson>that can be 'observed' e.g. the UI can be bound to this list so that the UI automatically updates when the data in the list change. -
does not depend on any of the other three components.
Figure 2.5.1 : Structure of the Storage Component
API : Storage.java
The Storage component,
-
can save
UserPrefobjects in json format and read it back. -
can save the Resident Book data in xml format and read it back.
This section describes some noteworthy details on how certain features are implemented.
The undo/redo mechanism is facilitated by an UndoRedoStack, which resides inside LogicManager. It supports undoing and redoing of commands that modifies the state of the resident book (e.g. add, edit). Such commands will inherit from UndoableCommand.
UndoRedoStack only deals with UndoableCommands. Commands that cannot be undone will inherit from Command instead. The following diagram shows the inheritance diagram for commands:
As you can see from the diagram, UndoableCommand adds an extra layer between the abstract Command class and concrete commands that can be undone, such as the DeleteCommand. Note that extra tasks need to be done when executing a command in an undoable way, such as saving the state of the resident book before execution. UndoableCommand contains the high-level algorithm for those extra tasks while the child classes implements the details of how to execute the specific command. Note that this technique of putting the high-level algorithm in the parent class and lower-level steps of the algorithm in child classes is also known as the template pattern.
Commands that are not undoable are implemented this way:
public class ListCommand extends Command {
@Override
public CommandResult execute() {
// ... list logic ...
}
}With the extra layer, the commands that are undoable are implemented this way:
public abstract class UndoableCommand extends Command {
@Override
public CommandResult execute() {
// ... undo logic ...
executeUndoableCommand();
}
}
public class DeleteCommand extends UndoableCommand {
@Override
public CommandResult executeUndoableCommand() {
// ... delete logic ...
}
}Suppose that the user has just launched the application. The UndoRedoStack will be empty at the beginning.
The user executes a new UndoableCommand, delete 5, to delete the 5th person in the resident book. The current state of the resident book is saved before the delete 5 command executes. The delete 5 command will then be pushed onto the undoStack (the current state is saved together with the command).
As the user continues to use the program, more commands are added into the undoStack. For example, the user may execute add n/David … to add a new person.
|
ℹ️
|
If a command fails its execution, it will not be pushed to the UndoRedoStack at all.
|
The user now decides that adding the person was a mistake, and decides to undo that action using undo.
We will pop the most recent command out of the undoStack and push it back to the redoStack. We will restore the resident book to the state before the add command executed.
|
ℹ️
|
If the undoStack is empty, then there are no other commands left to be undone, and an Exception will be thrown when popping the undoStack.
|
The following sequence diagram shows how the undo operation works:
The redo does the exact opposite (pops from redoStack, push to undoStack, and restores the resident book to the state after the command is executed).
|
ℹ️
|
If the redoStack is empty, then there are no other commands left to be redone, and an Exception will be thrown when popping the redoStack.
|
The user now decides to execute a new command, clear. As before, clear will be pushed into the undoStack. This time the redoStack is no longer empty. It will be purged as it no longer make sense to redo the add n/David command (this is the behavior that most modern desktop applications follow).
Commands that are not undoable are not added into the undoStack. For example, list, which inherits from Command rather than UndoableCommand, will not be added after execution:
The following activity diagram summarize what happens inside the UndoRedoStack when a user executes a new command:
Aspect: Implementation of UndoableCommand
Alternative 1 (current choice): Add a new abstract method executeUndoableCommand()
Pros: We will not lose any undone/redone functionality as it is now part of the default behaviour. Classes that deal with Command do not have to know that executeUndoableCommand() exist.
Cons: Hard for new developers to understand the template pattern.
Alternative 2: Just override execute()
Pros: Does not involve the template pattern, easier for new developers to understand.
Cons: Classes that inherit from UndoableCommand must remember to call super.execute(), or lose the ability to undo/redo.
Aspect: How undo & redo executes
Alternative 1 (current choice): Saves the entire resident book.
Pros: Easy to implement.
Cons: May have performance issues in terms of memory usage.
Alternative 2: Individual command knows how to undo/redo by itself.
Pros: Will use less memory (e.g. for delete, just save the person being deleted).
Cons: We must ensure that the implementation of each individual command are correct.
Aspect: Type of commands that can be undone/redone
Alternative 1 (current choice): Only include commands that modifies the resident book (add, clear, edit).
Pros: We only revert changes that are hard to change back (the view can easily be re-modified as no data are lost).
Cons: User might think that undo also applies when the list is modified (undoing filtering for example), only to realize that it does not do that, after executing undo.
Alternative 2: Include all commands.
Pros: Might be more intuitive for the user.
Cons: User have no way of skipping such commands if he or she just want to reset the state of the resident book and not the view.
Additional Info: See our discussion here.
Aspect: Data structure to support the undo/redo commands
Alternative 1 (current choice): Use separate stack for undo and redo
Pros: Easy to understand for new Computer Science student undergraduates to understand, who are likely to be the new incoming developers of our project.
Cons: Logic is duplicated twice. For example, when a new command is executed, we must remember to update both HistoryManager and UndoRedoStack.
Alternative 2: Use HistoryManager for undo/redo
Pros: We do not need to maintain a separate stack, and just reuse what is already in the codebase.
Cons: Requires dealing with commands that have already been undone: We must remember to skip these commands. Violates Single Responsibility Principle and Separation of Concerns as HistoryManager now needs to do two different things.
We are using java.util.logging package for logging. The LogsCenter class is used to manage the logging levels and logging destinations.
-
The logging level can be controlled using the
logLevelsetting in the configuration file (See Configuration) -
The
Loggerfor a class can be obtained usingLogsCenter.getLogger(Class)which will log messages according to the specified logging level -
Currently log messages are output through:
Consoleand to a.logfile.
Logging Levels
-
SEVERE: Critical problem detected which may possibly cause the termination of the application -
WARNING: Can continue, but with caution -
INFO: Information showing the noteworthy actions by the App -
FINE: Details that is not usually noteworthy but may be useful in debugging e.g. print the actual list instead of just its size
Certain properties of the application can be controlled (e.g App name, logging level) through the configuration file (default: config.json).
The add/delete picture mechanism allows the adding of an image to every individual resident.
Images are saved in the format [NAME][CONTACT].jpg to differentiate between persons with the same name
The mechanism is as two different versions: * GUI Version * CLI Version
A Picture class is implemented to record the image url of every resident.
Considering the drastically different accessible file paths between development and production mode, every Picture includes a jar URL for production mode. Both of these URLs are updated when a new image is added.
public Picture() {
this.pictureUrl = PLACEHOLDER_IMAGE;
this.jarPictureUrl = PLACEHOLDER_JAR_URL;
this.jarResourcePath = false;
}Every resident is given a default placeholder image URL on instantiation which points to the placeholder_person present in resources
public static final String PLACEHOLDER_IMAGE = System.getProperty("user.dir")
+ "/src/main/resources/images/placeholder_person.png";
public static final String PLACEHOLDER_JAR_URL = "/images/placeholder_person.png";The GUI version includes two buttons available to the user in the PersonPanel when a person is selected.
Since it does not make sense for an image to be added when no Resident is selected, the GUI buttons are automatically disabled when no resident is selected, utilizing the enableButtons method as illustrated below
private void enableButtons(boolean state) {
this.addImageButton.setDisable(!state);
this.resetImageButton.setDisable(!state);
}The add/delete image buttons is implemented in the PersonPanel with a handler for each button.
|
💡
|
Since the file paths for Production and Development environments are different as mentioned, it is imperative that we verify for resource paths.
|
private void handleAddImage() {
FileChooser picChooser = new FileChooser();
File selectedPic = picChooser.showOpenDialog(null);
if (selectedPic != null) {
try {
...
private void handleResetImage() {
try {
person.getPicture().resetPictureUrl();
if (person.getPicture().checkJarResourcePath()) {
InputStream in = this.getClass().getResourceAsStream(person.getPicture().getJarPictureUrl());
person.getPicture().setJarResourcePath();
Image personPicture = new Image(in);
...The CLI version allows the user to specify the index of the resident and directly update the image url from the command box.
Validity of the given format is check initially, throwing an InvalidImageFormatException if file type is not one of jpg/jpeg/png/bmp.
Subsequently, the validity of the index and the given image URL is checked.
public String validImageFormat(String imageUrl) throws InvalidImageFormatException {
String validFormatRegex = "(.+(\\.(?i)(jpg|jpeg|png|bmp))$)";
if (imageUrl.matches(validFormatRegex)) {
return imageUrl;
} else {
throw new InvalidImageFormatException(MESSAGE_INVALID_COMMAND_FORMAT);
}
}
public CommandResult executeUndoableCommand() throws CommandException {
List<ReadOnlyPerson> lastShownList = model.getFilteredPersonList();
if (index.getZeroBased() >= lastShownList.size()) {
throw new CommandException(Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX);
}
if (!(new File(newImageUrl).exists())) {
throw new CommandException(Messages.MESSAGE_INVALID_IMAGE_URL);
}
...The image is then saved according to whether the app is run in production or development, through checking the validity of the jar resource path
public void createResidentImage(ReadOnlyPerson resident) {
File picFile = new File(newImageUrl);
try {
if (resident.getPicture().checkJarResourcePath()) {
ImageIO.write(ImageIO.read(picFile), "jpg", new File(resident.getPicture().getJarPictureUrl()));
} else {
ImageIO.write(ImageIO.read(picFile), "jpg", new File(resident.getPicture().getPictureUrl()));
}
} catch (Exception e) {
System.out.println("Cannot create Person Image");
}
}The activity diagram below summarizes the sequence of execution:
The CLI Delete Image allows the user to specify the index of the resident and directly update the image url from the command box, as long as the index passed is valid
public CommandResult executeUndoableCommand() throws CommandException {
List<ReadOnlyPerson> lastShownList = model.getFilteredPersonList();
if (index.getZeroBased() >= lastShownList.size()) {
throw new CommandException(Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX);
}
...The deletion of the image occurs as a resetting of the image url within the Picture of the resident
public Person resetPersonImage(ReadOnlyPerson resident) {
...
Person editedResident = new Person(name, phone, email, room, timestamp, tags);
return editedResident;
}The activity diagram below summarizes the sequence of execution:
The actual update of the image is implemented by reloading the Person passed to the PersonPanel whenever the residentBook is updated.
@Subscribe
private void handlePersonPanelSelectionChangedEvent(PersonPanelSelectionChangedEvent event) {
logger.info(LogsCenter.getEventHandlingLogMessage(event));
loadPersonInformation(event.getNewSelection().person);
}
private void loadPersonInformation(ReadOnlyPerson person) {
this.person = updatePersonFromLogic(person);
name.textProperty().setValue(person.getName().toString());
phone.textProperty().setValue(person.getPhone().toString());
...Alternatives Considered:
Alternative 1: Omit creation of resident’s image
Pros: Addition of images directly from the user specified path and not saving their duplicates was considered due to it’s simplicity as well as having the added benefit of not saving a duplicate of the picture.
Cons: This would also mean that it would be impossible for the application to be portable since the images could not be possibly be bundled together when the user wants to migrate the application to another platform.
Alternative 2: Implementing Add/Delete Image as UNDOABLE commands
Pros: Implementing image commands as UNDOABLE commands would grant the user the convenience of adding back an image they accidentally deleted.
Cons: The implementation of such a feature would be very complex (especially when 'alternative 1', omitting the resident’s image is not an option). Furthermore, this would mean saving multiple images of the same person to allow for addition/deletion, which would be a huge burden on the space required to run the application.
The autocomplete mechanism implements a list of commands to be auto-completed upon user input
It is implemented as a SuggestionsProvider object complementing the TextField.
public void initAutoComplete() {
suggestions = SuggestionProvider.create((Arrays.asList(logic.getAutoCompleteList())));
TextFields.bindAutoCompletion(commandTextField, suggestions);
}The AutoComplete Class stores a list of base commands that is final. Additionally, it stores: * A string array of currently displayed autocomplete phrases which is instantiated to the base commands. * ArrayList of residents names as strings that is updated upon update in the model
public static final String[] BASE_COMMANDS = { "add", "addEvent", "addImage", "backup", "edit", "select", "delete",
...
};
private ArrayList<String> personsStringArray;
private String[] autoCompleteList;The String array of currently displayed phrases is updated upon every update instance of the user input to correctly display the current autocomplete phrases.
public void updateAutoCompleteList(String userInput) {
switch (userInput) {
case "":
this.resetAutocompleteList();
break;
case "find":
this.autoCompleteList = getConcatPersonsArray("find");
break;
...The smart feature of the autocomplete feature in that it will display person names or indexes when certain commands are typed is implemented by concatenating resident names or indexes to the end of the search phrase.
public void updateAutoCompleteList(String userInput) {
switch (userInput) {
case "":
this.resetAutocompleteList();
break;
case "find":
this.autoCompleteList = getConcatResidentsArray("find");
break;
...
private String[] getConcatResidentsArray(String command) {
String[] newAutoCompleteList = new String[personsStringArray.size()];
for (int i = 0; i < personsStringArray.size(); i++) {
if (command.equals("find")) {
newAutoCompleteList[i] = command + " " + personsStringArray.get(i);
...The swaproom command swaps the rooms of two residents specified with indexes.
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof SwaproomCommand // instanceof handles nulls
&& this.targetIndex1.equals(((SwaproomCommand) other).targetIndex1)
&& this.targetIndex2.equals(((SwaproomCommand) other).targetIndex2)) // state check
|| (other instanceof SwaproomCommand // instanceof handles nulls
&& this.targetIndex1.equals(((SwaproomCommand) other).targetIndex2)
&& this.targetIndex2.equals(((SwaproomCommand) other).targetIndex1)); // state check
}The method above is defined in SwaproomCommand.java. It is important to note that two swaproom commands with their residents' indexes swapped are still equal to each other. For example the following commands are equal:
-
swaproom 3 4 -
swaproom 4 3
The command has a alias sr. So, the following commands are equivalent:
-
swaproom 3 4 -
sr 3 4
Illegal arguments such as non-integer arguments or integers bigger than the size of the last shown list will raise a CommandException which will be displayed to the user in the command output box.
The highlight command is implemented to highlight the contacts with the tag specified.
If the tag specified does not exist, trying to highlight the persons with the tag will raise the TagNotFoundException:
public void updateHighlight(String highlightTag) {
try {
persons.updateHighlight(highlightTag);
if (!this.tags.contains(new Tag(highlightTag))) {
throw new TagNotFoundException("Tag not found");
}
} catch (IllegalValueException e) {
throw new TagNotFoundException("Tag not found");
}
}This exception is caught higher up the execution stack and the user receives a message that the tag does not exist.
To highlight the persons with the specified tags, the list of persons is indicated to be updated every time the command is run. This change is reflected in the UI with the refreshing of the persons list.
private void initHighlightStatus() {
if (person.getHighlightStatus()) {
cardPane.setStyle("-fx-border-style: solid inside; -fx-border-width: 2;"
+ "-fx-border-insets: 5; -fx-border-radius: 5; -fx-border-color: red;");
}
}The highlight command also allows removal of highlighting through input of - as tag name.
|
💡
|
This is possible since - is an invalid tag name and would not be a valid tag to be highlighted.
|
public void resetHighlightStatus() throws NoneHighlightedException {
boolean highlightReset = resetHighlightStatusHelper();
if (!highlightReset) {
throw new NoneHighlightedException("No Residents Highlighted");
}
}The following sequence diagram illustrates execution of the highlight command:
Alternatives Considered:
Alternative 1: Allow user to remove tag highlight with additional command or by specifying an invalid tag
Pros:
* Reduce possible confusion and the need to memorize - as a deletion command.
* Easier implementation.
Cons:
* User may accidentally unselect highlighted personnel upon wrong input.
The implementation of temporary persons has two parts:
-
Creating a timestamp for temporary persons
-
Deleting temporary persons
-
Updated user stories incording to user stories A Timestamp class has been implemented to record the time a person in the ResidentBook is created; more importantly, it records the time that a person will expire. A non-temporary person will never expire and has an expiry date of "null". On the other hand, a temporary person has an expiry time represented by the LocalDateTime class.
public Timestamp(long day) throws IllegalValueException {
this.creationTime = LocalDateTime.now().withNano(0).withSecond(0).withMinute(0);
if (!isValidTimestamp(day)) {
throw new IllegalValueException(MESSAGE_TIMESTAMP_CONSTRAINTS);
}
if (day > 0) {
this.expiryTime = this.creationTime.plusDays(day).withNano(0).withSecond(0).withMinute(0);
}
this.daysToLive = day;
}The level of precision chosen is to the nearest Hour. Originally, a LocalDateTime object’s precision is to the nearest nanoseconds, but this high level of precision is unnecessary to the users, and also cumbersome for developers to do tests due to the small room for difference in system time. As we can see from the code block above, the time that this person will expire is to the nearest hour, done by ignoring nanosecond, second, and minute.
When creating a temporary person, users should input temp/ followed by the number of days they want this person to remain i.e. "temp/2", without the quotation marks. The use of this temp/ prefix is optional. When temp/ is not used, a normal person which does not expire is created.
The following activity diagram shows the process of adding a temporary person.
|
ℹ️
|
Due to the nature of this implementation, testing becomes tricky. One way to test is to add a temporary person, then forward system time by the more than the number of days that this person will expire. The temporary person should not appear in the ResidentBook now. Remember to switch back your system time after testing. |
Deletion of temporary persons is done when the ResidentBook starts up. When the ResidentBook object is intialised at the ModelManager, it deletes all(and any) temporary persons.
public ResidentBook(ReadOnlyResidentBook toBeCopied) {
this();
resetData(toBeCopied);
deleteTemporary();
}A iterator iterates through the UniquePersonList and looks at the expiry time of every person. If the current time has past that of the expiry time, this person will be removed from the UniquePersonList.
public void deleteTemporary() {
UniquePersonList personsList = this.getUniquePersonList();
Iterator<Person> itr = personsList.iterator();
while (itr.hasNext()) {
Person person = itr.next();
LocalDateTime personExpiry = person.getTimestamp().getExpiryTime();
LocalDateTime current = LocalDateTime.now();
if (personExpiry != null) {
if (current.compareTo(personExpiry) == 1) {
itr.remove();
}
}
}
}The following activity diagram shows how temporary persons are deleted from the ResidentBook.
Aspect: Implementation of temporary persons
Alternative 1 (current choice): Use a LocalDateTime class to represent timestamp
Pros: Flexible level of precision according to the developer i.e. to the nearest minute, or hour, etc.
Cons: A unintended change in system time may cause persons who are not due to expire to be deleted from the ResidentBook
Alternative 2: The previous implementation of temporary person only allows it to stay for one session i.e. all temporary persons will
be deleted the next time the application starts up
Pros: This implementation circumvents the problem of change in system time
Cons: This implementation is inflexible because users cannot choose how long they want a temporary person in the ResidentBook to stay.
The import mechanism is essentially adding multiple Residents to the ResidentBook and integrating the current data with an external xml file. It is implemented by calling add function repeatedly till all the new Residents have been added to the current ResidentBook.
This command only import Residents and does not support adding of Events in v1.5.
Aspect: Implementation of Import
Alternative 1 (current choice): Add all unique Residents currently not found in ResidentBook
Pros: Removes redundancy and prevents duplication of data
Cons: Current data will not be updated if there are exisiting Resident details in the ResidentBook
Alternative 2: Add all entries found on the file specified by user, and update the details when there is a difference
Pros: Get the most updated ResidentBook with each import
Cons: Import file may be outdated and not accurate, this results in inconsistency of data.
The following is the Sequence Diagram for Import Command.
This command only import Residents and does not support adding of Events in v1.5.
Aspect: Implementation of Import
Alternative 1 (current choice): Add all unique Residents currently not found in ResidentBook
Pros: Removes redundancy and prevents duplication of data
Cons: Current data will not be updated if there are exisiting Resident details in the ResidentBook
Alternative 2: Add all entries found on the file specified by user, and update the details when there is a difference
Pros: Get the most updated ResidentBook with each import
Cons: Import file may be outdated and not accurate, this results in inconsistency of data.
The following is the Sequence Diagram for Import Command.
A button is also added onto the top bar menu to facilitate import via clicking and choosing file from FileChooser.
The Import Command is implemented this way, where user will specify the filePath:
public ImportCommand(String filePath) {
this.filePath = filePath;
}It then goes through the data in the file and calls the add command repeatedly. If an exception is caught, it will continue and ignore that entry in the imported file. For every new Resident added, the name of the Resident is added to the list which keeps track of the new entries.
private void addUniquePerson(ReadOnlyResidentBook newList, ArrayList<String> namesAdded) {
ObservableList<ReadOnlyPerson> personList = newList.getPersonList();
for (ReadOnlyPerson p : personList) {
try {
model.addPerson(p);
} catch (DuplicatePersonException e) {
continue;
}
namesAdded.add(p.getName().fullName);
}
}The following method checks if there are any new Resident added to ResidentBook.
private String getNamesFeedback(ArrayList<String> namesAdded) throws NoUniqueImport {
String namesFeedback = "";
if (namesAdded.size() == 0) {
throw new NoUniqueImport(MESSAGE_FILE_NOT_UNIQUE);
}
for (int i = 0; i < namesAdded.size(); i++) {
namesFeedback += namesAdded.get(i);
if (i + 1 != namesAdded.size()) {
namesFeedback += NAME_SEPERATOR;
}
}
return namesFeedback;
}|
ℹ️
|
If the filePath is invalid, then there are no file that is readable and hence, an exception will be thrown. Users will be notified to check their filePath. |
If the data in the file specified is exactly the same as the current ResidentBook, there is nothing to import. The NoUniqueImport exception will be throw. Users will be notified to check their file.
The following is the NoUniqueImport Exception:
public class NoUniqueImport extends Exception {
public NoUniqueImport(String message) {
super(message);
}
}The following activity diagram summarize what happens inside the ImportCommand when a user executes this command:
The backup command saves the current ResidentBook into backup.xml located in the project location.
Aspect: Implementation of Backup
Alternative 1 (current choice): Saves entire ResidentBook in a backup file
Pros: Simple and straightforward in achieving objective of keeping another copy of ResidentBook
Cons: Requires more storage space
Alternative 2: Allow user to specify which entries to be added to backup
Pros: Flexible level of precision according to the needs of the user
Cons: User may miss some entries when specifying. Hard to roll back to the latest data during crisis
One consideration for the chosen mechanism is that backup should aid during crisis, such as data corruption or lost. Hence, backing up the entire file is the safest choice for administrator staffs. The following function saves the ResidentBook and images.
@Override
public void backupResidentBook(ReadOnlyResidentBook residentBook) throws IOException {
saveResidentBook(residentBook, getDirAbsolutePath() + backup_location);
backupImages();
}Apart from the Resident details, Backup command also includes saving the images uploaded by user previously.
public void backupImages() throws IOException {
String backupFolder = getDirAbsolutePath() + File.separator + Picture.FOLDER_NAME + "_backup";
String originalFolder = getDirAbsolutePath() + File.separator + Picture.FOLDER_NAME;
handleImageBackupFolder(backupFolder, originalFolder);
handleImagesBackupFiles(backupFolder, originalFolder);
}Check is done to make sure that folder where images are saved exists before creating a backup folder. If the staff did not save any pictures for the Residents, no backup folder will be created.
private void handleImageBackupFolder(String backupFolder, String originalFolder) throws IOException {
File source = new File(originalFolder);
if (source.exists()) {
boolean backupExist = new File(backupFolder).exists();
if (!backupExist) {
boolean isSuccess = (new File(backupFolder)).mkdirs();
if (!isSuccess) {
throw new IOException();
}
}
}
}If the staff saved images for the Residents, the images will be copied from the source folder to the backup folder as seen below.
private void handleImagesBackupFiles(String backupFolder, String originalFolder) throws IOException {
File source = new File(originalFolder);
if (source.exists()) {
File[] listOfImages = source.listFiles();
for (int i = 0; i < listOfImages.length; i++) {
File dest = new File(backupFolder + File.separator + listOfImages[i].getName());
copy(listOfImages[i], dest);
}
}
}The following is the activity diagram of Backup Comand.
For future enhancement, developers may consider allowing user to specify backup location and file name.
The addevent command adds an Event to the EventBook. The format for the current command is:
addevent ti/TITLE des/DESCRIPTION loc/LOCATION [time/STARTTIME TO ENDTIME or STARTTIME DURATION (in hours)]
If the event being added already exists in the EventBook, executing the add event command raises a DuplicateEventException:
@Override
public CommandResult executeUndoableCommand() throws CommandException {
requireNonNull(model);
try {
model.addEvent(toAdd);
return new CommandResult(String.format(MESSAGE_SUCCESS, toAdd));
} catch (DuplicateEventException e) {
throw new CommandException(MESSAGE_DUPLICATE_EVENT);
}
}Furthermore, if the date is not a valid date (for eg. 29/02/2017) or the event spans for more than one day, the user will receive appropriate error messages:
Aspect: Allow tentative events
Alternative 1 (current choice): Tentative events with empty location or datetime fields are not allowed. User needs to specify every field to execute the command.
Pros: Easier to implement. Fewer validations needed. Removes ambiguity from the Events List.
Cons: User cannot add tentative events or has to use a "tentative" or "TBC" placeholder to indicate tentativeness.
Alternative 2: Allow tentative events for which the Location or Datetime have not yet been finalised.
Pros: Allows users to plan for events using the application itself and edit the event as plans get more finalised.
Cons: Need to add more validations and checks for implementing tentative fields. Sorting list consisting of tentative fields might become an issue.
The deleteEvent command deletes an Event from the EventBook. The format for the current command is:
deleteEvent INDEX (must be a positive integer)
If the index passed to the deleteEvent command as argument is greater than the number of events in the EventBook, a CommandException is raised on execution (in DeleteEventCommand.executeUndoableCommand()):
List<ReadOnlyEvent> lastShownList = model.getFilteredEventList();
if (targetIndex.getZeroBased() >= lastShownList.size()) {
throw new CommandException(Messages.MESSAGE_INVALID_EVENT_DISPLAYED_INDEX);
}The switch tab command allows users to switch between the Residents List and the Events lists from the Command Line Interface.
The two possible commands are switch 1 which switches to Residents List and switch 2 switches to the Events List
If an invalid argument such as a or 5 is passed with the switch command, a ParseException is raised:
public SwitchTabCommand parse(String args) throws ParseException {
try {
int index = ParserUtil.parseIndex(args).getOneBased();
if (index > 2 || index < 1) {
throw new IllegalValueException(MESSAGE_INVALID_COMMAND_FORMAT);
}
return new SwitchTabCommand(index);
} catch (IllegalValueException ive) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, SwitchTabCommand.MESSAGE_USAGE));
}
}Furthermore, if a SwitchTabCommand command is successfully made with invalid arguments by another class (such as when running tests), a CommandException will be raised when the command is executed:
@Override
public CommandResult execute() throws CommandException {
if (targetIndex > 2 || targetIndex < 1) {
throw new CommandException(MESSAGE_USAGE);
}
EventsCenter.getInstance().post(new SwitchTabRequestEvent(targetIndex));
return new CommandResult(String.format(MESSAGE_SWITCH_TAB_SUCCESS, tabName));
}If successfully executed, the command posts a new SwitchTabRequestEvent. This event is later handled in the UI:MainWindow:
public void switchTab(int index) {
tabPane.getSelectionModel().select(index);
}
@Subscribe
private void handleSwitchTabEvent(SwitchTabRequestEvent event) {
logger.info(LogsCenter.getEventHandlingLogMessage(event));
switchTab(event.targetIndex);
}Aspect: Passing of tab-number to switch
Alternative 1 (current choice): User needs to specify using the tab-number which tab should to be selected
Pros: Easy to implement and track. The user can be certain of the expected outcome without even knowing the current state of the application.
Cons: Requires an extra field from the user. Need to parse and validate the arguments which induces latency and makes the application more prone to bugs
Alternative 2: switch should be able to detect the current tab and switch tabs without taking in any arguments.
Pros: Removes the need for parsing and validating any arguments
Cons: More complicated implementation as it is dependent on the current state of the UI. Harder to test and debug.
The sort command is implemented to sort the current Resident book according to the following possible criteria: * name * phone * room * email
By default, the list is sorted by name. It is important to note that after every other command such as add, edit or delete, the sort is run again to maintain the order of the list.
If the list is already sorted by a particular field, trying to sort it by the same field will raise an AlreadySortedException:
public void sortBy(String sortCriteria) throws AlreadySortedException {
if (persons.getCurrentlySortedBy().equals(sortCriteria)) {
throw new AlreadySortedException("List already sorted by: " + sortCriteria);
} else {
persons.sortBy(sortCriteria);
}
}This exception is later caught higher up the execution stack and a CommandException is thrown. The user receives a message that the list is already sorted by the field.
To enable the sorting, standard FXCollections.sort is used. To enable this, ReadOnlyPerson interface extends Comparable.
The person Class which implements this interface defines compareTo to compare two fields. The following is a snippet from the compareTo method:
public int compareTo(Object otherPerson) {
ReadOnlyPerson person = (ReadOnlyPerson) otherPerson;
// If a field is "Not Set" put the corresponding person at the end of the list.
if (firstField.equals("Not Set") && secondField.equals("Not Set")) {
return 0;
} else if (!firstField.equals("Not Set") && secondField.equals("Not Set")) {
return -1;
} else if (firstField.equals("Not Set") && !secondField.equals("Not Set")) {
return 1;
} else {
return firstField.compareTo(secondField);
}
}This compareTo method gives Not Set the least priority and hence if a list is sorted by a field (say room), the residents with rooms Not Set will appear at the bottom of the list.
The RemoveTag command is implemented for fast removal of a tag from all entries in the address book. It is implemented by updating the tag list of Residents.
The motivation for implementing such a command is that the hostel/hotel administrator may need to mass delete a Tag from the person. For example, deleting the "RA" (Resident Assistant) tag when the old batch of RA steps down from operations.
Aspect: Implementation of RemoveTag
Alternative 1 (current choice): Removes all tag from Residents holding it, by looking through the current ResidentBook
Pros: Effective way, as it ensures that no one holds the tag after going through all Residents
Cons: May take a longer time when running through all Residents if the ResidentBook has large amount of data
Alternative 2: Keep a list of Residents holding the Tag, and update it when necessary
Pros: Efficient way, O(1) time in retrieving all Residents holding the Tag.
Cons: Redundancy and overhead in keeping another list of Residents. Edit, Add, Delete commands will require additional checks to prevent outdated data.
The current choice of design prevents unnecessary overhead in implementation, and is straightforward. While it may take a longer time in operation when handlinng large amount of data, it is understood that Residents population does not vary a lot. Since the number of rooms are fixed due to building design, it is safe to assume that all operations are able to complete within a reasonable amount of time.
The following is the Sequence Diagram for RemoveTag command. The alias is "rm".
|
ℹ️
|
The difference between the RemoveTag and DeleteByTag is that RemoveTag does not remove any Resident from the ResidentBook. It just removes all the specified tags attached to the Resident. |
The following shows the implementation method, where user will specify the tagName:
public RemoveTagCommand(String tagName) {
this.tagName = tagName;
}The following shows the core of RemoveTag command. It is essentially editing all Residents which holds the Tag specified by the user.
private void updateTagList(List<ReadOnlyPerson> lastShownList, int i) throws CommandException {
ReadOnlyPerson personToEdit = lastShownList.get(i);
Person editedPerson = removedTagFromPerson(personToEdit);
try {
model.updatePerson(personToEdit, editedPerson);
} catch (PersonNotFoundException e) {
throw new CommandException(MESSAGE_REMOVE_TAG_ERROR);
} catch (DuplicatePersonException e) {
throw new CommandException(MESSAGE_REMOVE_TAG_ERROR);
}
}This following section shows how the Tag specified is removed. It loops through the TagList each person has, and creates another set of updated TagList. While there will not be a duplication of tag, this defensive code ensures that indeed all specified tag is removed.
private Person removedTagFromPerson(ReadOnlyPerson personToEdit) {
assert personToEdit != null;
Set<Tag> updatedTags = new HashSet<>();
for (Tag t : personToEdit.getTags()) {
if (t.tagName.equals(this.tagName)) {
continue;
} else {
updatedTags.add(t);
}
}
return new Person(personToEdit.getName(), personToEdit.getPhone(), personToEdit.getEmail(),
personToEdit.getRoom(), personToEdit.getTimestamp(), updatedTags);
}|
ℹ️
|
If the tagName is invalid, the TagNotFoundException will be raised. |
The deletebybtag command allows users to delete residents in the addressbook that has a certain tag supplied. This command is implemented to enable the deletion of persons who have a particular tag. The motivation for implementing such a command is so that hostel/hotel administrators can mass delete a certain group of residents without going through the trouble of deleting them one by one.
Only one argument is supplied with this command, a String tag.
The sequence of steps carried out by this command is shown in the activity diagram below.
|
ℹ️
|
Deletebytag command and RemoveTag command may sound similar, but they serve totally different purpose. |
The function to actually delete the persons who have the TAG supplied is done in the UniquePersonList class.
The code belows shows it’s execution. First we define an iterator to iterate through all the persons in the list of persons.
The condition if (p.getTags().contains(tag) checks if each person has the TAG supplied.
If it does, we remove the person from the list.
The sequence diagram below shows the execution of the command.
The removeByTag(tag) method is laid out below for better understanding.
public void removeByTag(Tag tag) throws CommandException {
Iterator<Person> itr = this.iterator();
int numRemoved = 0;
while (itr.hasNext()) {
Person p = itr.next();
if (p.getTags().contains(tag)) {
itr.remove();
numRemoved++;
}
}
if (numRemoved == 0) {
throw new CommandException(Messages.MESSAGE_INVALID_TAG_FOUND);
}
}If by the end of method execution, number of people removed, numRemoved is 0, we conclude that it is because nobody has that tag supplied.
Hence, a INVALID_TAG_FOUND message will be displayed to the user.
Deletion of persons by multiple tag remains a viable enhancement to this command, but it is not implemented due to the following considerations:
-
To enable a clean workflow, hostel/hotel administrators might prefer deleting one group of people at a time.
-
Ambiguity will be introduced into this command. The user may not know if by supplying multiple tags, the application will delete persons who have all the tags supplied, or delete all persons who has any of the tags supplied.
The Person Panel interface is implemented as a JavaFX StackPane
When a PersonCard in the PersonListPanel is selected, additional information of the resident is displayed in the PersonPanel.
When no person is selected, the default PersonPanel pane is loaded with the image edition buttons disable and all fields set as -.
private void loadDefaultScreen() {
name.textProperty().setValue("No Resident Selected");
phone.textProperty().setValue("-");
address.textProperty().setValue("-");
email.textProperty().setValue("-");
enableButtons(false);
}The update of information in the PersonPanel is handled by the following method and loadPersonInformation is invoked every time a change is detected.
@Subscribe
private void handlePersonPanelSelectionChangedEvent(PersonPanelSelectionChangedEvent event) {
logger.info(LogsCenter.getEventHandlingLogMessage(event));
loadPersonInformation(event.getNewSelection().person);
}To load the image of the person in the PersonPanel, it is imperative that the jar path is checked to indicated production or development environments.
private void initImage() {
try {
initProjectImage();
} catch (Exception pfnfe) {
try {
initJarImage();
...Alternatives Considered:
Alternative 1: Popup Panel instead of permanent display panel
Pros:
* UI space is conserved which would leave more room for viewing Calendar events.
Cons:
* Popup window would obstruct the view of the Calendar when the user wishes to both view both resident info and Calendar at the same time.
* Future implementations could include additional event info in the Panel as well, which means it would be infeasible to make the panel small enough to implement as a popup.
The calendar interface is implemented with a JavaFX Pane Class that contains 5 by 7 AnchorPaneNodes as individual dates.
During application start up, the MainWindow will create a Pane and adds a CalendarBoxPanel object inside. CalendarBoxPanel initialises the calendar in through the following construction.
public CalendarBoxPanel(Logic logic) {
super(FXML);
calendarBox = new CalendarBox(YearMonth.now(), logic);
calendarPane.getChildren().add(calendarBox.getView());
}A CalendarBox object is created inside the CalendarBoxPanel which takes in the current date and an instance of the LogicManager that contains the list of events.
The initialisation of the CalendarBox object is provided below.
public CalendarBox(YearMonth yearMonth, Logic logic) {
this.logic = logic;
currentYearMonth = yearMonth;
allCalendarDays = new ArrayList<>(35);
makeCalendarSkeleton();
makeCalendarNavigationTool();
populateCalendar(yearMonth, logic.getFilteredEventList());
// Create the calendar view
view = new VBox(titleBar, dayLabels, calendar);
VBox.setMargin(titleBar, new Insets(0, 0, 10, 0));
}The calendar is made in broadly 3 steps.
-
makeCalendarSkeleton()makes the skeleton for the calendar, i.e. grids for one month, and label for days of the week. -
makeCalendarNavigationTool()creates the entire navigation tool for the calender, i.e. title, previous-month button, next-month button -
populateCalendar(yearMonth, logic.getFilteredEventList())set the days of the calendar to correspond to the appropriate date, with events populated at their corresponding dates
When a new event is added or an existing event is removed, the calendar updates the change dynamically by repopulating the calendar with the updated list of events.
This is done through the help of the EventBus shown below, which will call the method handleCalenderBoxPanelChange(EventBookChangedEvent event) whenever an instance of EventBookChangedEvent is raised.
@Subscribe
public void handleCalenderBoxPanelChange(EventBookChangedEvent event) {
logger.info(LogsCenter.getEventHandlingLogMessage(event));
calandarBoxPanel.getCalendarBox().refreshCalendar(this.logic);
}For navigation to the previous or next month in the calendar, a click on the "PREV" or "NEXT" button will trigger a method to repopulate the calendar with dates
and events of the appropriate month. This can also be done through the CLI by typing prev or next at the command bar.
The sequence diagram for prev command is shown below. next works in a similar way.
The implementation of previousMonth() is illustrated here. nextMonth() works in a similar way.
private void previousMonth() {
currentYearMonth = currentYearMonth.minusMonths(1);
populateCalendar(currentYearMonth, logic.getFilteredEventList());
}Aspect: Implementation of Calendar
Alternative 1 (current choice): Repopulating a new calendar when there is a change in the EventBook
Pros: Simple to implement, and easy to understand. Simply make use of existing methods that we have written for populating the calendar for the first time.
Cons: Takes a little longer(not notably) for the calendar to be populated
Alternative 2: Use Google Calendar
Pros: Many functionalities are already created for us.
Cons: Security concerns because the ResidentBook would require User Authentication to login to Google. ResidentBook would also need to store
the username and password.
The main styling for the UI can be found in DarkTheme.css. The document has been divided into the following sections:
-
Base Styling -
Tab and Tab Pane Styling -
Split Pane and list CSS -
Button Styling -
Button Styling in Person Panel -
Dialog Pane Styling -
Scroll bar Styling -
Card Pane Styling -
Command Pane Styling -
Person Panel Styling
Here, we look at a specific section of DarkTheme.css:
/*PERSON PANEL STYLING*/
#personPanel {
-fx-background-color: #232A34;
-fx-padding: 61 35 50 35;
}
#personDetailsBox {
-fx-padding: 20 20 20 20;
-fx-background-color: #404040;
-fx-text-color: white;
}
#personDetailsBox #name {
-fx-padding: 7, 0, 0, 0;
}
#name, #phone, #address, #email {
-fx-text-fill: white;
}We prefer modifying individual ids instead of an entire class of elements to keep the CSS modular. However, do note that for .tab and .button, class selectors have been used instead of id selectors to enforce a uniform looks for all buttons and tabs throughout the application.
It is important to note that not all the styling properties are defined in DarkTheme.css. For example, the colors for the tags are defined in PersonCard.java:
private static ArrayList<String> colors = new ArrayList<String>(Arrays.asList(
"#cc6600", "#cc0000", "#d11141", "#00b159", "#00aedb",
"#f37735", "#ffc425", "#a200ff", "#742323", "#757a25", "#237629",
"#2c2972", "#732474"));
private static String getColorForTag(String tag) {
if (!tagColor.containsKey(tag)) {
String chosenColor = colors.get(random.nextInt(colors.size()));
tagColor.put(tag, chosenColor);
}
return tagColor.get(tag);
}-
Please refrain from using
!importantbecause it induces ambiguity and reduces modularity in the codebase -
Use
idsinstead ofclassesas css selectors. -
If the new UI Styling is drastically different from the current version, consider putting it in a new file and changing the loaded css to that instead of the current
DarkTheme.css -
Do not use
element.setStyle()unless there is no way using CSS to achieve the same. Using such methods induces difficulty in tracking the source of the styling making it cumbersome to edit later.
In version 1.4 and above, the application has been expanded to allow not only list of Residents but also of Events. The rationale behind is to allow the hostel management staff be aware of the events taking place in the hostel and make necessary preparations for the same. This section breifly explains the implementation of Events and the EventBook at four different levels: Model Logic UI and Storage
At the model level, the Event class describes the behavior of an Event object. It has the following fields:
-
Title -
Location -
Datetime -
Description
Each of these fields have a class of their own within seedu/room/model/event and these classes contain the definitions and validations for each field. For example lets look at a snippet from Datetime.java:
/**
* Returns true if a given string is a valid datetime in the format dd/mm/yyyy hhmm k or dd/mm/yyyy hhmm to hhmm.
*/
public static boolean isValidDatetime(String test) {
String[] components = test.split(" ");
String date = components[0];
String startTime = components[1];
//If the format is dd/mm/yyyy hhmm k
if (components.length == 3) {
String duration = components[2];
return isValidDate(date) && isValidTime(startTime) && isValidDuration(duration);
//If the format is dd/mm/yyyy hhmm to hhmm
} else if (components.length == 4) {
String endtime = components[3];
return isValidDate(date) && isValidTime(startTime) && isValidTime(endtime);
} else {
return false;
}
}This snippet shows how the application checks for invalid an Datetime when a user tries to add an event to the EventBook. Note that currently, the current implementation of Datetime disallows multi-day Events.
It is important to note that two Event objects are considered equivalent (i.e .equals returns true) if their Title, Location and Datetime are the equivalent irregardless of whether the Description is the same or not. This is because a user may try to add an Event again if he/see forgets that it has already been added before. In such a senario, it is very unlikely that the Description for both the attempts to add the events will be the same but the Title, Location and Datetime would probably be the same.
If an event is being added to the EventBook when an equivalent event already exists, a DuplicateEventException will be thrown by the Model
EventBook implements a ReadOnlyEventBook and is responsible for maintaining the list of Events for the Logic and UI to query and update. The notable methods defined for EventBook are:
-
setEvents(List<? extends ReadOnlyEvent> events) -
resetData(ReadOnlyEventBook newData) -
addEvent(ReadOnlyEvent e) -
updateEvent(ReadOnlyEvent target, ReadOnlyEvent editedReadOnlyEvent) -
removeEvent(ReadOnlyEvent key) -
sortBy(String sortCriteria) -
getEventList()
Some important things to note about EventBook:
-
By default, the events are sorted by
Title -
Querying for events may throw a
EventNotFoundExceptionand adding events may throw aDuplicateEventException
-
Implement a better sort for
Events. Although they can be sorted by *Title,Location,DatetimeandDescription, a user would like to see upcoming events first. So, a possible sort criteria would beNumber of days until the Event. So, the upcoming events would be at the top of the list and the past ones and others much later in the future would be further down.
At the logic level, there are two commands which allow addition and deletion of events:
-
Add Event Command:
addeventorae -
Delete Event Command:
deleteeventorde
Both these commands follow the general implementations of an Undoable Command. For more details look at their respective sections in the Developer Guide: addEvent deleteEvent
The implementation of EventBook storage follows the ResidentBook storage closely. The main methods defined by the EventBookStorage interface are:
-
getEventBookFilePath() -
readEventBook() -
readEventBook(String filePath) -
saveEventBook(ReadOnlyEventBook eventBook) -
saveEventBook(ReadOnlyEventBook eventBook, String filePath) -
backupEventBook(ReadOnlyEventBook eventBook)
The EventBook is stored in an xml file at data/eventbook.xml using a XmlSerializableEventBook object. When the application is started, the contents of this xml file are read and passed to the Model. If there is no such file found, sample data is read from SampleDataUtil and the xml file is only created if any events are added or deleted from this sample data.
The EventBook is displayed to the user as an EventCard in an EventListPanel. The EventCard displays all the necessary information about the event such as the title, date, time, location and description.
To display this data in presentable manner and not clutter the UI of the application, a TabPane is used. A TabPane allows users to switch between the Residents List and the Events List. To switch between the tabs, a user can either use the Switch Tab command or a mouse click on either of the Tabs
-
Remove unnecessary details such as
Descriptionfrom theEventCard. -
Allow
EventCardsto be selectable so that when selected, a Panel with all the details about the events is displayed -
Allow the Calendar to be clickable and selectable so that when a day is selected, the Events for the day are displayed.
We use asciidoc for writing documentation.
|
ℹ️
|
We chose asciidoc over Markdown because asciidoc, although a bit more complex than Markdown, provides more flexibility in formatting. It supports adding of new contacts and will skip known contacts residing in the resident book. |
See UsingGradle.adoc to learn how to render .adoc files locally to preview the end result of your edits.
Alternatively, you can download the AsciiDoc plugin for IntelliJ, which allows you to preview the changes you have made to your .adoc files in real-time.
See UsingTravis.adoc to learn how to deploy GitHub Pages using Travis.
We use Google Chrome for converting documentation to PDF format, as Chrome’s PDF engine preserves hyperlinks used in webpages.
Here are the steps to convert the project documentation files to PDF format.
-
Follow the instructions in UsingGradle.adoc to convert the AsciiDoc files in the
docs/directory to HTML format. -
Go to your generated HTML files in the
build/docsfolder, right click on them and selectOpen with→Google Chrome. -
Within Chrome, click on the
Printoption in Chrome’s menu. -
Set the destination to
Save as PDF, then clickSaveto save a copy of the file in PDF format. For best results, use the settings indicated in the screenshot below.
Figure 5.6.1 : Saving documentation as PDF files in Chrome
There are three ways to run tests.
|
💡
|
The most reliable way to run tests is the 3rd one. The first two methods might fail some GUI tests due to platform/resolution-specific idiosyncrasies. |
Method 1: Using IntelliJ JUnit test runner
-
To run all tests, right-click on the
src/test/javafolder and chooseRun 'All Tests' -
To run a subset of tests, you can right-click on a test package, test class, or a test and choose
Run 'ABC'
Method 2: Using Gradle
-
Open a console and run the command
gradlew clean allTests(Mac/Linux:./gradlew clean allTests)
|
ℹ️
|
See UsingGradle.adoc for more info on how to run tests using Gradle. |
Method 3: Using Gradle (headless)
Thanks to the TestFX library we use, our GUI tests can be run in the headless mode. In the headless mode, GUI tests do not show up on the screen. That means the developer can do other things on the Computer while the tests are running.
To run tests in headless mode, open a console and run the command gradlew clean headless allTests (Mac/Linux: ./gradlew clean headless allTests)
We have two types of tests:
-
GUI Tests - These are tests involving the GUI. They include,
-
System Tests that test the entire App by simulating user actions on the GUI. These are in the
systemtestspackage. -
Unit tests that test the individual components. These are in
seedu.room.uipackage.
-
-
Non-GUI Tests - These are tests not involving the GUI. They include,
-
Unit tests targeting the lowest level methods/classes.
e.g.seedu.room.commons.StringUtilTest -
Integration tests that are checking the integration of multiple code units (those code units are assumed to be working).
e.g.seedu.room.storage.StorageManagerTest -
Hybrids of unit and integration tests. These test are checking multiple code units as well as how the are connected together.
e.g.seedu.room.logic.LogicManagerTest
-
See UsingGradle.adoc to learn how to use Gradle for build automation.
We use Travis CI and AppVeyor to perform Continuous Integration on our projects. See UsingTravis.adoc and UsingAppVeyor.adoc for more details.
Here are the steps to create a new release.
-
Update the version number in
MainApp.java. -
Generate a JAR file using Gradle.
-
Tag the repo with the version number. e.g.
v0.1 -
Create a new release using GitHub and upload the JAR file you created.
A project often depends on third-party libraries. For example, Resident Book depends on the Jackson library for XML parsing. Managing these dependencies can be automated using Gradle. For example, Gradle can download the dependencies automatically, which is better than these alternatives.
a. Include those libraries in the repo (this bloats the repo size)
b. Require developers to download those libraries manually (this creates extra work for developers)
Suggested path for new programmers:
-
First, add small local-impact (i.e. the impact of the change does not go beyond the component) enhancements to one component at a time. Some suggestions are given in this section Improving a Component.
-
Next, add a feature that touches multiple components to learn how to implement an end-to-end feature across all components. The section Creating a new command:
remarkexplains how to go about adding such a feature.
Each individual exercise in this section is component-based (i.e. you would not need to modify the other components to get it to work).
|
💡
|
Do take a look at the Design: Logic Component section before attempting to modify the Logic component.
|
-
Add a shorthand equivalent alias for each of the individual commands. For example, besides typing
clear, the user can also typecto remove all persons in the list.-
Hints
-
Just like we store each individual command word constant
COMMAND_WORDinside*Command.java(e.g.FindCommand#COMMAND_WORD,DeleteCommand#COMMAND_WORD), you need a new constant for aliases as well (e.g.FindCommand#COMMAND_ALIAS). -
ResidentBookParseris responsible for analyzing command words.
-
-
Solution
-
Modify the switch statement in
ResidentBookParser#parseCommand(String)such that both the proper command word and alias can be used to execute the same intended command. -
See this PR for the full solution.
-
-
|
💡
|
Do take a look at the Design: Model Component section before attempting to modify the Model component.
|
-
Add a
removeTag(Tag)method. The specified tag will be removed from everyone in the resident book.-
Hints
-
The
ModelAPI needs to be updated. -
Find out which of the existing API methods in
ResidentBookandPersonclasses can be used to implement the tag removal logic.ResidentBookallows you to update a person, andPersonallows you to update the tags.
-
-
Solution
-
Add the implementation of
deleteTag(Tag)method inModelManager. Loop through each person, and remove thetagfrom each person. -
See this PR for the full solution.
-
-
|
💡
|
Do take a look at the Design: UI Component section before attempting to modify the UI component.
|
-
Use different colors for different tags inside person cards. For example,
friendstags can be all in grey, andcolleaguestags can be all in red.Before
After
-
Hints
-
The tag labels are created inside
PersonCard#initTags(ReadOnlyPerson)(new Label(tag.tagName)). JavaFX’sLabelclass allows you to modify the style of each Label, such as changing its color. -
Use the .css attribute
-fx-background-colorto add a color.
-
-
Solution
-
See this PR for the full solution.
-
-
-
Modify
NewResultAvailableEventsuch thatResultDisplaycan show a different style on error (currently it shows the same regardless of errors).Before
After
-
Hints
-
NewResultAvailableEventis raised byCommandBoxwhich also knows whether the result is a success or failure, and is caught byResultDisplaywhich is where we want to change the style to. -
Refer to
CommandBoxfor an example on how to display an error.
-
-
Solution
-
Modify
NewResultAvailableEvent's constructor so that users of the event can indicate whether an error has occurred. -
Modify
ResultDisplay#handleNewResultAvailableEvent(event)to react to this event appropriately. -
See this PR for the full solution.
-
-
-
Modify the
StatusBarFooterto show the total number of people in the resident book.Before
After
-
Hints
-
StatusBarFooter.fxmlwill need a newStatusBar. Be sure to set theGridPane.columnIndexproperly for eachStatusBarto avoid misalignment! -
StatusBarFooterneeds to initialize the status bar on application start, and to update it accordingly whenever the resident book is updated.
-
-
Solution
-
Modify the constructor of
StatusBarFooterto take in the number of persons when the application just started. -
Use
StatusBarFooter#handleResidentBookChangedEvent(ResidentBookChangedEvent)to update the number of persons whenever there are new changes to the residentbook. -
See this PR for the full solution.
-
-
|
💡
|
Do take a look at the Design: Storage Component section before attempting to modify the Storage component.
|
-
Add a new method
backupResidentBook(ReadOnlyResidentBook), so that the resident book can be saved in a fixed temporary location.-
Hint
-
Add the API method in
ResidentBookStorageinterface. -
Implement the logic in
StorageManagerclass.
-
-
Solution
-
See this PR for the full solution.
-
-
By creating this command, you will get a chance to learn how to implement a feature end-to-end, touching all major components of the app.
Edits the remark for a person specified in the INDEX.
Format: remark INDEX r/[REMARK]
Examples:
-
remark 1 r/Likes to drink coffee.
Edits the remark for the first person toLikes to drink coffee. -
remark 1 r/
Removes the remark for the first person.
Let’s start by teaching the application how to parse a remark command. We will add the logic of remark later.
Main:
-
Add a
RemarkCommandthat extendsUndoableCommand. Upon execution, it should just throw anException. -
Modify
ResidentBookParserto accept aRemarkCommand.
Tests:
-
Add
RemarkCommandTestthat tests thatexecuteUndoableCommand()throws an Exception. -
Add new test method to
ResidentBookParserTest, which tests that typing "remark" returns an instance ofRemarkCommand.
Let’s teach the application to parse arguments that our remark command will accept. E.g. 1 r/Likes to drink coffee.
Main:
-
Modify
RemarkCommandto take in anIndexandStringand print those two parameters as the error message. -
Add
RemarkCommandParserthat knows how to parse two arguments, one index and one with prefix 'r/'. -
Modify
ResidentBookParserto use the newly implementedRemarkCommandParser.
Tests:
-
Modify
RemarkCommandTestto test theRemarkCommand#equals()method. -
Add
RemarkCommandParserTestthat tests different boundary values forRemarkCommandParser. -
Modify
ResidentBookParserTestto test that the correct command is generated according to the user input.
Let’s add a placeholder on all our PersonCard s to display a remark for each person later.
Main:
-
Add a
Labelwith any random text insidePersonListCard.fxml. -
Add FXML annotation in
PersonCardto tie the variable to the actual label.
Tests:
-
Modify
PersonCardHandleso that future tests can read the contents of the remark label.
We have to properly encapsulate the remark in our ReadOnlyPerson class. Instead of just using a String, let’s follow the conventional class structure that the codebase already uses by adding a Remark class.
Main:
-
Add
Remarkto model component (you can copy fromRoom, remove the regex and change the names accordingly). -
Modify
RemarkCommandto now take in aRemarkinstead of aString.
Tests:
-
Add test for
Remark, to test theRemark#equals()method.
Now we have the Remark class, we need to actually use it inside ReadOnlyPerson.
Main:
-
Add three methods
setRemark(Remark),getRemark()andremarkProperty(). Be sure to implement these newly created methods inPerson, which implements theReadOnlyPersoninterface. -
You may assume that the user will not be able to use the
addandeditcommands to modify the remarks field (i.e. the person will be created without a remark). -
Modify
SampleDataUtilto add remarks for the sample data (delete yourresidentBook.xmlso that the application will load the sample data when you launch it.)
We now have Remark s for Person s, but they will be gone when we exit the application. Let’s modify XmlAdaptedPerson to include a Remark field so that it will be saved.
Main:
-
Add a new Xml field for
Remark. -
Be sure to modify the logic of the constructor and
toModelType(), which handles the conversion to/fromReadOnlyPerson.
Tests:
-
Fix
validResidentBook.xmlsuch that the XML tests will not fail due to a missing<remark>element.
Our remark label in PersonCard is still a placeholder. Let’s bring it to life by binding it with the actual remark field.
Main:
-
Modify
PersonCard#bindListeners()to add the binding forremark.
Tests:
-
Modify
GuiTestAssert#assertCardDisplaysPerson(…)so that it will compare the remark label. -
In
PersonCardTest, callpersonWithTags.setRemark(ALICE.getRemark())to test that changes in thePerson's remark correctly updates the correspondingPersonCard.
We now have everything set up… but we still can’t modify the remarks. Let’s finish it up by adding in actual logic for our remark command.
Main:
-
Replace the logic in
RemarkCommand#execute()(that currently just throws anException), with the actual logic to modify the remarks of a person.
Tests:
-
Update
RemarkCommandTestto test that theexecute()logic works.
See this PR for the step-by-step solution.
Priorities: High (must have) - * * *, Medium (nice to have) - * *, Low (unlikely to have) - *
| Priority | As a … | I want to … | So that I can… |
|---|---|---|---|
|
new user |
see usage instructions |
refer to instructions when I forget how to use the App |
|
user |
add a new person |
|
|
user |
delete a person |
remove entries that I no longer need |
|
user |
favourite a contact |
it is convenient for me to access |
|
user |
find a person by name |
locate details of persons without having to go through the entire list |
|
user |
hide private contact details by default |
minimize chance of someone else seeing them by accident |
|
user |
know which contact I have not viewed for a specified period of time |
delete those obsolete contacts |
|
user |
upload pictures for my contact |
I can store memories with my friend |
|
user |
know the crash report so that when the residentbook crashes |
restore backup |
|
user |
encrypt selected contacts |
avoid people from seeing confidential contact |
|
user |
delete contacts by tag |
remove them at one go |
|
user |
import contacts using another xml file |
add more contacts at one go |
|
user |
use autocomplete |
save typing time |
|
user |
search my contacts by tag |
make changes according to that single group |
|
user |
be able to export my residentbook information |
I can import it into another device |
|
user |
email a group of contacts by tag |
send important information efficiently |
|
user |
be able to swap the rooms of the residents |
update resident addresses conveniently |
|
user |
pin important contacts to the top of the list |
remind myself of activities |
|
user |
remove a group of contacts using a single tag |
remove contacts saved for a common purpose |
|
user |
remove a tag that is shared by a group of contacts |
update them easily when an event is over |
|
user |
be able to export my residentbook information |
I can import it into another device |
|
user |
have tag coloring |
find the category of contacts I am looking for |
|
user with many persons in the resident book |
sort persons by name |
locate a person easily |
|
user |
add temporary contacts |
don’t have to add them permanently into my contact list. |
{More to be added}
(For all use cases below, the System is the ResidentBook and the Actor is the user, unless specified otherwise)
MSS
-
User requests to list persons
-
ResidentBook shows a list of persons
-
User requests to delete a specific person in the list
-
ResidentBook deletes the person
Use case ends.
Extensions
-
2a. The list is empty. Use case ends.
-
3a. The given index is invalid. Use case resumes at step 2
-
3a1. ResidentBook shows an error message.
Use case ends
-
MSS
-
User requests to import external XML file
-
System requests for file location
-
User provides file location
-
System loads file and shows success message, along with the updated list Use case ends.
Extensions
-
1a. System detects there is no file location specified
-
1a1. System outputs message saying that the input location is incorrect Use case ends.
-
-
3a. System detects an invalid file location or finds invalid XML file
-
3a1. System asks for a new file location
-
Steps 3 is repeated until a valid file location is entered
-
Use cases resumes at step 4
-
3b. System detects not enough storage on hard drive
-
3b1. System tells user not enough space on hard drive
-
Use case ends.
MSS
-
User requests to backup file
-
System requests for backup location
-
User provides backup location
-
System backups file and shows success message Use case ends.
Extensions
-
1a. System detects there is no new file to backup
-
1a1. System outputs message saying there is nothing new to backup Use case ends.
-
-
3a. System detects an invalid backup location
-
3a1. System asks for a new backup location
-
Steps 3 is repeated until a valid backup location is entered
-
Use cases resumes at step 4
-
3b. System detects not enough storage on hard drive
-
3b1. System tells user not enough space on hard drive
-
Use case ends.
MSS
-
User requests to view unused contacts beyond a certain time (i.e. contacts not viewed for 3 years or more)
-
System asks user to input the time period
-
User input time period
-
System generates a list of contacts not view for that period or longer
-
User chooses which contact(s) to delete
-
System deletes the contact(s)
Extensions
4a. There are no unused users beyond the time period user input Use case ends.
{More to be added}
-
Should work on any mainstream OS as long as it has Java
1.8.0_60or higher installed. -
Should be able to hold up to 1000 persons without a noticeable sluggishness in performance for typical usage.
-
A user with above average typing speed for regular English text (i.e. not code, not system admin commands) should be able to accomplish most of the tasks faster using commands than using the mouse.
-
Data files should be supported by previous version of resident book (backward compatibility)
-
Data files should be portable to another computer with the same process running
-
Resident book should backup every 30 days to aid disaster recovery
-
Query in the resident book should be executed promptly
-
Resident book should not take too much resources for other applications
{More to be added}








































