CSC 309 Lecture Notes Week 2 General Design Principles High-Level - - PowerPoint PPT Presentation

csc 309 lecture notes week 2 general design principles
SMART_READER_LITE
LIVE PREVIEW

CSC 309 Lecture Notes Week 2 General Design Principles High-Level - - PowerPoint PPT Presentation

CSC309-S15-L2 Slide 1 CSC 309 Lecture Notes Week 2 General Design Principles High-Level Design Patterns Examples of Design Derivation CSC309-S15-L2 Slide 2 I. Milestone and other Jav a examples: A. www:.../309/exmaples/milestone2 B.


slide-1
SLIDE 1

CSC309-S15-L2 Slide 1

CSC 309 Lecture Notes Week 2 General Design Principles High-Level Design Patterns Examples of Design Derivation

slide-2
SLIDE 2

CSC309-S15-L2 Slide 2

  • I. Milestone and other Jav

a examples:

  • A. www:.../309/exmaples/milestone2
  • B. www:.../309/exmaples/misc-java
slide-3
SLIDE 3

CSC309-S15-L2 Slide 3

  • II. What is design?
  • A. Abstraction of implementation.
  • 1. Abstraction means things get left out.
  • 2. Simply put,

design leaves out method code bodies.

  • 3. This is an over simplification.
  • 4. There are several levels of design.
slide-4
SLIDE 4

CSC309-S15-L2 Slide 4

What is design, cont’d

  • B. Levels of design abstraction.
  • 1. Packaging Design
  • a. Largest modular units.
  • b. Pkg names, descriptions, communication.
  • c. Separate applications and servers.
slide-5
SLIDE 5

CSC309-S15-L2 Slide 5

What is design, cont’d

  • 2. Abstract Class Design
  • a. Classes added to packages.
  • b. Class names, descriptions; no contents.
slide-6
SLIDE 6

CSC309-S15-L2 Slide 6

What is design, cont’d

  • 3. Mid-Level Class Design
  • a. Add methods and data fields to classes.
  • b. Method and field names, descriptions; no

method signatures or concrete data reps.

  • c. Define class inheritance.
slide-7
SLIDE 7

CSC309-S15-L2 Slide 7

What is design, cont’d

  • 4. Detailed Class Design
  • a. Add full input/output signatures.
  • b. Select concrete data representations.
slide-8
SLIDE 8

CSC309-S15-L2 Slide 8

What is design, cont’d

  • 5. Functional Design
  • a. Add pre- and postconditions to methods.
  • b. Define control flow among methods.
slide-9
SLIDE 9

CSC309-S15-L2 Slide 9

What is design, cont’d

  • C. At any lev

el, apply suitable patterns.

  • D. We’ll start with two patterns:
  • 1. "Model/View/Process".
  • 2. "Information Processing Tool".
slide-10
SLIDE 10

CSC309-S15-L2 Slide 10

  • III. What is a design pattern?
  • A. From architect Christopher Alexander:

"Each pattern describes a problem which

  • ccurs over and over again ... "
  • B. The same applies to software.
  • C. For software, notation is design diagrams,

code templates, step-by-step descriptions.

slide-11
SLIDE 11

CSC309-S15-L2 Slide 11

  • IV. The MVP pattern
  • A. Separate core processing from GUI and

underlying support.

  • 1. Model is directly traceable to abstract spec.
  • 2. View is concrete GUI.
  • 3. Process is underlying support.
slide-12
SLIDE 12

CSC309-S15-L2 Slide 12

MVP, cont’d

  • B. Correspondence between models and com-

panion views.

  • 1. There is typically a canonical view.
  • 2. May also be additional views.
  • 3. Both model and view classes are directly

traceable to requirements spec.

slide-13
SLIDE 13

CSC309-S15-L2 Slide 13

MVP, cont’d

  • C. General diagram of MVP ...
slide-14
SLIDE 14

CSC309-S15-L2 Slide 14

Model View Model getView setView View Model Screen Window View run compose show hide setModel getModel getWindow isShown isEditable setEditable Tool-Specific Model Class Z Tool-Specific Model Class A Auxilary View Class for Model A Auxilary View Class for Model A Canonical View Class for Model Z Auxilary View Class for Model Z Auxilary View Class for Model Z Canonical View Class for Model A

. . . . . .

slide-15
SLIDE 15

CSC309-S15-L2 Slide 15

MVP, cont’d

  • 1. Figure shows data members and methods

for abstract Model and View classes.

  • 2. Defined in 309 Java class library.
slide-16
SLIDE 16

CSC309-S15-L2 Slide 16

  • V. "Info Processing Tool" pattern
  • A. Used to layout high-level packaging.
  • B. In conjunction with MVP.
  • C. Applies to 309 applications specifically.
  • D. Major functional groupings consist of a pair
  • f model/view packages.
slide-17
SLIDE 17

CSC309-S15-L2 Slide 17

Top-Level Tool Package Functional Model Package N Functional Model Package A Top-Level Model Package Companion View Package N Companion View Package A Top-Level View Package

slide-18
SLIDE 18

CSC309-S15-L2 Slide 18

  • E. IPT pattern info sources:
  • 1. The organization of the top-level GUI
  • 2. The organization of the end-user require-

ments scenarios

  • 3. Modular organization of the abstract

Java/UML model

slide-19
SLIDE 19

CSC309-S15-L2 Slide 19

  • VI. Calendar Tool example from 308.
  • A. Similar in size, scope to 308/309 projects.
  • B. We’ll continue this quarter with design and

implementation.

slide-20
SLIDE 20

CSC309-S15-L2 Slide 20

  • VII. Applying Info-Processing-Tool pattern
  • A. Eight modules in Cal Tool spec:
  • 1. File -- file processing
  • 2. Edit -- general editing
  • 3. Schedule -- item scheduling
  • 4. View -- viewing calendars
slide-21
SLIDE 21

CSC309-S15-L2 Slide 21

Applying patterns, cont’d

  • 5. Admin -- managing databases
  • 6. Options -- managing options
  • 7. CalDB -- underlying calendar database
  • 8. Server -- host server and communication
slide-22
SLIDE 22

CSC309-S15-L2 Slide 22

Applying patterns, cont’d

  • B. From derivation pattern, we get eight model

packages.

  • C. Applying IPT, we add a top-level tool pack-

age, and companion view packages.

  • D. Diagram:
slide-23
SLIDE 23

CSC309-S15-L2 Slide 23

caltool schedule edit file view

  • ptions

admin caldb server view model schedule edit file view

  • ptions

admin

slide-24
SLIDE 24

CSC309-S15-L2 Slide 24

  • E. Note no companion UIs for CalDB and

Server pkgs.

  • F. Derived top-level tool class in

implementation/source/ java/caltool/model/ CalendarTool.java:

slide-25
SLIDE 25

CSC309-S15-L2 Slide 25

CalendarTool.java

package caltool.model; import caltool.view.*; import caltool.model.file.*; import caltool.model.edit.*; import caltool.model.schedule.*; import caltool.model.view.*; import caltool.model.admin.*; import caltool.model.options.*; import caltool.model.help.*; import caltool.model.caldb.*; import mvp.Model;

slide-26
SLIDE 26

CSC309-S15-L2 Slide 26

CalTool.java, cont’d /**** * * Class CalendarTool is ... * * @author Gene Fisher (gfisher@... * @version 13apr15 * */

slide-27
SLIDE 27

CSC309-S15-L2 Slide 27

CalTool.java, cont’d

public class CalendarTool extends Model { . . . /** File-handling model class */ protected File file; . . . /** Calendar database model class */ protected CalendarDB caldb; }

slide-28
SLIDE 28

CSC309-S15-L2 Slide 28

  • VIII. Excerpts from Cal Tool spec and

derived design.

  • A. Packaging & class design for Calendar Tool.
  • B. Refined from 308 model and prototype.
  • C. Major refinement is packages, per IPT and

Model/View patterns.

  • D. Between mid-level & detailed class design.
slide-29
SLIDE 29

CSC309-S15-L2 Slide 29

  • IX. Selected Calendar Tool java files.
  • A. caltool/model/caldb/pack-

age.html

<html> <body> Major model database classes ... </html> </body>

slide-30
SLIDE 30

CSC309-S15-L2 Slide 30

  • B. CalendarDB.java

package caltool.caldb; import caltool.schedule.*; import caltool.admin.*; import caltool.options.*; import mvp.*; import java.util.Collection;

slide-31
SLIDE 31

CSC309-S15-L2 Slide 31

/**** * * The CalendarDB is the top-level data * repository for the Calendar Tool. ...

slide-32
SLIDE 32

CSC309-S15-L2 Slide 32

See code file links at end of online notes. We’ll look at some during lecture.

slide-33
SLIDE 33

CSC309-S15-L2 Slide 33

  • C. Class diagram for Milestone 2ish design:
slide-34
SLIDE 34

CSC309-S15-L2 Slide 34

Category Calendar DB Category DB Schedule Appointment Schedule Meeting Confirm Meeting Schedule Task Schedule Event UserDB User Calendars GroupDB UserWork Space RoomDB Global Options * File User Options Requires Saving UserId Scheduled Item * User Calendar User Options Clipboard UserId Previous State Selection Context Selection File calendar. View Edit Schedule Admin Options Calendar DB Calendar Tool . . . * StartTime Details Location Duration Recurring Info Remind Info Security Priority Task Event Appointment StartOr DueDate Title EndDate Category Attendees Meeting

slide-35
SLIDE 35

CSC309-S15-L2 Slide 35

  • X. Observations on derivations in Notes 2
slide-36
SLIDE 36

CSC309-S15-L2 Slide 36

  • A. CalendarDB.java
  • 1. Traceability to spec is quite direct.
  • 2. This is a managerial class.
  • 3. Class comment derived from spec descrip.
  • 4. Derived data fields trace to spec object.
slide-37
SLIDE 37

CSC309-S15-L2 Slide 37

  • B. Schedule.java
  • 1. Another managerial class.
  • 2. Doesn’t appear in abstract model.
  • 3. Used to help model/view communication.
slide-38
SLIDE 38

CSC309-S15-L2 Slide 38

  • C. ScheduledItem.java
  • 1. Traces directly to abstract object.
  • 2. Object components are class data fields.
slide-39
SLIDE 39

CSC309-S15-L2 Slide 39

  • D. Appointment.java,

Meeting.java, Task.java, Event.java

  • 1. Also trace to spec objects.
  • 2. Inheritance relationships retained.
slide-40
SLIDE 40

CSC309-S15-L2 Slide 40

  • E. Date.java
  • 1. Straightforward translation of spec object.
  • 2. Likely replaced with Java lib class.
slide-41
SLIDE 41

CSC309-S15-L2 Slide 41

  • XI. What if abstract spec is

incomplete or inconsistent?

  • A. See 308 week 4-5 notes.
  • B. When spec is incomplete or inconsistent,

derive design directly from requirements.

slide-42
SLIDE 42

CSC309-S15-L2 Slide 42

  • XII. Intro to Jav

a library classes.

  • A. Get into the "library habit".
  • B. Ke

y packages in JFC lib:

  • 1. java.lang
  • 2. java.util
  • 3. java.io
  • 4. javax.swing
  • 5. java.awt
slide-43
SLIDE 43

CSC309-S15-L2 Slide 43

Library classes, cont’d

  • C. Packages have data structure and GUI classes

you’ll use in 309.

  • 1. Summarized UML in Week 4 in notes.
  • 2. Concrete examples in milestone and misc-

java directories.

  • 3. This week focus on intro to GUI classes.
slide-44
SLIDE 44

CSC309-S15-L2 Slide 44

  • XIII. Package javax.swing
  • A. Selected Classes:
  • Box
  • JButton
  • JComboBox
  • JLabel
  • JList
  • JMenu
  • JMenuBar
  • JMenuItem
  • JTabbedPane
  • JTextArea
  • JTextField
slide-45
SLIDE 45

CSC309-S15-L2 Slide 45

javax.swing , cont’d

  • B. Selected subpackages:
  • swing.colorchooser
  • swing.filechooser
  • swing.table
  • swing.text.html.parser
  • swing.tree
  • swing.undo
slide-46
SLIDE 46

CSC309-S15-L2 Slide 46

  • XIV. Package java.awt

Lower-level support for swing.

  • Color
  • Component
  • Event
  • Graphics2D
  • GridLayout
  • Image
slide-47
SLIDE 47

CSC309-S15-L2 Slide 47

  • XV. Designing GUIs with Swing.
  • A. Above list used widely in 309.
  • B. Figure 2 shows a typical menubar.
slide-48
SLIDE 48

Item Day Week -> Month Year Next Previous Goto Date ... Lists -> Filter -> Other User ... Windows -> Help Appointment ... Meeting ... Task ... Event ... Categories ... Appointments Meetings Tasks Events All Items Custom ... File Edit Schedule View Admin Calendar Tool Table Lists Windowing Mode ... Edit ... Options

JMenuBar Operating-system-maintained banner, except title is set using JFrame.setTitle JMenu JMenuItems JSeparator JMenus Box, containing a horizontal strut for blank spacing JFrame

slide-49
SLIDE 49

CSC309-S15-L3-4 Slide 49

Swing, cont’d

  • C. Figure 3 shows typical dialog.
slide-50
SLIDE 50

CSC309-S15-L3-4 Slide 50

public must Start Time: Duration: Date: End Date: Title: weekly Recurring? S M T W Th F S Interval: Location: Details: Priority: Schedule an Appointment Security: Category:

hr min

  • n screen

minutes before Remind? 15 OK Cancel Clear

JLabels JTextFields JTextField (disabled) JCheckBoxes (disabled) JCheckBox JComboBox JTextArea JScrollBar in a JScrollPane JButtons JFrame

slide-51
SLIDE 51

CSC309-S15-L3-4 Slide 51

Swing, cont’d

  • D. Figure 4 dialog layout with Boxes
slide-52
SLIDE 52

CSC309-S15-L3-4 Slide 52

public must Start Time: Duration: Date: End Date: Title: weekly Recurring? S M T W Th F S Interval: Location: Details: Priority: Schedule an Appointment Security: Category:

hr min

  • n screen

minutes before Remind? 15 OK Cancel Clear

Horizontal Box Vertical Box JPanel in the content pane

  • f the JFrame
slide-53
SLIDE 53

CSC309-S15-L3-4 Slide 53

  • XVI. View class naming conventions.
  • A. Standard name suffixes.
  • B. For classes that inherit from mvp.View.
  • C. Suffixes indicate general usage
slide-54
SLIDE 54

CSC309-S15-L3-4 Slide 54

View class naming, cont’d

Suffix Example UI ScheduleUI Dialog ScheduleAppointmentDialog Editor CategoriesEditor Display MonthlyAgendaDisplay ButtonListener OKScheduleAppointmentButtonListener Panel SchedulingOptionsPanel

slide-55
SLIDE 55

CSC309-S15-L3-4 Slide 55

  • XVII. Coordination of Model, View classes.
  • A. Parallel decomposition.
  • 1. Model and View classes at top of inheri-

tance hierarchy.

  • 2. Tool-specific model and view classes inherit

from these.

slide-56
SLIDE 56

CSC309-S15-L3-4 Slide 56

M/V Coordination, cont’d

  • B. High-level class decomposition follows func-

tional hierarchy.

  • C. Most important that functional hierarchy

makes sense.

slide-57
SLIDE 57

CSC309-S15-L3-4 Slide 57

  • XVIII. Example of high-level

Model/View class diagram.

slide-58
SLIDE 58

CSC309-S15-L3-4 Slide 58

ScheduleUI ScheduleMenu ScheduleAppointmentDialog ScheduleMeetingDialog ConfirmMeetingDialog ScheduleTaskDialog ScheduleEventDialog CategoriesEditor ScheduleUI compose getScheduleAppointmentDialog getScheduleMeetingDialog getConfirmMeetingDialog getScheuleTaskDialog getSchduleEventDialog getCategoriesEditor Schedule CalendarDB Categories Schedules scheduleAppointment scheduleMeeting confirmMeeting scheduleTask scheduleEvent Model View Model getView setView CalendarTool File Edit Schedule View Admin Options CalendarDB CalendarTool getFile getEdit getSchedule getCalView getAdmin getOptions getHelp View Model Screen Window View run compose show hide setModel getModel getWindow isShown isEditable setEditable

. . .

CalendarToolUI FileUI EditUI ScheduleUI ViewUI AdminUI OptionsUI CalendarToolUI constructSubviews compose composeMenuBar composeHelpSpacing

. . .

slide-59
SLIDE 59

CSC309-S15-L3-4 Slide 59

M/V class diagram, cont’d

  • A. Model and View are the root of the inheri-

tance hierarchy.

  • B. Inheriting from these are top-level model and

view classes.

  • C. Below top-level are submodels and subviews.
  • D. These also inherit from Model and View.
slide-60
SLIDE 60

CSC309-S15-L3-4 Slide 60

  • XIX. High-level M/V function diagram.

calToolUI.run main CalendarToolUI calToolUI.compose caltoolUI.show calTool.setView CalendarTool Screen

slide-61
SLIDE 61

CSC309-S15-L3-4 Slide 61

Screen CalendarTool

top-level constructor functions second-level model constructor functions

CalendarToolUI super JMenuBar constructSubviews Help

second-level view constructor functions

File Schedule View Admin Options Edit HelpUI FileUI ScheduleUI ViewUI AdminUI OptionsUI EditUI

. . .

from

main

slide-62
SLIDE 62

CSC309-S15-L3-4 Slide 62

FileUI.compose EditUI.compose ScheduleUI.compose ViewUI.compose AdminUI.compose OptionsUI.compose HelpUI.compose calToolUI.run mvp.Window composeMenuBar setMenuBar setTitle pack

GUI layout functions (bold-borders are library functions) display the GUI

  • n the screen

execute the GUI toolkit event loop (noop in Java)

calToolUI.compose caltoolUI.show calTool.setView

second-level view compose functions

. . .

slide-63
SLIDE 63

CSC309-S15-L3-4 Slide 63

High-level function diagram, cont’d

  • A. First three calls are top-level constructors.
  • 1. Screen initializes GUI.
  • 2. CalendarTool constructs models.
  • 3. CalendarMenuUI constructs views.
slide-64
SLIDE 64

CSC309-S15-L3-4 Slide 64

Function diagram, cont’d

  • B. CalendarToolUI.compose performs

UI layout.

  • 1. Subfunctions layout various UI pieces.
  • 2. Functions with bold borders are in Java and

309 libraries.

slide-65
SLIDE 65

CSC309-S15-L3-4 Slide 65

Function diagram, cont’d

  • C. CalendarTool.setView sets model to

point to view.

  • 1. Model and view mutually refer.
  • 2. Model constructed first, View constructor

passed a Model reference.

  • 3. Then Model.setView is called.
  • 4. Enables two-way communication.
slide-66
SLIDE 66

CSC309-S15-L3-4 Slide 66

Function diagram, cont’d

  • D. View.show inserts the view’s main win-

dow into UI screen.

  • E. Depending on GUI toolkit, call to

View.run may be necessary.

  • 1. In Java, run is no-op.
  • 2. In other toolkits, run starts GUI event han-

dling loop.

slide-67
SLIDE 67

CSC309-S15-L3-4 Slide 67

High-level function diagram, cont’d

  • F. Once event loop is started, all program con-

trol assumed by toolkit.

  • 1. In Java, event loop is separate thread.
  • 2. Event loop calls application methods that

listen for events.

slide-68
SLIDE 68

CSC309-S15-L3-4 Slide 68

  • XX. Overview of Event-Based Design
  • A. Event loop takes over at end of Main.
  • 1. A separate thread --

java.awt.EventDispatchThread

  • 2. MainThread terminated.
  • 3. Application methods invoked via events.
slide-69
SLIDE 69

CSC309-S15-L3-4 Slide 69

Overview, cont’d

  • B. Event-based processing in all GUI toolkits.
  • 1. Details vary widely.
  • 2. Each has an event model.
  • 3. What’s the same is main program looses

control, methods invoked through events.

slide-70
SLIDE 70

CSC309-S15-L3-4 Slide 70

  • XXI. Designing event-based programs
  • A. Tw
  • important aspects:
  • 1. Setting up event handlers.
  • 2. Handling the events.
slide-71
SLIDE 71

CSC309-S15-L3-4 Slide 71

Designing event-based, cont’d

  • B. Event handlers respond to events.
  • 1. Events are user actions.
  • 2. In Java, we set up an EventListener.
  • 3. Typical case is an ActionListener for a

menu item or button.

slide-72
SLIDE 72

CSC309-S15-L3-4 Slide 72

Designing event-based, cont’d

  • C. Event handler invokes an application

method.

  • 1. Event-invoked methods are "call-backs".
  • 2. In Java, call-backs invoked by action-

Performed method of EventListener.

slide-73
SLIDE 73

CSC309-S15-L3-4 Slide 73

Designing event-based, cont’d

  • 3. actionPerformed is specialized for

each listener.

  • 4. Each specialized actionPerformed

calls an appropriate appl’n method.

slide-74
SLIDE 74

CSC309-S15-L3-4 Slide 74

  • XXII. Design diagram notation
  • A. In function diagram, event-based invocation

is shown with a double line.

  • B. See Figure 7
slide-75
SLIDE 75

CSC309-S15-L3-4 Slide 75

main methodA methodB methodC

  • a. Normal method invocation

methodD methodE EventName

  • b. Event-based method invocation
slide-76
SLIDE 76

CSC309-S15-L3-4 Slide 76

  • XXIII. Examples
  • A. Figure 11 shows setting up event handlers.
slide-77
SLIDE 77

CSC309-S15-L3-4 Slide 77

main

. . .

CalendarToolUI. compose CalendarToolUI. composeMenuBar FileUI.compose FileMenu.compose

. . . . . . . . .

addNewItem JMenuItem addActionListener addOpenItem JMenuItem addActionListener

. . .

slide-78
SLIDE 78

CSC309-S15-L3-4 Slide 78

ScheduleUI. compose ScheduleMenu. compose

. . . . . .

addEventItem JMenuItem addActionListener scheduleEvent Dialog.compose composeButtonRow JButton OKScheduleEvent ButtonListener addActionListener

. . .

from CalendarToolUI.composeMenuBar

. . .

slide-79
SLIDE 79

CSC309-S15-L3-4 Slide 79

  • B. Figure 9 shows event-based invocation.
slide-80
SLIDE 80

CSC309-S15-L3-4 Slide 80

File.fileNew JMenuItem. actionListener. actionPerformed System.out.println MouseButton Event File.open JMenuItem. actionListener. actionPerformed System.out.println

JFileChosser. showOpenDialog

File.java: 36 FileMenu.java:113 FileMenu.java:117 FileMenu.java:135 FileMenu.java:141 FileMenu.java:146 File.java: 44

slide-81
SLIDE 81

CSC309-S15-L3-4 Slide 81

File.fileNew JMenuItem. actionListener. actionPerformed System.out.println MouseButton Event File.open JMenuItem. actionListener. actionPerformed System.out.println

JFileChosser. showOpenDialog

File.java: 36 FileMenu.java:113 FileMenu.java:117 FileMenu.java:135 FileMenu.java:141 FileMenu.java:146 File.java: 44 View and/or Controller Model

Events Handled by Toolkit’s Runtime Package Stubbed Model Method (for Milestone 2)

slide-82
SLIDE 82

CSC309-S15-L3-4 Slide 82

MouseButton Event ScheduleEventDialog. show JMenuItem. actionListener. actionPerformed

. . . . . .

ScheduleMenu.java: 128 ScheduleMenu.java: 129

slide-83
SLIDE 83

CSC309-S15-L3-4 Slide 83

OKScheduleEvent ButtonListener. actionPerformed System.out.println MouseButton Event Event.Event

Schedule. scheduleEvent

OKScheduleEvent ButtonListener.java: 41 Schedule.java: 93 OKScheduleEvent ButtonListener.java: 50 OKScheduleEvent ButtonListener.java: 50

slide-84
SLIDE 84

CSC309-S15-L3-4 Slide 84

MouseButton Event JMenuItem. actionListener. actionPerformed

MonthlyAgendaDisplay. update SmallDayViewDisplay. SmallDayViewDisplay JPanel.removeAll GridLayout.setRows MonthlyAgenda. getfirstDay MonthlyAgenda. getNextDay JPanel.add MonthlyAgendaDisplay. show

ViewMenu.java: 168 ViewMenu.java: 170 ViewMenu.java: 171 MonthlyAgenda Display.java: 186 188 193 202 203 206

slide-85
SLIDE 85

CSC309-S15-L3-4 Slide 85

MouseButton Event JMenuItem. actionListener. actionPerformed

AppointmentsList Display.update DefaultTableModel. setRowCount Lists.view AppointmentsList populateRow mvp.Window.pack

ViewMenu.java: 273 ViewMenu.java: 274 ViewMenu.java: 275 AppointmentsList Display.java: 80 86 88 93

AppointmentsList Display.show

slide-86
SLIDE 86

CSC309-S15-L3-4 Slide 86

  • 0. Schedule.java

package caltool.schedule; import caltool.caldb.*; import mvp.*; /**** * * Class Schedule is the top-level model class in the schedule package. * provides methods to schedule the four types of calendar item. * contains a Categories data field, which is the sub-model for editing * scheduled item categories. * * @author Gene Fisher (gfisher@calpoly.edu) * @version 3feb10

slide-87
SLIDE 87

CSC309-S15-L3-4 Slide 87

* */ public class Schedule extends Model { /** * Construct this with the given companion view and the parent CalendarDB * model. The CalendarDB is provided to access to its service methods that * store items in the current user calendar. * empty error exceptions for each method that throws one. * * pre: ; * * post: this.calDB == calDB && scheduleEventPrecondViolation != null; */ public Schedule(View view, CalendarDB calDB) {

slide-88
SLIDE 88

CSC309-S15-L3-4 Slide 88

super(view); this.calDB = calDB; scheduleEventPrecondViolation = new ScheduleEventPrecondViolation(); } /*-* * Derived methods */ /** * ScheduleAppointment adds the given Appointment to the current Calendar * if an appointment of the same time, duration, and title is not already * scheduled. * < * pre:

slide-89
SLIDE 89

CSC309-S15-L3-4 Slide 89

* * // * // The StartOrDueDate field is not empty and a valid date value. * // * ((appt.start_or_due_date != nnull) && appt.start_or_due_date.isValid()) * * && * * // * // If non-empty, the EndDate field is a valid date value. * // * ((appt.end_date != null) || appt.end_date.isValid()) * * && *

slide-90
SLIDE 90

CSC309-S15-L3-4 Slide 90

* // * // The duration is between 1 minute and 999 hours, inclusive. * // * ((appt.duration <= 1) && (appt.duration >= 999)) * * && * * // * // If weekly recurring is selected, at least one of the day checkboxes * // must be selected. * // * if appt.recurring.is_recurring and appt.recurring.interval?weekly * then appt.recurringInfo.details.weekly.onSun or * appt.recurringInfo.details.weekly.onMon or * appt.recurringInfo.details.weekly.onTue or

slide-91
SLIDE 91

CSC309-S15-L3-4 Slide 91

* appt.recurringInfo.details.weekly.onWed or * appt.recurringInfo.details.weekly.onThu or * appt.recurringInfo.details.weekly.onFri or * appt.recurringInfo.details.onWeekly.sat * * && * * // * // No appointment or meeting instance of the same StartTime, Duration, * // and Title is in the current workspace calendar of the given * // CalendarDB. The current calendar is * // * // cdb.workspace.calendars[1] * // * // The index is 1 since, by convention, the workspace calendar list is

slide-92
SLIDE 92

CSC309-S15-L3-4 Slide 92

* // maintained in most-recently visited order, with the first element * // being most recent and therefore current. * // * ! (exists (item in calDB.getCurrentCalendar().items) * (item.start_or_due_date.equals(appt.start_or_due_date)) && * (item.duration.equals(appt.duration)) && * (item.title.equals(appt.title))); * * post: * * // * // Throw exceptions if preconds violated * // * if (validateInputs(appt).anyErrors()) * then throw == scheduleAppointmentPrecondViolation

slide-93
SLIDE 93

CSC309-S15-L3-4 Slide 93

* * || * * if (alreadySchededuled(event)) then * then throw == scheduleAppointmentPrecondViolation * * || * * if (calDB.getCurrentCalendar() == null) then * then throw == scheduleAppointmentPrecondViolation * * || * * // * // If preconds met, a scheduled item is in the output calendar if

slide-94
SLIDE 94

CSC309-S15-L3-4 Slide 94

* // and only if it is the new appt to be added or it is in the * // input calendar. * // * (forall (item in calDB’.getCurrentCalendar().getItems()) * ((item == event) || * (item in calDB.getCurrentCalendar().items))) * * && * * (calDB’.getCurrentCalendar().getItems().size() == * calDB.getCurrentCalendar().getItems().size + 1) * * && * * (calDB’.getCurrentCalendar().requiresSaving)

slide-95
SLIDE 95

CSC309-S15-L3-4 Slide 95

* * && * * (calDB’.getCurrentCalendar().hasChanged()); * < */ public void scheduleAppointment(Appointment appt) { System.out.println("In Schedule.scheduleAppointment."); } /** * ScheduleMeeting adds a Meeting to the current calendar, based on the the * given MeetingRequest. The work is done by the three suboperations, * which determine a list of possible meetings times, set * meeting-scheduling options, and confirm the scheduling of a specific

slide-96
SLIDE 96

CSC309-S15-L3-4 Slide 96

* meeting selected from the possibles list. */ public void scheduleMeeting(MeetingRequest meeting_req) { System.out.println("In Schedule.scheduleMeeting."); } /** * Produce the list of possible meeting times that satisfy the given * MeetingRequest. */ public PossibleMeetingTimes listMeetingTimes(MeetingRequest request) { System.out.println("In schedule.listMeetingTimes."); return null; }

slide-97
SLIDE 97

CSC309-S15-L3-4 Slide 97

/** * Set the meeting options in the CalendarDB to those given. * */ public void setMeetingOptions(MeetingSchedulingOptions options) { System.out.println("In schedule.setMeetingOptions."); } /** * ConfirmMeeting takes a CalendarDB, MeetingRequest, list of * PossibleMeetingTimes, and a selected time from the list. * new CalendarDB with the given request scheduled at the selected time. */ public void confirmMeeting(MeetingRequest meeting_req, PossibleMeetingTimes possible_times, int selected_time) {

slide-98
SLIDE 98

CSC309-S15-L3-4 Slide 98

System.out.println("In Schedule.confirmMeeting"); } /** * ScheduleTask adds the given Task to the given CalendarDB, if a task of * the same start date, title, and priority is not already scheduled. */ public void scheduleTask(Task task) { System.out.println("In Schedule.scheduleTask."); } /** * ScheduleEvent adds the given Event to the given CalendarDB, if an event * of the same start date and title is not already scheduled. * <

slide-99
SLIDE 99

CSC309-S15-L3-4 Slide 99

* pre: * * // * // The Title field is at least one character long. * // * ((event.title != null) && (event.title.size() >= 1)) * * && * * // * // The StartOrDueDate field is not empty and a valid date value. * // * ((event.startOrDueDate != null) && event.startOrDueDate.isValid()) * * &&

slide-100
SLIDE 100

CSC309-S15-L3-4 Slide 100

* * // * // If non-empty, the EndDate field is a valid date value. * // * ((event.endDate == null) || event.endDate.isValid()) * * && * * // * // The current workspace is not null. * // * (calDB.getCurrentCalendar() != null) * * && *

slide-101
SLIDE 101

CSC309-S15-L3-4 Slide 101

* // * // No event of same StartDate and Title is in the current workspace * // calendar of the given CalendarDB. * // * ! (exists (item in calDB.getCurrentCalendar().items) * (item.startOrDueDatevent.equals(event.startOrDueDate)) && * (item.title.equals(event.title))); * * post: * // * // Throw exceptions if preconds violated * // * if (validateInputs(event).anyErrors()) * then throw == scheduleEventPrecondViolation *

slide-102
SLIDE 102

CSC309-S15-L3-4 Slide 102

* || * * if (alreadySchededuled(event)) then * then throw == scheduleEventPrecondViolation * * || * * if (calDB.getCurrentCalendar() == null) then * then throw == scheduleEventPrecondViolation * * || * * // * // If preconds met, a scheduled item is in the output calendar if * // and only if it is the new event to be added or it is in the

slide-103
SLIDE 103

CSC309-S15-L3-4 Slide 103

* // input calendar. * // * (forall (item in calDB’.getCurrentCalendar().getItems()) * ((item == event) || * (item in calDB.getCurrentCalendar().items))) * * && * * (calDB’.getCurrentCalendar().getItems().size() == * calDB.getCurrentCalendar().getItems().size + 1) * * && * * (calDB’.getCurrentCalendar().requiresSaving) *

slide-104
SLIDE 104

CSC309-S15-L3-4 Slide 104

* && * * (calDB’.getCurrentCalendar().hasChanged()); * < */ public void scheduleEvent(Event event) throws ScheduleEventPrecondViolation { /* * Clear out the error fields in precond violation exception object. */ scheduleEventPrecondViolation.clear(); /* * Throw a precond violation if the validity check fails on the start

slide-105
SLIDE 105

CSC309-S15-L3-4 Slide 105

* or end date. */ if (validateInputs(event).anyErrors()) { throw scheduleEventPrecondViolation; } /* * Throw a precond violation if an event of the same start date and * title is already scheduled. */ if (alreadyScheduled(event)) { scheduleEventPrecondViolation.setAlreadyScheduledError(); throw scheduleEventPrecondViolation; }

slide-106
SLIDE 106

CSC309-S15-L3-4 Slide 106

/* * Throw a precond violation if there is no currently active calendar. * Note that this condition will not be violated when interacting * through the view, since the ’Schedule Event’ menu item is disabled * whenever the there is no active calendar. */ if (calDB.getCurrentCalendar() == null) { scheduleEventPrecondViolation.setNoActiveCalendarError(); throw scheduleEventPrecondViolation; } /* * If preconditions are met, add the given event to the currently * active calendar. */

slide-107
SLIDE 107

CSC309-S15-L3-4 Slide 107

calDB.getCurrentCalendar().add(event); } /** * Change the given old appointment to the given new one in the * current calendar. */ public void changeAppointment(Appointment oldAppt, Appointment newAppt) { System.out.println("In Schedule.changeAppointment."); } /** * Delete the given appointment from the current calendar. */

slide-108
SLIDE 108

CSC309-S15-L3-4 Slide 108

public void deleteAppointment(Appointment appt) { System.out.println("In Schedule.deleteAppointment."); } /*-* * Access methods */ /** * Return the categories component. * * pre: ; * post: return == categories; */

slide-109
SLIDE 109

CSC309-S15-L3-4 Slide 109

public Categories getCategories() { return categories; } /** * Convert this to a printable string. * only converted shallow since no methods of this change the contents of * categories. The deep string conversion is of calDB.getCurrentCalendar, * since it’s the object to which the scheduling methods effect change. */ public String toString() { return "Categories: " + categories + "0 + "caldDB.currentCalendar:0 + calDB.getCurrentCalendar().toString();

slide-110
SLIDE 110

CSC309-S15-L3-4 Slide 110

} /*-* * Protected methods */ /** * Return true if there is an already scheduled event of the same title on * any of the same dates as the given event. */ protected boolean alreadyScheduled(Event e) { /* * Implementation forthcoming. */

slide-111
SLIDE 111

CSC309-S15-L3-4 Slide 111

return false; /* * The following won’t fully work, since we must check all dates. * return calDB.getCurrentCalendar().getItem( new ItemKey(e.startDate, null, null, e.title)) == null; * */ } /** * Validate the <a href= Schedule.html#scheduleEvent(Event)> ScheduleEvent * </a> precondition. Return the appropriately set

slide-112
SLIDE 112

CSC309-S15-L3-4 Slide 112

* scheduleEventPrecondViolation object. * ScheduleEventPrecondViolation.html> ScheduleEventPrecondViolation </a> * for further details. */ protected ScheduleEventPrecondViolation validateInputs(Event event) { if ((event.getTitle() == null) || (event.getTitle().length() == 0)) { scheduleEventPrecondViolation.setEmptyTitleError(); } if (! event.getStartDate().isValid()) { scheduleEventPrecondViolation.setInvalidStartDateError(); } if ((event.getEndDate() != null) && (! event.getEndDate().isValid())) {

slide-113
SLIDE 113

CSC309-S15-L3-4 Slide 113

scheduleEventPrecondViolation.setInvalidEndDateError(); } return scheduleEventPrecondViolation; } /*-* * Derived data fields */ /** Category list in which scheduled item categories are defined */ protected Categories categories;

slide-114
SLIDE 114

CSC309-S15-L3-4 Slide 114

/*-* * Process data fields */ /** Calendar database that contains the current calendar in which scheduled * items are stored */ protected CalendarDB calDB; /** Precond violation exception object */ protected ScheduleAppointmentPrecondViolation scheduleAppointmentPrecondViolation; protected ScheduleMeetingPrecondViolation scheduleMeetingPrecondViolation; protected ScheduleTaskPrecondViolation scheduleTaskPrecondViolation; protected ScheduleEventPrecondViolation scheduleEventPrecondViolation;

slide-115
SLIDE 115

CSC309-S15-L3-4 Slide 115

}

  • 0. ScheduledItem.java

package caltool.schedule; import caltool.caldb.*; import mvp.Model; /**** * * A ScheduledItem is the generic definition for the types of items stored in a * calendar. The Title component is a brief description of what the item is * for. The StartOrDueDate and EndDate components indicate when the item is

slide-116
SLIDE 116

CSC309-S15-L3-4 Slide 116

* scheduled. The Category component is used to organize items into related * color-coded categories. * * There are four specializations of ScheduledItem. * Meeting, Event, and Task, q.q.v. * * @author Gene Fisher (gfisher@calpoly.edu) * @version 6feb04 * */ public abstract class ScheduledItem extends Model { /** * Construct an empty schduled item.

slide-117
SLIDE 117

CSC309-S15-L3-4 Slide 117

*/ public ScheduledItem() { super(); } /*-* * Access methods */ /** * Return the title */ public String getTitle() { return title; }

slide-118
SLIDE 118

CSC309-S15-L3-4 Slide 118

/** * Return the . */ public Date getDate() { return startOrDueDate; } /** * Return the end date. */ public Date getEndDate() { return endDate; } /**

slide-119
SLIDE 119

CSC309-S15-L3-4 Slide 119

* Return the category. */ public Category getCategory() { return category; } /*-* * Process methods */ /** * Return the unique lookup key for this. * each subclasss per the unique key requirements described in class * <a href= UserCalendar.html> UserCalendar. </a>

slide-120
SLIDE 120

CSC309-S15-L3-4 Slide 120

* */ public abstract ItemKey getKey(); /*-* * Derived data fields */ /** Brief description of the scheduled item */ protected String title; /** Date on which item is scheduled or due. multi-purpose field of ScheduledItem. an item is a Task and whether it is recurring (Events cannot recur).

slide-121
SLIDE 121

CSC309-S15-L3-4 Slide 121

For non-recurring appointments and meetings, StartOrDueDate is used as the single date on which the item is scheduled. recurring, StartOrDueDate is the first date on which it occurs. non-recurring Task, StartOrDueDate is the single date the task is due. If the task is recurring, StartOrDueDate is the first date it is due. */ protected Date startOrDueDate; /** Last date on which item is scheduled or due. In recurring appointments, meetings, and tasks, the end date defines the last date on which the item will recur. In events, the end date defines the last date of a multi-day event. When the value of end date is empty, the StartOrDueDate component is interpreted as the single date on which the item occurs. */

slide-122
SLIDE 122

CSC309-S15-L3-4 Slide 122

protected Date endDate; /** Used to organize items into related color-coded categories */ protected Category category; }

  • 0. Appointment.java

package caltool.schedule; import caltool.caldb.*; import mvp.*;

slide-123
SLIDE 123

CSC309-S15-L3-4 Slide 123

/**** * * Class Appointment adds a number of components to a generic ScheduledItem. * The StartTime and Duration indicate when the appointment starts and how long * it lasts. The RecurringInfo defines if and how an appointment recurs. * Location is where it is held. The Security indicates who can see that the * appointment is scheduled. Priority is how important the appointment is. * RemindInfo indicates if and how the user is reminded of the appointment. * Details are free form text describing any specific appointment details. * */ public class Appointment extends ScheduledItem { /**

slide-124
SLIDE 124

CSC309-S15-L3-4 Slide 124

* Construct an empty appointment. */ public Appointment() { super(); } /** * Construct an appointment with the given field values. * store the unique key for this appointment. */ public Appointment(String title, Date startOrDueDate, Date endDate, Time startTime, Duration duration, RecurringInfo recurringInfo, Category category, String location, Security security, Priority priority, RemindInfo remindInfo, String details) {

slide-125
SLIDE 125

CSC309-S15-L3-4 Slide 125

this.title = title; this.startOrDueDate = startOrDueDate; this.endDate = endDate; this.startTime = startTime; this.duration = duration; this.recurringInfo = recurringInfo; this.category = category; this.location = location; this.security = security; this.priority = priority; this.remindInfo = remindInfo; this.details = details; itemKey = new ItemKey(startOrDueDate, startTime, duration, title, 0);

slide-126
SLIDE 126

CSC309-S15-L3-4 Slide 126

} /*-* * Access methods. */ /** * Return the start date. */ public Date getStartDate() { return startOrDueDate; } /**

slide-127
SLIDE 127

CSC309-S15-L3-4 Slide 127

* Return the end date. */ public Date getEndDate() { return endDate; } /** * Return the start time. */ public Time getStartTime() { return startTime; } /** * Return the duration.

slide-128
SLIDE 128

CSC309-S15-L3-4 Slide 128

*/ public Duration getDuration() { return duration; } /** * Return the recurring info. */ public RecurringInfo getRecurringInfo() { return recurringInfo; } /** * Return the location. */

slide-129
SLIDE 129

CSC309-S15-L3-4 Slide 129

public String getLocation() { return location; } /** * Return the security. */ public Security getSecurity() { return security; } /** * Return the priority. */ public Priority getPriority() {

slide-130
SLIDE 130

CSC309-S15-L3-4 Slide 130

return priority; } /** * Return the remind info. */ public RemindInfo getRemindInfo() { return remindInfo; } /** * Return the details. */ public String getDetails() { return details;

slide-131
SLIDE 131

CSC309-S15-L3-4 Slide 131

} /*-* * Process methods */ /** * Return the unique key for this, consisting of date, time, duration, and * title. Priority is unused at 0. * specialized in Meeting, since apppointments and meetings have the same * key formats. */ public ItemKey getKey() { return itemKey;

slide-132
SLIDE 132

CSC309-S15-L3-4 Slide 132

} /*-* * Derived data fields, in addition to those inherited from ScheduledItem. */ /** Starting time of the appointment */ protected Time startTime; /** How long the appointment lasts */ protected Duration duration; /** Defines if and how an appointment recurs */ protected RecurringInfo recurringInfo;

slide-133
SLIDE 133

CSC309-S15-L3-4 Slide 133

/** Where the appointment is held */ protected String location; /** Indicates who can see that the appointment is scheduled */ protected Security security; /** How important the appointment is */ protected Priority priority; /** Indicates if and how user is reminded */ protected RemindInfo remindInfo; /** Free-form text describing any specific appointment details */ protected String details;

slide-134
SLIDE 134

CSC309-S15-L3-4 Slide 134

/*-* * Process data field */ /** The uniqe key for storing this in the UserCalendar items list */ protected ItemKey itemKey; }

  • 0. Meeting.java

package caltool.schedule; /**** *

slide-135
SLIDE 135

CSC309-S15-L3-4 Slide 135

* A Meeting adds an Attendees component to an Appointment. * component reflects the fact that a meeting is scheduled for more than one * person, whereas an appointment is for a single user. * involves checking more than one user calendar and finding a common time * among all attendees. The description of the ScheduleMeeting operation has * further details. * */ public class Meeting extends Appointment { /** * Construct an empty meeting. */ public Meeting() {

slide-136
SLIDE 136

CSC309-S15-L3-4 Slide 136

} /*-* * Derived data field */ protected Attendees attendees; }

  • 0. Task.java

package caltool.schedule; import caltool.caldb.*;

slide-137
SLIDE 137

CSC309-S15-L3-4 Slide 137

/**** * * Like an Appointment, a Task adds a number of components to a generic * ScheduledItem. A Task differs from an Appointment as follows: (1) * Appointments have Duration and Location, Tasks do not. * Appointments, the priority is either ’Must’ or ’Optional’; for Tasks, * priority is a positive integer indicating the relative priority of a task * compared to other tasks. (3) Tasks have a CompletedFlag and CompletionDate * components; Appointments do not. * */ public class Task extends ScheduledItem { /**

slide-138
SLIDE 138

CSC309-S15-L3-4 Slide 138

* Construct an empty task. */ public Task() { } /** * Construct a task with the given field values. * unique key for this task. */ public Task(String title, Date startOrDueDate, Date endDate, Category category, Time dueTime, RecurringInfo recurringInfo, Security security, int priority, RemindInfo remindInfo, String details, boolean completedFlag, Date completionDate) { this.title = title;

slide-139
SLIDE 139

CSC309-S15-L3-4 Slide 139

this.startOrDueDate = startOrDueDate; this.endDate = endDate; this.category = category; this.dueTime = dueTime; this.recurringInfo = recurringInfo; this.security = security; this.priority = priority; this.remindInfo = remindInfo; this.details = details; this.completedFlag = completedFlag; this.completionDate = completionDate; itemKey = new ItemKey(startOrDueDate, dueTime, null, title, priority); }

slide-140
SLIDE 140

CSC309-S15-L3-4 Slide 140

/*-* * Process methods */ /** * Return the unique key for this, consisting of date, time, title, and * priority. Duration is unsed. */ public ItemKey getKey() { return itemKey; } /*-* * Derived data fields */

slide-141
SLIDE 141

CSC309-S15-L3-4 Slide 141

/** Due time of the task */ protected Time dueTime; /** Defines if and how an task recurs */ protected RecurringInfo recurringInfo; /** Indicates who can see that the task is scheduled */ protected Security security; /** Defines the relative priority of this task compared to others */ protected int priority; /** Indicates if and how user is reminded */ protected RemindInfo remindInfo;

slide-142
SLIDE 142

CSC309-S15-L3-4 Slide 142

/** Free-form text describing any specific appointment details */ protected String details; /** CompletedFlag is true if a Task has been completed, false if not. system does not enforce any specific constraints on the setting of a task’s CompletedFlag. That is, the user may set or clear it at will. Hence the meaning of the CompletedFlag is up to user interpretation, particularly for recurring tasks. */ protected boolean completedFlag; /** CompletionDate is date on which as task is completed. not enforce any specific constraints on the setting of a task’s CompletionDate (other than it being a legal Date value).

  • f the CompletionDate value is up to user interpretation, particularly
slide-143
SLIDE 143

CSC309-S15-L3-4 Slide 143

for recurring tasks. */ protected Date completionDate; /*-* * Process data field */ /** The uniqe key for storing this in the UserCalendar items list */ protected ItemKey itemKey; }

slide-144
SLIDE 144

CSC309-S15-L3-4 Slide 144

  • 0. Event.java

package caltool.schedule; import caltool.caldb.*; /**** * * An Event is the simplest type of ScheduledItem. * to a ScheduledItem is simple security. * * @author Gene Fisher (gfisher@calpoly.edu) * @version 6feb04 * */

slide-145
SLIDE 145

CSC309-S15-L3-4 Slide 145

public class Event extends ScheduledItem { /** * Construct an empty event. */ public Event() { } /** * Construct an event with the given field values. * unique key for this event. */ public Event(String title, Date startOrDueDate, Date endDate, Category category, SimpleSecurity security) {

slide-146
SLIDE 146

CSC309-S15-L3-4 Slide 146

this.title = title; this.startOrDueDate = startOrDueDate; this.endDate = endDate; this.category = category; this.security = security; itemKey = new ItemKey(startOrDueDate, null, null, title, 0); } /*-* * Access methods. */ /**

slide-147
SLIDE 147

CSC309-S15-L3-4 Slide 147

* Return the title. */ public String getTitle() { return title; } /** * Return the start date. */ public Date getStartDate() { return startOrDueDate; } /** * Return the end date.

slide-148
SLIDE 148

CSC309-S15-L3-4 Slide 148

*/ public Date getEndDate() { return endDate; } /*-* * Process methods */ /** * Return the unique key for this, consisting of date and title. * duration, and priority are unused. */ public ItemKey getKey() { return itemKey;

slide-149
SLIDE 149

CSC309-S15-L3-4 Slide 149

} /** * Convert this to a string. */ public String toString() { return "0 + "Title: " + title + "0 + "Start date: " + startOrDueDate.toString() + "0 + "End date: " + (endDate == null ? "" : endDate.toString()) + "0 + "Category: " + (category == null ? "" : category.toString()) + "0 + "Security: " + security + "0; }

slide-150
SLIDE 150

CSC309-S15-L3-4 Slide 150

/*-* * Derived data field */ /** Whether the event is public or private. */ protected SimpleSecurity security; /*-* * Process data field */ /** The uniqe key for storing this in the UserCalendar items list */ protected ItemKey itemKey;

slide-151
SLIDE 151

CSC309-S15-L3-4 Slide 151

}

  • 0. Date.java

package caltool.schedule; import mvp.*; import java.util.Calendar; import java.text.*; /**** * * Class Date is the basic unit of calendar time keeping, consisting of a day * of the week, numeric date, month, and year.

slide-152
SLIDE 152

CSC309-S15-L3-4 Slide 152

*/ public class Date extends Model implements Comparable { /** * Construct an empty Date. */ public Date() { day = null; number = 0; month = null; year = 0; } /**

slide-153
SLIDE 153

CSC309-S15-L3-4 Slide 153

* Construct a date from the given string. * the given string does not parse as a valid date. * state representation is used instead of throwing an exception because * some users may want to delay the processing of invalid dates, and hence * may not be interested in handling an exception. * * Use java.text.SimpleDateFormat and java.util.Calendar to do the work. * This means that the first time the constructor is invoked, the static * format and jCalendar data fields are initialized to new SimpleDateFormat * and Calendar objects, resp. These static values are used in all * subsequent Date constructions. */ /*@ requires true; ensures true; @*/ public Date(String dateString) {

slide-154
SLIDE 154

CSC309-S15-L3-4 Slide 154

constructJCalendarIfNecessary(); try { jCalendar.setTime(format.parse(dateString)); day = convertJavaDay(jCalendar.get(Calendar.DAY_OF_WEEK)); number = jCalendar.get(Calendar.DAY_OF_MONTH); month = MonthName.values()[jCalendar.get(Calendar.MONTH)]; year = jCalendar.get(Calendar.YEAR); jDate = jCalendar.getTime(); valid = true; } catch (ParseException e) { valid = false; }

slide-155
SLIDE 155

CSC309-S15-L3-4 Slide 155

} /** * Construct a date from the given field values. * comments in the String-valued constructor. */ public Date(DayName day, int number, MonthName month, int year) { constructJCalendarIfNecessary(); this.day = day; this.number = number; this.month = month; this.year = year;

slide-156
SLIDE 156

CSC309-S15-L3-4 Slide 156

if (valid = (day != null) && (month != null) && (((month == MonthName.January) || (month == MonthName.March) || (month == MonthName.May) || (month == MonthName.July) || (month == MonthName.August) || (month == MonthName.October) || (month == MonthName.December)) ? (number <= 31) : ((month == MonthName.April) || (month == MonthName.June) || (month == MonthName.September) || (month == MonthName.November)) ? (number <= 30) : ((year % 4 == 0) && (year % 400 != 0)) ?

slide-157
SLIDE 157

CSC309-S15-L3-4 Slide 157

(number <= 29) : (number <= 28)) && ((year >= 1) && (year <= 9999))) { jCalendar.set(year - 1900, month.ordinal(), number); jDate = jCalendar.getTime(); } } /** * Construct the static java.util.format and Calendar if this is the first * time the constructor has been called. */ protected void constructJCalendarIfNecessary() { if (format == null) { format = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.MEDIUM);

slide-158
SLIDE 158

CSC309-S15-L3-4 Slide 158

jCalendar = format.getCalendar(); } } /** * Convert a java.util.Calendar.DAY_OF_WEEK number to a * caltool.schedule.DayName enum. This is necessary because JFC does not * (necessarily) map the pseudo-enum day name literals to any particular * numeric sequence. The last time I checked, Calendar.MONDAY == 2. */ protected DayName convertJavaDay(int javaDayNum) { switch (javaDayNum) { case Calendar.SUNDAY: return DayName.Sunday; case Calendar.MONDAY: return DayName.Monday;

slide-159
SLIDE 159

CSC309-S15-L3-4 Slide 159

case Calendar.TUESDAY: return DayName.Tuesday; case Calendar.WEDNESDAY: return DayName.Wednesday; case Calendar.THURSDAY: return DayName.Thursday; case Calendar.FRIDAY: return DayName.Friday; case Calendar.SATURDAY: return DayName.Saturday; default: return null; // To placate javac } } /** * Return true if this is a valid date. */ public boolean isValid() { return valid; }

slide-160
SLIDE 160

CSC309-S15-L3-4 Slide 160

/** * Return true if this is an empty date, indicated by the date number = 0. */ public boolean isEmpty() { return number == 0; } /** * Return the string representation of this. */ public String toString() { return day.toString().concat(" ").concat(Integer.toString(number)). concat(" ").concat(month.toString()).concat(" "). concat(Integer.toString(year)); }

slide-161
SLIDE 161

CSC309-S15-L3-4 Slide 161

/** * Define equality for this as componentwise equality. */ public boolean equals(Object obj) { Date otherDate = (Date) obj; return day.equals(otherDate.day) && number == otherDate.number && month.equals(otherDate.month) && year == otherDate.year; } /** * Define compareTo using java.util.Calendar.

slide-162
SLIDE 162

CSC309-S15-L3-4 Slide 162

* dates is defined as follows: (1) invalid < valid; (2) invalid == * invalid. * */ public int compareTo(Object o) { Date otherDate = (Date) o; if ((! valid) && (! otherDate.valid)) { return 0; } if ((! valid) && (otherDate.valid)) { return -1; } if ((valid) && (! otherDate.valid)) { return 1;

slide-163
SLIDE 163

CSC309-S15-L3-4 Slide 163

} /* * If both dates are valid, compare using java.util.Date.compareTo. */ return jDate.compareTo(otherDate.jDate); } /** * Define the hash code for this as the sum of the components. * code is used in turn by ItemKey.hashCode. */ public int hashCode() { return day.hashCode() + number + month.hashCode() + year; }

slide-164
SLIDE 164

CSC309-S15-L3-4 Slide 164

/*-* * Derived data fields */ /** One of the seven standard days of the week */ protected DayName day; /** Numeric date in a month, between 1 and 31 */ protected int number; /** One of the twelve months of the year */ protected MonthName month; /** The four-digit year number. (Yes, this Calendar Tool has a Y10K problem.)

slide-165
SLIDE 165

CSC309-S15-L3-4 Slide 165

*/ protected int year; /** True if this is a valud date */ protected boolean valid; /** The JFC SimpleDateFormat object to use for date calculations. */ SimpleDateFormat format; /** The JFC

  • bject to use for date calculations. */

Calendar jCalendar; /** The java.util.Date value that represents this’ date. may be the only data rep of this, but for now we keep our own model data fields around as well. At present, the significant use of this

slide-166
SLIDE 166

CSC309-S15-L3-4 Slide 166

date rep is in this.compareTo. */ protected java.util.Date jDate; }

  • 0. DayName.java

package caltool.schedule; /**** * * Class DayName is one of the seven standard days of the week. * * @author Gene Fisher (gfisher@calpoly.edu)

slide-167
SLIDE 167

CSC309-S15-L3-4 Slide 167

* @version 25jan10 * */ public enum DayName { /** One of the seven days of the week */ Sunday, /** One of the seven days of the week */ Monday, /** One of the seven days of the week */ Tuesday, /** One of the seven days of the week */

slide-168
SLIDE 168

CSC309-S15-L3-4 Slide 168

Wednesday, /** One of the seven days of the week */ Thursday, /** One of the seven days of the week */ Friday, /** One of the seven days of the week */ Saturday }

  • 0. MonthName.java
slide-169
SLIDE 169

CSC309-S15-L3-4 Slide 169

package caltool.schedule; /**** * * Class MonthName is one of the twelve standard month of the year. * * @author Gene Fisher (gfisher@calpoly.edu) * @version 15jan10 * */ public enum MonthName { /** One of the twelve months of the year */ January,

slide-170
SLIDE 170

CSC309-S15-L3-4 Slide 170

/** One of the twelve months of the year */ February, /** One of the twelve months of the year */ March, /** One of the twelve months of the year */ April, /** One of the twelve months of the year */ May, /** One of the twelve months of the year */ June,

slide-171
SLIDE 171

CSC309-S15-L3-4 Slide 171

/** One of the twelve months of the year */ July, /** One of the twelve months of the year */ August, /** One of the twelve months of the year */ September, /** One of the twelve months of the year */ October, /** One of the twelve months of the year */ November,

slide-172
SLIDE 172

CSC309-S15-L3-4 Slide 172

/** One of the twelve months of the year */ December }

  • 0. Duration.java

package caltool.schedule; import mvp.*; /**** * * Duration is the time length of a scheduled item, in hours and minutes.

slide-173
SLIDE 173

CSC309-S15-L3-4 Slide 173

* miniumn duration value is 1 minute. The maximum is 999 houus. * */ public class Duration extends Model { /** * Construct an empty duration value. */ public Duration() { hours = 0; minutes = 0; } /**

slide-174
SLIDE 174

CSC309-S15-L3-4 Slide 174

* Construct a duration from the given hours and minutes. */ public Duration(int hours, int minutes) { this.hours = hours; this.minutes = minutes; } /** * Return true if this is an empty duration, indicated by both hours and * minutes = 0. */ public boolean isEmpty() { return (hours == 0) && (minutes == 0); }

slide-175
SLIDE 175

CSC309-S15-L3-4 Slide 175

/** * Return the string representation of this. */ public String toString() { String hrString = (hours == 0) ? "" : Integer.toString(hours).concat( (hours == 1) ? " hr " : " hrs "); String minString = (minutes > 0) ? Integer.toString(minutes).concat(" min ") : ""; return hrString.concat(minString); }

slide-176
SLIDE 176

CSC309-S15-L3-4 Slide 176

/** * Define equality for this as componentwise equality. */ public boolean equals(Object obj) { Duration otherDuration = (Duration) obj; return hours == otherDuration.hours && minutes == otherDuration.minutes; } /** * Define the hash code for this as the sum of the components. * code is used in turn by ItemKey.hashCode. */

slide-177
SLIDE 177

CSC309-S15-L3-4 Slide 177

public int hashCode() { return hours + minutes; } /*-* * Derived data fields */ /** Hour component of a duration value, between 0 and 999 */ int hours; /** Minute component of a duration value, between 0 and 60*999 */ int minutes;

slide-178
SLIDE 178

CSC309-S15-L3-4 Slide 178

}

  • 0. Time.java

package caltool.schedule; import mvp.*; /**** * * A Time consists of an hour, minute, and AM or PM indicator. * expressed using a 12-hour or 24-hour clock style. * an option by the user. If the clock style is 24-hour, the AmOrPm indicator * is nil.

slide-179
SLIDE 179

CSC309-S15-L3-4 Slide 179

* */ public class Time extends Model { /** * Construct an empty time value. */ public Time() { hour = 0; minute = 0; amOrPm = null; valid = true; empty = true; }

slide-180
SLIDE 180

CSC309-S15-L3-4 Slide 180

/** * Construct a time from the given string. Set the valid field to false if * the given string does not parse to a valid time. * state representation is used instead of throwing an exception because * some users may want to delay the processing of invalid dates, and hence * may not be interested in handling an exception. */ public Time(String time) { /* * Constant stubbed implementation. */ hour = 12; minute = 0; amOrPm = null;

slide-181
SLIDE 181

CSC309-S15-L3-4 Slide 181

valid = true; empty = false; } /** * Return true if his is an empty time. */ public boolean isEmpty() { return empty; } /** * Return the string representation of this. */ public String toString() {

slide-182
SLIDE 182

CSC309-S15-L3-4 Slide 182

return Integer.toString(hour).concat(":"). concat((minute < 10) ? "0" : "").concat( Integer.toString(minute)). concat((amOrPm != null) ? " " + amOrPm.toString() : ""); } /** * Define equality for this as componentwise equality. */ public boolean equals(Object obj) { Time otherTime = (Time) obj; return hour == otherTime.hour &&

slide-183
SLIDE 183

CSC309-S15-L3-4 Slide 183

minute == otherTime.minute && amOrPm.equals(otherTime.amOrPm); } /** * Define the hash code for this as the sum of the components. * code is used in turn by ItemKey.hashCode. */ public int hashCode() { return hour + minute + amOrPm.hashCode(); } /*-* * Derived data fields

slide-184
SLIDE 184

CSC309-S15-L3-4 Slide 184

*/ /** The hour component of a time value, between 1 and 12 or 0 and 24 based

  • n the clock style in use

*/ protected int hour; /** The minute component of a time value, between 0 and 59 */ protected int minute; /** Standard suffix used in 12-hour time value */ protected AmOrPm amOrPm; /*-*

slide-185
SLIDE 185

CSC309-S15-L3-4 Slide 185

* Process data fields */ /** True if this is a valid time */ boolean valid; /** True if this is an empty time, indicated by hour = 0, minute = 0, and amOrPm = "empty". */ boolean empty; }

  • 0. Security.java
slide-186
SLIDE 186

CSC309-S15-L3-4 Slide 186

package caltool.schedule; /**** * * Security is one of four possible levels: Public, PublicTitle, Confidential, * or Private. The levels specify the degree of visibility a scheduled item * has to other users. For an appointment, task, or event, "other users" are * defined as all users other than the user on whose calendar the scheduled * item appears. For a meeting, "other users" are all users not on the * Attendees list of the meeting. * * Public security means other users can see the scheduled item and all the * information about the item. * * PublicTitle security means other users can see the title of the scheduled

slide-187
SLIDE 187

CSC309-S15-L3-4 Slide 187

* item but none of the other information about the item. * * Confidential security means other users can only see that a user is * unavailable for the time period of a scheduled item; no other information * about the scheduled item is visible. * a specific time period, it is meaningful only for appointments and meetings, * not for tasks or events; tasks and events do not have specific time * components. * * Private security means other users see no information at all about a * scheduled item, not even that the item is scheduled. * security hides a scheduled item from the ScheduleMeeting operation, q.v., so * that a meeting may be scheduled at the same time as a private appointment. * It is up to the user to handle this situation by accepting or refusing the * scheduled meeting. Given the nature of private security, it does not apply

slide-188
SLIDE 188

CSC309-S15-L3-4 Slide 188

* to meetings. I.e., only appointments can have private security. * * @author Gene Fisher (gfisher@calpoly.edu) * @version 15jan10 * */ public enum Security { /** Public security means other users can see the scheduled item and all the information about the item. */ Public, /** PublicTitle security means other users can see the title of the scheduled item but none of the other information about the item. */

slide-189
SLIDE 189

CSC309-S15-L3-4 Slide 189

PublicTitle, /** Confidential security means other users can only see that a user is unavailable for the time period of a scheduled item; no other information about the scheduled item is visible. security applies to a specific time period, it is meaningful only for appointments and meetings, not for tasks or events; tasks and events do not have specific time components. */ Confidential, /** Private security means other users see no information at all about a scheduled item, not even that the item is scheduled. security hides a scheduled item from the ScheduleMeeting operation, q.v., so that a meeting may be scheduled at the same time as a private

  • appointment. It is up to the user to handle this situation by
slide-190
SLIDE 190

CSC309-S15-L3-4 Slide 190

accepting or refusing the scheduled meeting. private security, it does not apply to meetings. appointments can have private security. */ Private }

  • 0. Priority.java

package caltool.schedule; /**** * * Priority indicates whether an appointment is a must or if it is optional.

slide-191
SLIDE 191

CSC309-S15-L3-4 Slide 191

* This information is used to indicate the general importance of an * appointment to the user. The operational use of Priority is in the * ScheduleMeeting operation, where the meeting scheduler can elect to consider * optional appointments as allowable times for a meeting. * * @author Gene Fisher (gfisher@calpoly.edu) * @version 15jan10 * */ public enum Priority { /** Indicates a scheduled item is ’Must’ priority */ Must,

slide-192
SLIDE 192

CSC309-S15-L3-4 Slide 192

/** Indicates a scheduled item is ’Optional’ priority. */ Optional }

  • 0. Category.java

package caltool.schedule; import mvp.*; /**** * * A Category has a Name and StandardColor, which serve to distinguish it from

slide-193
SLIDE 193

CSC309-S15-L3-4 Slide 193

* other categories. Colored-coded categories serve as visual cues to the user * when viewing lists of scheduled items in some form. * used in filtered viewing. * */ public class Category extends Model { /** * Construct an empty category. */ public Category() { }

slide-194
SLIDE 194

CSC309-S15-L3-4 Slide 194

/** * Construct a category of the given name. * asking the Catgories class for the color assignment of the given * cateogories name. */ public Category(String name) { this.name = name; color = Categories.getColor(name); } /** * Return the string representation of this. * not do color. */

slide-195
SLIDE 195

CSC309-S15-L3-4 Slide 195

public String toString() { return name; } /*-* * Derived data fields */ /** Text name of the category */ String name; /** Color name of the category */ StandardColor color;

slide-196
SLIDE 196

CSC309-S15-L3-4 Slide 196

}

  • 0. StandardColor.java

package caltool.schedule; /**** * * A StandardColor is one of a fixed set of possibilities for use in color * coding a cateogry. The possible values are "Black", "Brown", "Red", * "Orange", "Yellow", "Green", "Blue", or "Purple". * * @author Gene Fisher (gfisher@calpoly.edu) * @version 15jan10

slide-197
SLIDE 197

CSC309-S15-L3-4 Slide 197

* */ public enum StandardColor { /** One of the built-in category colors */ Black, /** One of the built-in category colors */ Brown, /** One of the built-in category colors */ Red, /** One of the built-in category colors */

slide-198
SLIDE 198

CSC309-S15-L3-4 Slide 198

Orange, /** One of the built-in category colors */ Yellow, /** One of the built-in category colors */ Green, /** One of the built-in category colors */ Blue, /** One of the built-in category colors */ Purple }

slide-199
SLIDE 199

CSC309-S15-L3-4 Slide 199