M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

81
Information Technology and Computing: Level 3 ARAB OPEN UNIVERSITY Faculty of Computer Studies M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06 M301 Software Systems and their Development Assignment Booklets CONTENTS Assignment Booklet 1 -TMA01- cut off date: (12 Nov. 2005) Assignment Booklet 2 -TMA02- cut off date: (10 Dec. 2005) Assignment Booklet 3 -TMA03- cut off date: (11 Mar. 2006) Assignment Booklet 4 -TMA04- cut off date: (15 Apr. 2006) Assignment Booklet 5 -TMA05- cut off date: (20 May 2006) Assignment Booklet 6 -TMA06- cut off date: (10 June 2006) Copyright © 2005 The Arab Open University SUP 60030 8 3.1

Transcript of M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Page 1: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Information Technology and Computing: Level 3

ARAB OPEN UNIVERSITY

Faculty of Computer Studies

M301 TMA01,TMA02,TMA03

TMA04,TMA05,TMA06

M301 Software Systems and their

Development

Assignment Booklets

CONTENTS

Assignment Booklet 1 -TMA01- cut off date: (12 Nov. 2005) Assignment Booklet 2 -TMA02- cut off date: (10 Dec. 2005) Assignment Booklet 3 -TMA03- cut off date: (11 Mar. 2006) Assignment Booklet 4 -TMA04- cut off date: (15 Apr. 2006) Assignment Booklet 5 -TMA05- cut off date: (20 May 2006) Assignment Booklet 6 -TMA06- cut off date: (10 June 2006)

Copyright © 2005 The Arab Open University SUP 60030 8 3.1

Page 2: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

2 2

Page 3: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Information Technology and Computing: Level 3 M301 Software Systems and their Development

ARAB OPEN UNIVERSITY

Faculty of Computer Studies

M301

Assignment Booklet I

Contents TMA 301 2005/2006 Cut-off date TMA M301 01 (Question 1) 8 October 2005 TMA M301 01 (Questions 2, 3, 4 and 5) 12 November 2005 This assignment must be submitted in two parts. The answer to Question 1 must be sent to your tutor as TMA00 (the test TMA) on or before 8 October 2005, while the answers to the remaining four questions must be sent as TMA01 on or before 12 November 2005. (Note that there is a potential confusion here. Question 1 is not to be considered as TMA00: it is part of TMA01 and its marks will be included in the marks for TMA01. TMA00, which is a test TMA, is used merely as a delivery vehicle enabling you to send Question 1 to your tutor at the same time that you test the e-TMA system.)

For TMA00 write your solution to Question 1 into a single word-processed document known as the Solution Document (clearly headed with your name, the number of the TMA as given above, and your personal identifier). This Solution Document should contain all text, diagrams and screen dumps requested in the questions. Submit your Solution Document containing your solution to Question 1 to the e-TMA system as TMA00 (i.e. TMA zero zero). Your tutor will mark it and send it back to you with any feedback that is necessary. Your mark for Question 1 will not be registered with the e-TMA system at this point: instead, your tutor will record it and add it to your overall mark when you submit the remaining four questions as part of TMA01.

You should use the same Solution Document you used for Question 1 to complete Questions 2 – 5. Send this completed document to the e-TMA system as TMA01 (i.e. TMA zero one). Your tutor will mark it and will also add your marks for Question 1 to the overall total for the TMA. The e-TMA system will record this overall mark when your tutor sends TMA01 back to you.

Always submit your Solution Document (i.e. the Solution Document plus other files as directed) in the form of a zip archive file to the e-TMA system on or before the cut-off date shown above. You will find details on how to create a zip archive file in the Guide to Electronic Tuition. You will find details on how to submit a zip archive file to the e-TMA system in Using the Electronic TMAs System – A Student Guide to e-TMAs.

3 3

Page 4: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

TMA M301 01 Cut-off date 8 October 2005 Important Enter your solutions to this TMA into a Solution Document. This document must be readable in Word. If you are in any doubt, try reading your document using WordViewer before submitting it to the e-TMAs system.

To avoid sending over-large files through the e-TMA system (something that can cause problems to those marking your assignment) please:

• prepare your Solution Document using Word if you have it;

• avoid sending an RTF document;

• do not copy screen dumps (i.e. dumps of the whole screen) into your Solution Document. Only window dumps will ever be required (e.g. an output window, or an interface window) as a solution to a question. To copy a window, select the window so that it is highlighted and press the Alt-PrintScreen keys together. This will copy the window onto the clipboard. It can then be pasted into your Solution Document using the Edit menu or shortcut key, Ctrl V.

It would be tremendously helpful if, in your Solution Document, you would explicitly state if you have not answered a question or part of a question. This should avoid the necessity for your tutor to contact you should a solution (or part of one) appear to be missing from your Solution Document.

Question 1 [20 marks] Cut-off date: 8 October 2005 This question must be submitted as TMA00. See the rubric on the front page of this Assignment booklet.

The answers to parts (i) to (x) of this question can be found in the Course Guide, in the Guide to Electronic Tuition, by using FirstClass, and by accessing the M301 course web site.

(i) Name two elements of the course materials that will be distributed to you via the M301 course web site. [1 mark]

(ii) Having entered the M301 web site, describe the steps you would need to take to find out any errata for Unit 1.1. [1 mark]

(iii) What is the role of the Study Calendar? What is the cut-off date for TMA02? [1 mark]

(iv) In the Course Guide why are you ‘advised to tackle as many of the SAQs as you can during the course and use the solutions in your revision’? [1 mark]

(v) The system of ‘substitution’ in OU terms means that, in general, and for specified courses, the average mark for all your TMAs plus the examination mark will be substituted for your lowest marked TMA. Does this system of substitution apply to this course? [1 mark]

(vi) Suppose you do not have a suitable copy of Microsoft Word, how do you read the marked TMA document that you receive from your tutor? Where will you find the software to do this? [1 mark]

Copyright © 2005 The Arab Open University SUP 52036 9 2.1

Page 5: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

(vii) When is the first face-to-face tutorial with your tutor scheduled? (You should have received this information from your tutor or your Regional Centre; but if you have not been sent the information, please telephone your Regional Centre for details relating to the first tutorial for your course. You will also need to ask your Regional Centre to let you know the dates and venues of tutorials and day schools in your region.) If you do not have the information then answer, ‘No information’, and also say what you have done to obtain the information.

In the case of those students for whom face-to-face tutorials are not scheduled, such as those based in Continental Western Europe, please indicate ‘CWE – Not scheduled’. [1 mark]

(viii) Where will you find details of a particular electronic tutorial? [1 mark]

(ix) To engage in electronic communication with your tutor and other students, what software do you require? Where will you find it? [1 mark]

(x) Carry out the tasks described in Section 4 of the Guide to Electronic Tuition. Now log on to your M301 regional conference and read the Welcome message that has been posted there by the tutors who will monitor the conference. Now go into the Tutor Group subconference that is labelled with your tutor’s initials (e.g. TG ABC2). Read the message your tutor will have posted to this conference.

Go into your own personal mail box on FirstClass and send an email to your tutor’s individual mail box (your tutor’s email address will be in his/her message) acknowledging what has been said in his/her message, and what has been said in the main conference’s Welcome message.

You should also post a message to your Tutor Group conference to introduce yourself and say whether or not you are interested in joining a self-help group. [1 mark]

Parts (xi) to (xv) of this question test your understanding of Section 1 (Introduction to the course) and Section 2 (Introduction to the Integrated Development Environment) of Unit 1.1.

(xi) How many distinct kinds of software element would you expect to find in a client-server system? Name them. [2 marks]

(xii) What terms are used to describe a system consisting of many interacting processes that are running on different computers? [2 marks]

(xiii) Which character in The ‘Killer Robot’ Case claimed, ‘It doesn’t seem that Randy Samuels caught onto the spirit of “egoless programming”.’? [2 marks]

(xiv) In Section 1 of the Case Study, four differences are given between the new proposed banking system and the old system. In a brief sentence describe one of them. [2 marks]

2 2

Page 6: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

(xv) Having completed step 14 of Practical Activity 2.2 in the IDE Handbook, include in your Solution Document a copy of the window showing the output from the FirstProgram project. [2 marks]

On completion of this question, add the Solution Document to the TMA00 zip archive file.

You should now submit this zip archive file to the e-TMA system as TMA00 (see Using the Electronic TMAs System – A Student Guide to e-TMAs) on before the cut-off date.

3 3

Page 7: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Your answers to Questions 2 to 5 should be added to the Solution Document that you used for TMA00, which your tutor has returned to you. Once completed, it should be submitted as TMA01 on or before the cut-off date.

Question 2 [20 marks] Cut-off date: 12 November 2005 This question is based on Unit 1.2 but also draws on the work you have done in Unit 1.1.

(i) Use the Java code below to answer the questions that follow.

import java.io.*; class TestMirror { static public void main (String [ ] args) { Shape form1 = new Circle (10, 10, 5); // 1 Mirror mirror1 = new Mirror (5, form1); // 2 Mirror mirror2 = mirror1; // 3 Shape form2 = new Square (15, 20, 10); // 4 mirror1.setShape (form2); // 5 } } class Mirror { protected int num; protected Shape aShape; public Mirror (int n, Shape s) {num = n; aShape = s;} public int getNum () {return num;} public void setNum (int n) {num = n;} public Shape getShape () {return aShape;} public void setShape (Shape s) {aShape = s;} } class Shape { protected int x; protected int y; public Shape (int ix, int iy) { x = ix; y = iy;} public String describe () {return "unknown shape";} } class Square extends Shape {

protected int side; public Square (int ix, int iy, int is) {super (ix, iy); side = is;} public String describe () {return "square with side " + side;} } class Circle extends Shape { protected int radius; public Circle (int ix, int iy, int ir) {super (ix, iy); radius = ir;} public String describe () {return "circle with radius " + radius;} }

(a) The constructor for Circle has three formal arguments. Explain, in a manner similar to that associated with Figure 2.4 of Unit 1.2, how each of these formal parameters is used when the constructor is called in

4 4

Page 8: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

statement // 1 of the above program. Your answer must make it clear that you understand the difference between actual arguments and formal arguments. [4 marks]

(b) In the class Mirror, identify an assignment statement that:

• changes a reference to an object;

• copies a value of primitive data type. [2 marks]

(c) In the manner of Unit 1.1, Figure 3.3 and of Exercise 2.2 of Unit 1.2, draw the state of the objects mirror1 and mirror2 at the end of step // 5 shown in the class Test.Mirror. You must show the form1 and form2 objects but you need not show their internal structure (this is similar to the way the Ball objects are handled in Exercise 2.2 in Unit 1.2). [4 marks]

(ii) In the activities of Unit 1.2, Section 3 (step 8) you are asked to read Section 3 of the Case Study entitled An example of inheritance. In the manner of Figures 2.9 and 3.2 in Unit 1.2, draw a class diagram involving the following classes described in that section: Customer, AccountCollection, Account, Vector, CurrentAccount and BalanceHistory. Also include the class String but no other classes need to be shown. [4 marks]

(iii) This question requires you to do Exercise 2 in Budd, Chapter 6. Start off by carrying out the following steps.

1 Create a new folder in JavaProjects called TMA01 and then create a new folder in TMA01 called Cannons. Copy into Cannons the folder called src from the JavaProjects\Cannons folder (which contains all the CannonWorld source files). Make sure you COPY rather than MOVE src. Also copy (NOT move) the Ball.java file from javaProjects\BallWorlds\src to JavaProjects\TMA01\Cannons\src.

2 Start your IDE and create a new project called TMACannonWorld.jpr in the Cannons directory. Add to this project the files CannonWorld.java, CannonBall.java, CannonTarget.java, Cannon.java, CloseQuit.java, and Ball.java from the Cannons\src folder.

3 Run the TMACannonWorld program to ensure it executes as expected. Note that if you are using Windows ME, you may get a list of exceptions appearing in the Messages Window. Ignore them.

Now tackle the following questions.

(a) In the program you ran in step 3 above, what colour is a newly created cannonball? Describe how this colour is set when the cannon ball is created. [1 mark]

(b) What method can be used to change the colour of a cannonball? [1 mark]

5 5

Page 9: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

(c) Now carry out Exercise 2 in Budd, Chapter 6, which is reproduced below for your convenience (you may ignore the question posed in the second part of Budd’s question, since it will be answered implicitly by the modifications that you produce):

‘Modify the class CannonBall so that the ball is colored blue when the ball is moving upward, and colored red when the ball is descending.’ [Note that you need not worry about what colour a stationary ball is.]

Run your modified program to ensure it meets Budd’s requirements, and copy all modified code into your Solution Document, making clear where the modification(s) is/are located. [4 marks]

On completion of this question, add the Solution Document to your zip archive file for this TMA.

6 6

Page 10: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Question 3 [20 marks] This question is based on Unit 1.3 but also draws on the work you have done in Units 1.1 and 1.2.

(i) In Budd, Chapter 7, the class Peg (Figure 7.11) inherits from ScorePad (Figure 7.9), which in turn inherits from Hole (Figure 7.8), which in turn inherits from Ball (Figure 5.3).

(a) List the methods that form part of the public interface of Peg. Include the methods inherited from the parent classes up to and including Ball (i.e. ignore methods inherited from Object). For each method, say which of the following applies:

• it is first defined in Peg, and does not appear in any superclass;

• it is inherited from a superclass (state which one) without being overridden in Peg (in this case, you should also state in which superclass the method was first implemented);

• it is inherited from a superclass (state which one), but is overridden in Peg. [4 marks]

(b) Comment briefly on the merits or otherwise of Hole inheriting from Ball. You should bring in the concepts of inheritance for specification and construction into your answer (without the need to define them). [3 marks]

(ii) The following code uses classes from the PinBallGame program:

Ball b = new Ball (…); Hole h = new Hole (…); ScorePad s = new ScorePad (…); h = s; // 1 s = b; // 2 ` . .

In the assignment at // 1 above, the type of the variable and the type (class) of the object it would be made to reference are different. The same is true of the line // 2. An assignment where the variable and the object it references are of different types is only allowable under certain circumstances in Java. In fact, the assignment in // 1 is permissible, but the one in // 2 is not.

(a) In line // 2, what is the type of the variable s, and what is the type (class) of the object to which the assignment makes s reference? [2 marks]

(b) The assignment at line // 2 would inevitably be followed by statements that involved invoking one or more methods on s. Identify a method that might legitimately be called on s, but would cause a problem given the assignment that has taken place at line // 2. Explain what the problem would be. [3 marks]

(iii) In this question you are asked to do Exercise 2 from Budd, Chapter 7. But first, carry out the following steps.

1 In the folder JavaProjects\TMA01 that you created in Question 2, create a new folder called PBG2 that, in turn, contains an empty folder called src. Copy (NOT move) into this src folder the following files:

• all the .java files from JavaProjects\PinBallGame1\src EXCEPT PinBallGame.java;

7 7

Page 11: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

• all the .java files from JavaProjects\PinBallGame2\src;

• Ball.java from JavaProjects\BallWorlds\src;

• CannonBall.java from JavaProjects\Cannons\src.

2 Start your IDE and create a new project called ModifiedPinBallGame2.jpr in the PBG2 directory, and add to this project all the files in the src folder in PBG2.

3 Run the program to ensure that it executes as expected. (It should execute like the original PinBallGame2 project that you created when doing Exercise 5.2 in the IDE Handbook.)

Now answer the following questions.

(a) Explain briefly, step by step, how the score in the score label at the top of the screen is updated when a ball ‘hits’ (intercepts) a scorepad (a target with a single circle). [2 marks]

(b) A slightly modified exercise based on Exercise 2 in Budd, Chapter 7 is as follows.

PinBallGame2 as presented allows the user an unlimited number of balls. Change it so that it is only possible to fire five (5) balls, disallowing firing once this supply is exhausted. Place a display (similar to the score label) that will indicate the number of remaining balls (e.g. Remaining Balls = 2) at the bottom of screen. Note that putting a label at the bottom of the screen may slightly obscure the fire button — this is not a problem.

Include in your Solution Document copies of the code that you have added/modified, with a clear indication of where the change is located. (Please do not copy whole classes.) [5 marks]

(c) Include in your Solution Document a copy of your PinBallGame window when there are two balls left to fire. [1 mark]

On completion of this question, add the Solution Document to your zip archive file for this TMA.

8 8

Page 12: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Question 4 [20 marks] This question is based on Unit 1.4 but also draws on the work you have done in Units 1.1, 1.2 and 1.3.

(i) This question requires you to define a class that will represent a list of objects, taken in order, with a specified maximum number of elements. For example, such a data type may be used to represent a waiting list of names for admission to a school. Prospective students are normally added at the end of the list, but if they have a sibling already at the school then they can be inserted at an earlier point. Once the list reaches its maximum size, and becomes full, no further students can be added until the person at the top has been admitted to the school, and removed from the waiting list, thus freeing up a space.

Assume that the class implementing such a list is called MyList and has the following public constructor and methods (note that to the user of the list, the first element of the list should be in position 1 and not 0):

• a constructor, MyList (int m), which creates a new empty list that can have a maximum of m elements.

• isFull (), which returns the boolean true if the list has the maximum number of elements in it, and false otherwise.

• first (), which returns the element at the top of the list. (There is no need to worry about the situation when there are no elements in the list, since we will assume that the user of this method must check that the list is not empty when this method is called.)

• removeFirst (), which removes the element at the top of the list. (As before you may assume that the list is not empty, so there is no need for your code to check whether or not the list is empty.)

• addElement (Object o), which adds the Object o to the end of the list. (In this case, it is assumed that the method will only be called if the list is not full, so there is no need for your code to check whether or not the list is full.)

• addElement (Object o, int n), which inserts the Object o at position n in the list. (It will be assumed that this method must not be called if n is less than 1 or greater than the number of elements in the list. That is, n must not fall outside the range of the current number of elements in the list. So, you do not have to write code to cover this situation.)

• getElement (int n), which returns the element of class Object in position n if there are n or more elements in the list. (As with addElement, you may assume that n is at least 1 and not greater than the current number of elements in the list.)

• numInList () , which returns the int value of the number of elements in the list.

(a) Create a new folder in JavaProjects\TMA01 called List, and create a new project TestMyList.jpr in this new folder. Add a new class, called MyList, to your project, and define a full implementation of this class using composition based on the class Vector (the operations of which are shown in Budd, Table 19.2). Note that you will need to include the appropriate import statement to be able to use Vector. Your class should contain two data fields:

9 9

Page 13: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

• one called theData of type Vector for storing the elements of the list;

• the other called maxElements, of type int for storing the maximum size of the list.

[NB DO NOT attempt to execute the project at this stage. It is incomplete and requires an additional class, which you will add in part (c) below, before it can be run and tested.]

Copy the text of your implementation into your Solution Document. [8 marks]

(b) Why would you use composition as opposed to inheritance to create the MyList class? [3 marks]

(c) The file TestMyList.java is one of the files that would have been downloaded onto your machine as part of the zip archive file containing TMA01. Copy TestMyList.java into JavaProjects\TMA01\List\src (the folder src would have been created when you developed the class MyList).

TestMyList.java contains a class that will test your MyList class developed in part (a). Add it to your TestMyList project and execute the program. Include a copy of the output window in your Solution Document. [2 marks]

(ii) This question uses the classes Shape, Circle and Square (as shown in Budd, Section 11.1) and Box (shown below) and BoxTest (shown on the next page). Java files containing these classes form part of the zip archive file you downloaded with TMA01.

public class Box { private int value; private Shape aShape; public Box () {value = 0;} public void setValue (int v, Shape s) {value = v; aShape = s;} public int getValue () {return value;} public Shape getShape () {return aShape;} }

10 10

Page 14: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

public class BoxTest { public BoxTest () { } public static void main (String [ ] args) { int inp1 = 4; int inp2 = 3; Shape shape1 = new Circle(1, 1, 3); Shape shape2 = new Square(6, 6, 2); Box aBox = new Box (); aBox.setValue (inp1, shape1); Box bBox = aBox; Box cBox = new Box (); inp2 = inp1; cBox.setValue(inp2, shape1); System.out.println("size of aBox = " + aBox.getValue()); System.out.println("contents of aBox = " + aBox.getShape().describe()); System.out.println("size of bBox = " + bBox.getValue()); System.out.println("contents of bBox = " + bBox.getShape().describe()); System.out.println("size of cBox = " + cBox.getValue()); System.out.println("contents of cBox = " + cBox. getShape().describe()); System.out.println("aBox == bBox ==" + (aBox == bBox)); // 1 System.out.println("aBox == cBox ==" + (aBox == cBox)); // 2 System.out.println("cBox == bBox ==" + (cBox == bBox)); System.out.println("cBox.getShape() == bBox.getShape() ==" + (cBox.getShape() == bBox.getShape())); // 3 } }

Carry out the following steps and then answer the questions below.

1 You should create a new folder called Shapes in JavaProjects\TMA01, and in Shapes create a folder called src.

2 Copy or move all the files containing Shape, Circle, Square, Box and BoxTest into src.

3 Start up your IDE, and create a new project called ShapeTesting.jpr inside Shapes.

4 Add the files contained in JavaProjects\TMA01\Shapes\src (i.e. Shape.java, Circle.java, Square.java, Box.java and BoxTest.java) to your new project.

5 Run the program.

(a) Include a copy of the output from your program in your Solution Document. Explain the output you receive from the lines marked // 1, // 2, and // 3 shown in the class BoxTest above. [4 marks]

11 11

Page 15: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

(b) In the classes of the ShapeTesting project, identify an example (if there is one) of:

• a variable that is being used as a polymorphic variable;

• an example of overriding;

• a deferred method. [3 marks]

On completion of this question, add the Solution Document to your zip archive file for this TMA.

12 12

Page 16: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Question 5 [20 marks] This question is based on Unit 1.5 but also draws on the work you have done in Units 1.1 through 1.4. If you have not already done so, work through Section 6 of the IDE Handbook before attempting this question. You will also find e-Tutorial 01 helpful when tackling part (i) of the question.

(i) Use JBuilder's GUI builder to help you to create a program that draws a window with a coloured ball in the centre. Place a vertical scroll bar along the right edge of the window. When the user moves the right scroll bar down or up, the ball should move down or up the window accordingly. Give the ball an initial vertical position of about 150. The current value of the slider (from 0 to 100 by default), retrieved with getValue (), can be multiplied by a number (depending on the height of the frame) and the new y position of the ball can be set from it.

To do this, follow the steps given below.

1 Create a new folder called GuiProject in JavaProjects\TMA01, and in GuiProject create a folder called src.

2 Copy (NOT move) Ball.java from JavaProjects\BallWorlds\src into the new src folder you created in step 1.

3 In the directory JavaProjects\TMA01\GuiProject create an application, called MoveBall.jpr, as described in Section 6 of the IDE Handbook (among other things, this will provide you with an incomplete class named Frame1 which extends JFrame).

4 Add Ball.java to the project from the JavaProjects\TMA01\GuiProject\src.

5 Use the GUI builder to place a JScrollbar object on the right side of Content Pane. (Remember to change the layout property appropriately beforehand.) Set the name of the scrollbar to sBar, its maximum value to 100 and current value to 50.

6 Modify the class Frame1 so that a Ball object with radius 20 appears in the application window at the point (200, 150).

7 Use the AdjustmentValueChanged event to make the ball move up and down as the scrollbar is moved up and down. When the scrollbar is at its highest point the ball should be at the top of the window, and vice versa.

8 To make the ball visible on your screen you will have to override the paint method in class Frame1. Use BallWorlds to guide you.

Include in your Solution Document:

(a) a copy of the code of your completed Frame1 class; [8 marks]

(b) a copy of the window that appears when you run the application and move the cursor to its lowest point. [2 marks]

(ii) This question requires you to write and test a program that, using the StreamTokenizer class (Budd, Section 14.3), will read a file containing numbers, and print them to a second file with a ‘+’ printed before each number, and an ‘=’ sign at the end followed by the sum of all the numbers. For example, if the input file contained ‘5 23 11’ then the output file should contain ‘+ 5.0 + 23.0 + 11.0 = 39.0’.

In doing this question, you should carry out the following steps.

1 Create a new folder called Streams in JavaProjects\TMA01.

13 13

Page 17: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

2 Start up your IDE and create a new project called AddingNumbers.jpr in the folder JavaProjects\TMA01\Streams.

3 Add a new class called Adder to this project, which includes both a main method and a constructor (see Practical Activity 2.2 in the IDE Handbook for details on how to do this).

4 Within the constructor for Adder, write a try statement that will create:

• a BufferedReader object named input, which is capable of reading characters from a text file named MyInputFile.txt stored in a directory of your own choice such as C:\JavaProjects\TMA01\Streams. (See Budd, Chapter 14, Section 14.7). Note that in a Java string, whenever you want to include the character '\' you should use '\\'.

• a BufferedWriter object named output, which is associated with a file called MyOutputFile.txt, to which the processed input from MyInputFile.txt can be written. For convenience, we suggest MyOutputFile.txt be located in the same directory as MyInputfile.txt.

5 Create the text file named MyInputFile.txt (using an editor such as Notepad) in the directory you used in step 4 above. It should contain three or four numbers with spaces between the numbers (e.g. 5 23 11). Note that you do not have to create MyOutputFile.txt before running the program: it will be automatically created when the program is executed.

6 Define a method called run that processes the numbers in MyFile.txt according to the requirements described above. You should use the facilities of the class StreamTokenizer to do this. Budd, Chapter 14, Section 14.3 illustrates the use of the StreamTokenizer class, but you may also find the description given in the box below helpful.

7 Write an appropriate main method for Adder.

8 Run your program.

Include in your Solution Document:

(a) a copy of the code of your class Adder; [7 marks]

(b) a window showing the contents of your text file MyFile.txt; [1 mark]

(c) a window showing the contents of your output file, MyOutputFile.txt. [2 marks]

The class StreamTokenizer

A StreamTokenizer object takes either an InputStream or a Reader (such as input in the first bulleted point of step 4 above) and splits it into a sequence of tokens (either bytes in the case of an InputStream or characters in the case of a Reader). The next token in the stream can be obtained by using the method nextToken (). The StreamTokenizer class defines four constants (all of type int and non-zero):

TT_EOF, which represents the special token that marks the end of a file; TT_EOL, which represents the token that marks the end of a line; TT_NUMBER, which represents a number; TT_WORD, which represents a word.

After you have read a token using nextToken, the int data field ttype contains one of the above constants. If the last token read is a number (ttype == TT_NUMBER), its value will be in the floating point (double) variable nval; if the last token read is a word (ttype == TT_WORD), the word will be in the String variable sval.

14 14

Page 18: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

To access the class StreamTokenizer, you need to import it from java.io.*

The class StreamTokenizer also allows you to define how a word or number is defined, but for this exercise simply accept the default definitions which, in essence, say that words or numbers are delimited by spaces and normal punctuation marks.

On completion of this question, add your Solution Document to your zip archive file for this TMA.

This should complete your work on this TMA, and your zip archive file should contain a single Solution Document.

You should now submit your completed zip archive file to the electronic TMAs system on or before the cut-off date.

15 15

Page 19: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

16 16

Page 20: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Information Technology and Computing: Level 3 M301 Software Systems and their Development

ARAB OPEN UNIVERSITY

Faculty of Computer Studies

M301

Assignment Booklet 2 Contents Cut-off date TMA M301 2005-2006 10 December 2005

Enter your solutions to this Tutor Marked Assignment (TMA) into a word-processed document known as the Solution Document. The Solution Document (clearly headed with your name, the number of the TMA as given above, and your personal identifier) should contain all text, diagrams and screen dumps requested in the questions. A file containing a template for the Solution Document, showing how your solutions should be laid out, can be downloaded from the M301 web site. (You may, of course, choose to use your own Solution Document.)

The marks allocated to each part of each question are indicated in brackets in the margin.

Note that, in answering the questions in this TMA, more is expected than simply reproducing passages from the course materials. In those instances where you feel it is essential to use extracts from these materials you must indicate their source. To do otherwise is plagiarism.

To avoid the difficulties that will arise if you inadvertently lose the contents of your Solution Document, we recommend that you add it to the zip archive file (overwriting any previous copy) each time you complete a question.

17 17

Page 21: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

TMA 02 Cut-off date 10 December 2005 Important Enter your solutions to this TMA into a Solution Document, the template for which can be downloaded from the M301 web site. (You may, of course, choose to use your own Solution Document.) Whatever Solution Document you use, the requirement is that it must be readable in Word. If you are in any doubt, try reading your document using WordViewer before submitting it to the e-TMAs system.

Create a new zip archive file for this TMA and name it TMA02. On completion of a question, add your Solution Document to this zip archive file. Each time you do this, you will overwrite the copy of the Solution Document that is in the TMA02 zip archive file, but doing this will be a way of providing a back-up of your work.

Question 1 [20 marks] This question tests your understanding of the concepts and techniques in Unit 2.1 and Section 1 of Unit 2.2.

(i) (a) What is the difference between a machine instruction and a high level language instruction and why might there be a problem when executing a high level language instruction in a time slicing system? [6 marks]

(b) A particular software system consists of two activities P1 and P2 that run indefinitely on a uniprocessor. P1 executes for a time and is then interrupted so that P2 can execute. P2 in turn is interrupted after a time so that P1 can execute, and so on. Explain, in terms of the definition of concurrency whether or not, P1 and P2 constitute a concurrent system. [4 marks]

(ii) Classify the following as hard real-time, soft real-time or non-real-time systems:

(a) a control system in a power station; [2 marks]

(b) library system for registering loans; [2 marks]

(c) an ATM (automatic teller machine). [2 marks]

In each case give a reason for your choice.

(iii) A person is consulting a recipe to make a cake. Use this example as an analogy to explain the notion of a process in a computing system. In your explanation you should identify which aspects of the example correspond to which elements of the computing system. [4 marks]

On completion of this question, add your Solution Document to the TMA02 zip archive file.

Copyright © 2005 The Arab Open University SUP 52037 4 2.1

Page 22: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Question 2 [20 marks] This question is based on the material in Unit 2.2.

(i) (a) The diagram in Figure 1 uses a notation similar to that in Bacon, Figure 4.2, and also indicates units of time in the horizontal direction.

Figure 1 Time graph of two device handler processes.

0 5 10 15 20

TIME

A’s Device

A’s ISR

Process A

B’s Device

B’s ISR

Process B

WAIT

WAIT

SIGNAL

SIGNAL

The information in the diagram, which relates to the utilization of the single CPU, can be represented in tabular form as shown in Figure 2.

Time Unit Use of processor

1 Process B

2 Process B

3 Process B

4 Process B

5 Process A

6 Process A

7 Process A

8

Figure 2 Tabular way of representing Figure 1

Thus Process B is running on the processor from time period 0 to the end of time period 4 when Process A commences execution.

Complete the table up to the end of time period 20 using the following assumptions.

• Each device’s ISR takes one time unit to complete and when complete the process that had been waiting for that device will be scheduled to run.

2 2

Page 23: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

• A policy of pre-emptive scheduling is used where each process that is runnable is given three time units of execution before being pre-empted and another runnable process executed in its place. If there is no other runnable process, a running process will continue until it completes. An interrupt is acted upon immediately, unless an ISR is running.

• It takes zero time to make a context switch.

• Neither process requires further I/O during this period.

• Process A completes after having executed for a total of 7 time units. [4 marks]

(b) Assuming that both Process A and B are requesting input from their respective devices, what kind of I/O policy is being illustrated in Figure 1: synchronous or asynchronous? Explain your answer. [4 marks]

(ii) In a concurrent system what property should be exhibited by operations used by different processes to update shared data? Explain why. [3 marks]

(iii) How many threads make up the BallWorld3 program of Practical Activity 5.1 of Unit 2.2. Briefly describe what each does. [3 marks]

(b) Create a new project BallWorld5 that is similar to BallWorld4 from Exercise 5.2 of Unit 2.2 except that:

• the data field NoOfBalls is no longer a constant;

• when the mouse is clicked the balls are restarted from the bottom right hand corner and not where the mouse is;

• the number of balls that are moved and then tracked is reduced by 1 until only one ball is moved and tracked.

Include in your Solution Document the Java code for your new MultiThreadedBallWorld class. [6 marks]

On completion of this question, add the Solution Document to the TMA02 zip archive file.

3 3

Page 24: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Question 3 [20 marks] This question is based on the material in Unit 2.3.

(i) This part of the question is based on Practical Activity 1.1 in Unit 2.3.

(a) What is Atomic time based on and how is atomic time kept synchronized with universal time? [3 marks]

(b) What is TAI? [2 marks]

(ii) In SAQ 5.7 (d) of Section 1 of Unit 2.3, a naming service is described as providing clients with the attributes associated with named objects.

(a) What are the named objects and attributes dealt with by the Name Server as described in Section 5 of the Case Study, A Simple Naming Service? [2 marks]

(b) Give an example of the information that would be given to the Name Server in order to identify a named object, together with an example of the attribute that you would expect back from the Name Server. [2 marks]

(iii) (a) Explain how would you overcome the problem illustrated in Exercise 1.2 of Unit 2.3. [4 marks]

(b) Assume that, in Exercise 1.2 of Unit 2.3, the signal from the time server indicated that the actual time was 76. Explain what problems, if any, would arise if the local clock were set to this time and event e3 occurred 2 time units later. [3 marks]

(c) Messages are being sent between two computers, P and Q, of a distributed system. Assume that events on Computer P are recorded (for example, as (p5, 63), where p5 is the name of the event and 63 is the local time of Computer P), and that events are similarly recorded on Computer Q. Explain briefly what synchronising steps, if any, would need to be taken in the case of the following messages:

• Message 1: sending event (p3, 54); receiving event (q1, 55);

• Message 2: sending event (q34, 92); receiving event (p51, 90). [4 marks]

On completion of this question, add your Solution Document to the TMA02 zip archive

file.

4 4

Page 25: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Question 4 [20 marks] This question is based on the material in Unit 2.4.

(i) Section 3 of the Case Study entitled An Example of Inheritance contains, in figure 3, the code for an Account class.

(a) What are the two important properties of an atomic action? [2 marks]

(b) Explain why you would expect the credit method of Account to be a single concurrent action (also referred to as a single logical action). [3 marks]

(ii) (a) In the scenario shown by Figure 2.1 in Unit 2.4, assume that turn == 1 and that P1 is able to enter its critical region. Show that P0 will be excluded from its critical region until P1 finishes its own critical region. [2 marks]

(b) Explain briefly in your own words what problem remains with the solution provided by Figure 2.1 and why. [2 marks]

(c) By assuming that P1 starts its entry protocol as shown in Figure 2.2 of Unit 2.4 before P0 explain how the two processes P0 and P1 can become deadlocked. [3 marks]

(iii) Suppose that there exists a test-and-set class TasClass, defined as follows:

public class TasClass { private boolean state = false; // stores the state of a TasClass object // and initilizes it to false. public void set (boolean b) { // and atomic operation that sets the state …. // of the object to true or false } public boolean tas () { // and atomic operation that acts as follows: … // if the state of the object is true, returns true // and takes no other action, otherwise sets the // state to true and returns false } }

Assume that a TasClass object referenced by tasObj is created as follows.

TasClass tasObj = new TasClass ();

Assume that the variable tasObj is accessible to the following code in Figure 4 that can be executed by two processes P0 and P1.

5 5

Page 26: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Non-critical code // Entry protocol for either Po or P1 while (tasObj.tas()) noOp(); Critical region // Exit protocol for either Po or P1TasObj.set(false); Non-critical code

Figure 4 Entry and exit protocols written in terms of a TasClass object

Assuming that P0 executes its entry protocol first:

(a) explain why P0 will be allowed into its critical region. [2 marks]

(b) describe what will happen if P1 is allowed to execute its entry protocol while P0 is still in its own critical region. [2 marks]

(iv) Assume that a Java class called Semaphore, based on Figure 9.17 in Bacon, has been defined as follows:

public class Semaphore { int value = 0; // stores the value of a semaphore object Queue waitQueue = new Queue (); // queue for storing waiting processes public void Semaphore (int v) { // constructor that initializes 'value' to ….. // the required value of 'v' } public void semaSignal () { // implements the conventional (atomic) semaphore ….. // operation SIGNAL (semaphore) } public void semaWait () { // implements the conventional (atomic) semaphore ….. // operation WAIT (semaphore) } }

Not that Bacon's semaphore operations, SIGNAL and WAIT have an argument representing the semaphore on which each operation is being invoked. The OO methods in Java do not have such an argument because, using the OO message-sending notation, the target of a semaWait (or semaSignal) message is the semaphore object on which the method semaWait (or semaSignal) would be invoked.

Assume that a Semaphore object, accessible to the code of two processes P0 and P1, is created as follows:

Semaphore aSemaphore = new Semaphore (1) // 1

(a) In the Java statement // 1 above, explain why an actual argument of 1 is used. [2 marks]

(b) Rewrite the entry and exit protocol parts of Figure 4 using the semaphore object referenced by aSemaphore. [2 marks]

On completion of this question, add your Solution Document to the TMA02 zip archive file.

6 6

Page 27: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Question 5 [20 marks] This question tests your understanding of Unit 2.5 but also relies on knowledge of the other units in Block 2.

A city is contemplating introducing a tramway in its city centre area. The proposed track layout is shown in Figure 5 and consists of two circular tracks. The plan is to run two trams travelling in opposite directions on separate tracks. However, both tracks pass through a tunnel through which there is only a single track. Only one tram should be in the tunnel at any one time. The trams start at the Depot and stop at the Stops and the Depot.

Tunnel

Depot

Stop Stop

Figure 5 The track layout for the tram simulation

To help the designers, an application is to be built which simulates the trams and their travels around the tramway loop.

The simulation is performed by having two threads, one for each tram, for which the run method consists, in outline, of calling two routines, named travel and stop, several times.

// each tram makes 3 loops of the track for (int j = 0; j < 3; j++) { System.out.println (spaces(id) + "Tram " + id + " leaves Depot"); travel (10, id); // tram travels 10 units of distance from Depot to first stop System.out.println (spaces(id) + "Tram " + id + " arrives at stop");

stop (5); // tram waits at first stop for 5 time units

travel (15, id); // tram travels 15 units of distance from first stop to tunnel

System.out.println (spaces(id) + "Tram " + id + " arrives at tunnel");

tun.useTunnel (this); // the tunnel is used by the tram represented by 'this'

travel (15, id); // tram travels 15 units of distance from tunnel to second stop System.out.println (spaces(id) + "Tram " + id + " arrives at stop");

stop (5); // tram waits at second stop for 5 time units

travel (10, id); // tram travels 10 units of distance from second stop to Depot System.out.println (spaces(id) + "Tram " + id + " arrives at Depot"); stop (10); // tram waits at depot for 10 time units } System.out.println(spaces(id) + "Tram " + id + " out of service");

The object tun is an instance of the class Tunnel that has a single method useTunnel which simulates a tram (given as an argument) travelling through the tunnel:

public void useTunnel (Tram t) { System.out.println (spaces (t.getId()) + "Tram " + t.getId() + " enters tunnel"); t.travel(20, t.getId()); // tram takes 20 time units to travel through tunnel System.out.println (spaces (t.getId()) + "Tram " + t.getId() + " exits tunnel");

7 7

Page 28: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

}

The routine travel takes two arguments. The first represents a distance travelled and represents the time taken to travel between stops. Its implementation is a loop that repeatedly performs a simple calculation to simulate the passage of time, proportional to the distance travelled. However, it has been so designed that tram 2 takes twice the time to travel the same distance as tram 1. The second argument is an integer, id, that identifies each tram (either 1 or 2).

The routine stop simply loops for a simulated time given by its argument and represents the amount of time a tram spends at each stop putting down and picking up passengers.

The run and useTunnel methods print out the progress of the simulation by indicating where each tram has reached.

(i) This part of the question requires you to familiarise yourself with the software by running the simulation without any attempt to ensure exclusive use of the tunnel resource.

(a) Open the project named TramA, stored in the directory \JavaProjects\Exercises\Tramway\TramA, using your IDE.

Complete the class named Simulate so that it has a main method that creates a single tunnel and two trams (as separate threads) and sets them going. Submit a copy of your amended Simulate class. [4 marks]

(b) Run the project. You should observe that it is possible for a second tram to enter the tunnel before the first tram has left the tunnel.

Explain briefly what information in the output leads you to this observation (you should include a copy of the output which illustrates your answer). [2 marks]

Note: the speed of the simulation will depend upon the speed of your computer. To alter the speed of the simulation, change the value of the constant that defines the variable speedFactor declared within the class Timer.

(ii) This part of the question requires you to use Java's synchronization facilities in order to guarantee that each train has exclusive access to the tunnel.

(a) Amend the TramA application using Java’s facilities for ensuring mutual exclusion so that only one tram is allowed in the tunnel at any one time.

Run the project. You should observe that it is no longer possible for a second tram to enter the tunnel before the first tram has come through the tunnel.

Submit a copy of your completed class Tram.java. Include a copy of the output window showing that a tram is forced to wait if the other tram is in the tunnel. [2 marks]

(b) Explain, in your own words, why your solution in (a) works. [2 marks]

(iii) When it was built, the tramway was a success, so the City decided to extend the system as follows. A bus service was to be run between the Depot and the Airport as shown in Figure 6.

8 8

Page 29: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Tunnel

Depot

Stop Stop

Depot

Airport

Waitingroom

Figure 6 An extended tramway system

A bus provides a shuttle service between the Depot and the Airport and is simulated by a run method:

// bus makes 10 journeys for (int j = 0; j < 10; j++) { System.out.println ("\t\tBus leaves Depot"); travel (30, 1); // Bus travels 30 units of distance from Depot to Airport System.out.println ("\t\tBus arrives at airport"); stop (10); // Bus waits at stop for 10 time units travel (30, 1); // Bus travels 30 units of distance from Airport to Depot System.out.println ("\t\tBus arrives at Depot"); stop (10); // Bus waits at depot for 10 time units }

When the bus arrives at the Depot, passengers wishing to use the tramway wait in a waiting room. Having stopped at the Depot to set passengers down and pick up new passengers, the bus travels to the Airport.

When a tram arrives at the Depot it must synchronize with the bus as follows. If the bus has set down passengers, the tram simply stops at the Depot for the specified time and then moves on. However, if the tram arrives at the Depot before the bus has returned from the Airport, the tram must wait until the bus arrives.

The software is to simulate the synchronization of the bus with trams as follows. The waiting room is to be represented by an object from the class WaitingRoom that has two public methods:

• setPassWaiting, which signals to other threads waiting for passengers that they can continue their execution;

• getPassWaiting, which causes the calling thread to wait if there are no passengers waiting.

In effect, the class WaitingRoom acts as semaphore.

9 9

Page 30: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Complete the implementation of WaitingRoom (it can be found in the folder C:\JavaProjects\Exercises\Tramway\TramB) in such a way that access to the 'buffer' passengersWaiting is performed under mutual exclusion and with the condition synchronization described above. Copy your revised version of the class WaitingRoom to your Solution Document. [3 marks]

(iv) (a) Complete the implementation of the classes Simulate, Tram and Bus. Copy your revised Simulate, Tram and Bus classes to your Solution Document. [3 marks]

(b) Also copy a part of the output trace that illustrates:

• an example of where a tram does not have to wait for the bus;

• an example of where a tram has to wait for the bus. [4 marks]

On completion of this question, add your Solution Document to your zip archive file for this TMA (you should already have added the three Java source code files requested in the question).

This should complete your work on this TMA, and your zip archive file should contain four files: one Solution Document, and three files containing Java source code (from Question 5).

You should now submit your completed zip archive file to the electronic TMAs system on or before the cut-off date for this TMA.

10 10

Page 31: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

11 11

Page 32: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Information Technology and Computing: Level 3 M301 Software Systems and their Development

ARAB OPEN UNIVERSITY

Faculty of Computer Studies

M301

Assignment Booklet 3 Contents Cut-off date TMA M301 2005-2006 11 March 2006

Enter your solutions to this tutor marked assignment (TMA) into a single word-processed document known as the Solution Document. The Solution Document (clearly headed with your name, the number of the TMA as given above, and your personal identifier) should contain all text, diagrams and screen dumps requested in the questions. A file containing a template for the Solution Document, showing how your solutions should be laid out, can be downloaded from the M301 web site. (You may, of course, choose to use your own Solution Document.)

The marks allocated to each part of each question are indicated in brackets in the margin.

Note that, in answering the questions in this TMA, more is expected than simply reproducing passages from the course materials. In those instances where you feel it is essential to use extracts from these materials you must indicate their source. To do otherwise is plagiarism.

To avoid the difficulties that will arise if you inadvertently lose the contents of your Solution Document, we recommend that you add it to the zip archive file (overwriting any previous copy) each time you complete a question.

12 12

Page 33: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

TMA 03 Cut-off date 11 March 2006 Important Please ensure that your Solution Document is readable in Word . If you are in any doubt, try reading your document using WordViewer before submitting it to the e-TMAs system.

Create a new zip archive file for this TMA and name it TMA03. On completion of a question, add your Solution Document to this zip archive file. Each time you do this, you will overwrite the copy of the Solution Document that is in the TMA03 zip archive file, but doing this will be a way of providing a back-up of your work.

Question 1 [20 marks] This question tests your understanding of the concepts and techniques in Unit 3.1.

(i) (a) In Bacon, Figure 12.7(a), explain what the process on the left can do after it performs a SEND operation and identify which mechanism enables it to do this. [3 marks]

(b) Explain in your own words, why the sending of messages in Bacon, Figure 12.7(b) is said to be synchronous. [2 marks]

(c) Explain why a monitor is considered to be a ‘passive structure’. [2 marks]

(d) What do the calls to FORK and JOIN intend to achieve when calling a monitor, as illustrated in Figure 12.10 in Bacon? [3 marks]

(ii) (a) Explain, with reference to Bacon Figure 15.7, whether RPC is considered to be synchronous or asynchronous. [3 marks]

(b) Explain how the RPC protocol in Figure 15.7 works when a network failure occurs between points D and E. [4 marks]

(c) Bacon, Figure 15.10, shows how communication across a network passes through several levels, from the application level at the top, to the lower levels of communications software. The RPC is situated on top of the transport layer. Bacon discusses two types of semantics in RPC, which deal specifically with the fact that this transport layer may be unreliable. Explain which of these semantics you would select if it were very important for you to know that a message had arrived safely, even though the same message might have to be re-sent several times? [3 marks]

On completion of this question, add your Solution Document to the TMA03 zip archive file.

Copyright © 2005 The Arab Open University SUP 52039 5 2.1

Page 34: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Question 2 [20 marks] This question is based on the material in Unit 3.2.

(i) Give the name and the main function of each of the three classes in the java.net package, which is used for the implementation of client–server systems. [3 marks]

(ii) You are provided with two incomplete files that form part of a multi-threaded client–server implementation of a simple calculator application. In this application the clients can provide numbers; and on the server side, these numbers are added up for each client before they are sent back to the client and shown to them.

The following is an example of what the user of the client program will see on their output screen.

Hello. Welcome to your calculator. What is your name? anna

anna, with which number do you want to begin today? 4

0 + 4 = 4, what is your next number to be added? 5

4 + 5 = 9, what is your next number to be added? 11

9 + 11 = 20, what is your next number to be added? quit

Figure 1 Input and output for the Calculator application

In Figure 1, the input by the user of a client program is indicated in italics.

The application uses three classes: CalculateClient (the client), Calculator (the server) and CalculateSession (each session is a thread that does the actual calculation). The first two classes are provided in Figures 2 and 3 (overleaf), albeit they are incomplete.

2 M301 AB5

Page 35: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

import java.io.*; import java.net.*; public class CalculateClient { public static final int portNumber = 5321; private BufferedReader input, term; private Writer output; public static void main (String [] args) { try { CalculateClient world = new CalculateClient(); } catch (IOException e) { System.out.println ("Trapped an IO exception " + e); } } public CalculateClient () throws IOException { term = new BufferedReader (new InputStreamReader (System.in)); //open socket as a reader and writer Socket sock = new Socket ("localhost", ****); // 1 Reader isRead = new InputStreamReader (sock.****); // 2 input = new BufferedReader (isRead); output = new OutputStreamWriter (sock.****); // 3 // now read and print while (true) { // read and print something from calculator String line = input.readLine (); System.out.println (line); // get user's response line = term.readLine (); if (line.equals ("Quit") || line.equals ("quit")) break; output.write (line + "\n"); output.flush (); } } }

Figure 2 CalculateClient class

3 M301 AB5

Page 36: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

import java.net.*; import java.io.*; public class Calculator { public static void main (String args []) { try { Calculator world = new Calculator (); } catch (IOException e) { System.out.println ("Server Socket failed" + e); System.exit (1); } } static final public int portNumber = ****; // 4 public Calculator () throws IOException { ServerSocket server = new **** ; // 5 System.out.println ("Waiting for first client"); int i = 1; while (true) { Socket sock2 = ****; // 6 System.out.println ("Client No " + i + " accepted"); //start new thread to handle session Thread session = new CalculateSession (sock2.getInputStream (), sock2.getOutputStream ()); session.****; // 7 i++; } } }

Figure 3 Calculator class

(a) Download from the M301 web site (from the web page for Block 3, Unit 3.2) a zip file, named TMA03java.zip, containing among others the incomplete classes CalculateClient and Calculator. Extract the files from TMA03java.zip into your C:\JavaProjects folder. A folder named TMA03 has now been created which contains two sub-folders: Calc and GreeterClient. In this question you will use the .java and .jpr files found in Calc and its sub-folders, whereas Question 2 part (iii) uses the GreeterClient folder.

Complete the classes CalculateClient and Calculator by providing the code for the parts marked ****, which are lines marked with a number. Submit only the code fragments you have produced rather than the whole file. Please number each fragment with the appropriate line number shown in Figures 2 and 3. [3 marks]

(b) Why is the constructor for CalculateClient marked with a ‘throws IOException’ clause? [2 marks]

(c) Write the code for the class CalculateSession according to the specification given. Include in your Solution Document the java code for your new CalculateSession class. [4 marks]

The specification for the class CalculateSession is as follows.

4 M301 AB5

Page 37: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

• CalculateSession is a subclass of Thread.

• The constructor for the class CalculateSession converts the input and output streams from the server Calculator into buffered readers and writers to simplify input and output.

• CalculateSession has two methods:

(1) run, which is invoked when the class is started by the Calculator.

The run method

• offers an appropriate welcome message, and requests the user’s name, followed by a flush statement, in order to mark the end of the output;

• reads the input from the user, and assumes it to be a one-word name;

• outputs a further message, requesting the user to provide a number, followed by a flush statement;

• has an infinite while loop containing the following steps:

• read a line from the user, which is assumed to be a number

• calculate the running total and output it

• flush the output.

(2) add, which accepts string input and will do the actual calculation involved in adding numbers. It outputs the result of the calculation as a String. The code for this method is provided below and assumes the declaration

private int runningTotal = 0;

as a data field of the class CalculateSession.

private String add (String inputNumber) { int previous = runningTotal; runningTotal= runningTotal + Integer.parseInt (inputNumber); return (previous + " + " + inputNumber + " = " + runningTotal + ", what is your next number to be added?"); }

Integer.parse (Int), which takes a String, and returns an int is similar to the method Integer.valueOf which takes a String but returns an Integer object (Budd, Section 6.1.4)

Note in order to run your application you need to add CalculateSession to the CalcServer project provided, setting Calculator as the main class.

(d) Run the calculator application with one server, and three clients, whose names are Anna, Beatrice and Catherine. Anna uses the numbers 7, 2 and 3; Beatrice has 13, 14 and 15 as input, and Catherine inputs 42, 2 and 1.

Include in your Solution Document a copy of the output window for your program, showing a tab for the server process, a tab for each client process and the active screen showing Anna as client. [1 mark]

(iii) This question asks you to use Java’s RMI facility by running both a client and a server on your machine. There are several tricky steps that must be followed to enable RMI to work successfully. The details are given below. Please ensure that the instructions are followed completely, otherwise you may have to repeat them from the beginning. Despite the length of the question, the steps should not take too long to complete.

5 M301 AB5

Page 38: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

The client application simply invokes a remote object (on the server) that returns a String value and prints out the returned message. The class of the remote object is named Greeter that contains a method named getInfo with the following signature.

public String getInfo (String aName);

This method takes a String argument (which should be your name) and returns a personalized message as a String.

In this question you should use the inbuilt facility of JBuilder35 for using RMI. To enable you to use this method you have been provided with the stub class, which is necessary for this project, instead of having to create this yourself.

Complete the following steps.

(1) If you have not already done so, download from the M301 web site (from the web page for Block 3, Unit 3.2), a zip file named TMA03java.zip, which contains among others:

• an incomplete version of the client, named GreeterClient; this will create a dialogue box in which you can type your name and which will return a personalized message. You must amend this code to include the RMI mechanism.

• a complete version of the server, named Greeter, which contains three classes named Greeter, GreeterImpl and GreeterServer.

• the stub class file named GreeterImpl_Stub.class.

(2) If you have not done so, unzip TMA03java.zip. Extract the contents into C:\JavaProjects. You should find that a new directory TMA03 and a subdirectory named GreeterRMI has been created containing two projects named GreeterClient and GreeterServer, each of which contains .java source files and a .jpr project file. The GreeterRMI folder also contains a file named GreeterImpl_Stub.class.

(3) Complete the client class GreeterClient.

(4) Before you try to compile the projects, it is important to switch off two of the run properties for both projects. To do this, open project GreeterServer in JBuilder35, and right click on the project name, select Properties...., click on the tab labelled Run, and de-select the two properties: Compile before running and Compile before debugging. Press OK. Now do the same for project GreeterClient.

Compile each of the projects. To do this, right click on each project name in turn and choose Make.

(5) Add a copy of the downloaded stub file GreeterImpl_Stub.class to both the classes directory that contains the client classes and the classes directory that contains the server classes. You can use your Windows Explorer to do this.

(6) Save both projects.

(7) You now need to change the CLASSPATH environment variable to the correct value. Carefully follow the instructions in point 1 of How to get it to work, on page 22 of Unit 3.2, but instead of setting it to the Ballworld folder, use the following two pathnames

C:\JavaProjects\TMA03\GreeterRMI\GreeterServer\classes;C:\JavaProjects\TMA03\GreeterRMI\GreeterClient\classes

6 M301 AB5

Page 39: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

assuming that those are the names of the folders that you used on your machine. It is very important to reboot your machine at this point, in order for these changes to take effect.

(8) In JBuilder35, select the Tools menu and choose the item RMIRegistry. This sets the RMI registry running.

(9) Run the GreeterServer. You should see the message Remote greeter object registered.

(10) Run the GreeterClient.

Add the following to your Solution Document:

(a) the Java code for your completed GreeterClient class; [5 marks]

(b) a screen dump showing the output from running your completed GreeterClient. [2 marks]

On completion of this question, add the Solution Document to the TMA03 zip archive file.

7 M301 AB5

Page 40: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Question 3 [20 marks] This question is based on the material in Unit 3.3.

(i) (a) “In some cases it is possible to ensure crash resilience by choosing an idempotent implementation for operations.” Explain what is meant by this statement, and explain the terms ‘crash resilience’ and ‘idempotent’. [3 marks]

(b) Suppose that you are given the following declarations in Java, where class Cannon is as defined in Budd Figure 6.3:

public static final int FrameHeight = 400; Cannon cannon = new Cannon (new Point (20, FrameHeight –10)); int x, y , z;

For each of the following statements, state whether or not it is idempotent.

cannon.setAngle(30); z = FrameHeight – 50; y = x + 3; [3 marks]

(ii) Figure 4 describes a system similar to those shown in Bacon, Figures 17.1 and 17.2, using two resources and two processes.

Get A Get BRelease A Release B

Progress of P

Get B

Get A

Release B

Release A

Progress of Q

P and Q

want A

P and Q

want B

h

1

Figure 4 Two processes using two objects

(a) In the manner of SAQ 17.2(c), describe what happens along path h as shown in Figure 4 up to point 1. [2 marks]

(b) Explain whether path h is deadlocked at point 1, or whether it can proceed. If it can proceed, illustrate how it might progress to completion. [2 marks]

(iii) This question refers to the notation for Object Allocation Graphs as discussed in Bacon, Section 17.6.

8 M301 AB5

Page 41: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

P

Q

R1

R3

R2

R4

Figure 5 Incomplete Object Allocation Graph

(a)Complete the graph in Figure 5, to show the following situation:

• Process P holds one instance each of resources R1 and R3

• Process P requests one instance each of resources R2 and R4

• Process Q holds one instance each of resources R2 and R4

• Process Q requests one instance of resource R3

in which there exists only one instance of each of resources R1, R2 and R4, but there are two instances of resource R3. [2 marks]

(b) Can you detect deadlock in the graph? Explain your answer. [2 marks]

(iv) Given the following composite operations:

Process P executes transfer (accountD, accountC, £400)

Process Q executes transfer (accountC, accountD, £250)

(a) Write out, in the manner of Bacon, Section 16.5, how the composite operation P consists of a number of sub-operations. Show two levels of detail. [3 marks]

(b) Imagine that for the execution of processes P and Q the following schedule of interleaved sub-operations is produced, where accountC and accountD each have £1000 initially:

P: read value of accountD

Q: read value of accountC

P: check value >= 400, and write original value – 400 to accountD

P: complete the whole credit operation on accountC

Q: check value >=250, write original value –250 to accountC

Q: complete the whole credit operation on accountD

Given the above interleaving of sub-operations, state the amount of money each account holds after the execution of the schedule, and explain whether the transfers have been executed correctly. [3 marks]

On completion of this question, add the Solution Document to the TMA03 zip archive file.

9 M301 AB5

Page 42: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Question 4 [20 marks] This question is based on the material in Unit 3.4.

Before you start work on this question, make sure that you have incorporated the errata for Bacon, Chapter 18, in particular those relating to Subsection 18.6.2, the condition for serializability. See the web page for Unit 3.4.

(i) Using the following description of transactions and SLAs together with your understanding of concurrency, describe the main difference and the main similarity between a transaction and an SLA, and explain why the difference is important. [4 marks]

A composite action is referred to as a transaction in Bacon, Chapter 18. A transaction consists of smaller sub-operations. A sub-operation is also referred to as a Single Logical Action (SLA) or a Single Concurrent Action (SCA). To achieve concurrency control, SLAs are made to be strictly indivisible atomic operations through the use of monitors. However, it is not desirable to treat transactions as strictly indivisible. Instead, we want transactions to appear atomic and appear indivisible, while in practice the executions of the sub-operations of transactions are interleaved.

For example, if two transactions, X and Y, were to be executed concurrently, the result should be as though the transactions were executed one after the other (that is, serially). Thus, the result should be either the same as executing X first then Y, or Y followed by X. In reality, the sub-operations may have been interleaved. In other words, we do not care in what order X and Y appear to have been executed, but we insist that the result is the same as would have been obtained had they been executed serially (one after the other).

(ii) The definition of serializability can be given as follows.

“to interleave the sub-operations of transactions in such a way that the transactions appear to be executing in a serial order.”

The condition for serializability outlines what needs to be true, in order for transactions to be said to be serializable. The condition can be defined as follows.

“if transactions have conflicting sub-operations acting on the same object, then those sub-operations should be scheduled in the same order for each transaction”

For this question we shall use the two transactions given in Bacon, Section 18.6: Transfer (T) and Sum (S), working on two accounts A and B.

transaction T: debit(A, 500); credit(B, 500). transaction S: read(A); read(B); print(A+B).

10 M301 AB5

Page 43: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

The two conflicting pairs of operations are:

read(A) conflicts with debit(A, 500) read(B) conflicts with credit(B, 500).

(c) Explain why the two pairs of operations are conflicting. [2 marks]

(d) Why do read(B) and debit(A, 500) not conflict? [1 mark]

(c) Imagine that the command is given to execute transactions T and S. It turns out that in practice the following schedule of interleaved sub-operations is produced (where time starts at the top, and increases down the page).

T : debit(A, 500)

S : read(A)

T : credit(B,500)

S : read(B)

S : print (A+B)

Figure 6 A schedule of sub-operations

Specify in which order (i.e. T before S, or S before T) the conflicting pairs of operations on each object are executed in the schedule of Figure 6. [1 mark]

(d) Given your answer in part (c), explain in terms of the condition for serializability whether the transactions are serializable in the schedule in Figure 6. [2 marks]

(e) Again the command is given to execute transactions T and S. The schedule of sub-operations begins as follows:

S : read(A) .........

Complete this schedule for interleaving the sub-operations in such a way that the execution is NOT serializable. Explain why your schedule is not serializable in terms of the definition for serializability. [2 marks]

(iii) Suppose that there are three transactions, T1 a Credit transaction, T2 a Transfer transaction, and T3 a Sum transaction, as defined in Figure 7, where:

• C = commit

• Cr = credit

• D = debit

• Pr = print

• R = read

• S = start

11 M301 AB5

Page 44: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

S2 D2B Cr2A C2

S3 R3B Pr3C3

R3A

R3C

S1 Cr1B C1T1

T2

T3

Figure 7 Three transactions and their sub-operations

(a) In the style of Bacon, Figure 19.4, redraw the diagram in Figure 7 such that it will include the nodes that would be necessary if the strategy of 2PL was used for concurrency control. [4 marks]

(b) Apply TSO to the schedule of interleaved sub-operations given in Figure 6, assuming that S starts before T. Show for each operation whether it is allowed given the time stamp ordering. What do you conclude? [4 marks]

On completion of this question, add the Solution Document to the TMA03 zip archive file.

12 M301 AB5

Page 45: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Question 5 [20 marks] This question tests your understanding of Unit 3.5 and the Section of the Case Study entitled Using a Distributed Object.

(i) What common problem are RMI and CORBA designed to solve? [2 marks]

(ii) What is the one major difference between RMI and CORBA? [2 marks]

(iii) What is the purpose of a proxy object in RMI and CORBA, and what actions does it perform? [4 marks]

(iv) What is the purpose of the interface definition language (IDL) in CORBA? Your answer should describe, in no more than 100 words, the role IDL plays in CORBA and why it is essential to the CORBA approach to distributed objects. [5 marks]

(v) Describe, in your own words, the purpose of the ORB in CORBA. Your answer should clearly show why an ORB is essential to the CORBA approach. [3 marks]

(vi) What was the problem described in Section 9 of the Case Study, that the developers of the banking system were trying to solve when they decided to use CORBA? Your answer should clearly show how CORBA solved the problem. [4 marks]

On completion of this question, add your Solution Document to the TMA03 zip archive file.

You should now submit your completed TMA03 zip archive file to the e-TMAs system on or before the cut-off date.

13 M301 AB5

Page 46: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

14 M301 AB5

Page 47: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Information Technology and Computing: Level 3 M301 Software Systems and their Development

ARAB OPEN UNIVERSITY

Faculty of Computer Studies

M301

Assignment Booklet 4

Contents Cut-off date

TMA M301 2005/2006 15 April 2006

Enter your solutions to this Tutor Marked Assignment (TMA) into a single word-processed document known as the Solution Document. The Solution Document (clearly headed with your name, the number of the TMA as given above, and your personal identifier) should contain all text, diagrams and screen dumps requested in the questions. You are not expected to submit additional files containing Java code unless you are asked to do so.

Please submit your solution to this TMA to the electronic TMAs (e-TMAs) system on or before the cut-off date shown above in the form of a zip archive file containing the Solution Document. You will find details on how to create a zip archive file in the Guide to Electronic Tuition. You will find details on how to submit a zip archive file to the e-TMA system in Using the Electronic TMAs System — A Student Guide to e-TMAs.

You do NOT have to submit a PT3 form when submitting electronic TMAs.

The marks allocated to each part of each question are indicated in brackets in the margin.

Note that, in answering the questions in this TMA, more is expected than simply reproducing passages from the course materials. In those instances where you feel it is essential to use extracts from these materials you must indicate their source. To do otherwise is plagiarism.

To avoid the difficulties that will arise if you inadvertently lose the contents of your Solution Document, we recommend that you add it to the zip archive file (overwriting any previous copy) each time you complete a question.

15 M301 AB5

Page 48: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

TMA M301 04 Cut-off date 15 April 2006 Important Please ensure that your Solution Document is readable in Word. If you are in any doubt, try reading your document using WordViewer before submitting it to the e-TMAs system.

Create a new zip archive file for this TMA and name it TMA04. On completion of a question, add your Solution Document to this zip archive file. Each time you do this, you will overwrite the copy of the Solution Document that is in the TMA04 zip archive file, but doing this will be a way of providing a back-up of your work.

Question 1 [20 marks] This question is based on the material in Unit 4.1.

(i) In your own words, explain why a software development process should adopt risk management as a central concept and how iteration helps to control risk. [4 marks]

(ii) Figure 5.1 of Unit 4.1 shows three use cases for a hotel reservation system and Figure 5.2 shows the corresponding business objects as classes. Figure 1.1 below shows two ways of implementing the use cases. Alternative A implements each use case as an operation in one central class called ReservationSystem. Alternative B implements each use case in its own special class. For simplicity, both implementations assume that there will be one user interface class for each use case, and that all communication with the business objects will be done through the Hotel class. Multiplicities are not shown.

Explain the difference in coupling and cohesion between alternatives A and B. Which of the two alternatives offers the better chances of reuse? [6 marks]

Figure 1.1

Copyright © 2005 The Arab Open University SUP 52041 5 2.1

Page 49: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

(iii) Subsection 3.3 of Unit 4.1 describes four models that are created and used by developers of a software system: conceptual, specification, implementation and deployment. It also describes five core activities for the development of a good software system. Draw up a table that indicates when each model is created (use the letter C) and potentially modified (use the letter M). You should justify your choice of entries for each model. You should assume a product life cycle that is both iterative and incremental. [10 marks]

On completion of this question, add your Solution Document to the TMA04 zip archive file.

2 M301 AB5

Page 50: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

The following description of a tennis club is used in Questions 2, 3 and 4 Walton Tennis Club (WTC) has an extensive range of facilities. It has both indoor and outdoor courts, a heated swimming pool and a gym with a variety of exercise machines that members can use. WTC wants to implement a booking system for their facilities. Members must book tennis courts or gym sessions in advance. Indoor courts have a higher fee than those outdoors. Tennis courts and gym sessions are cheaper in off-peak periods. Booking is not required for the swimming pool.

At the moment, members have to contact the reception desk, either in person or by phone, to make a booking. WTC want to reduce the workload on the receptionists and give their members a more direct booking system. Their solution is to allow members to use a web browser to book their tennis courts or gym sessions.

WTC already has two software systems: one to store and maintain its membership list and another to look after its accounts. The new software system will only accept members’ requests as long as there are courts or gym sessions available at the time they want them. Since members’ fees are collected on a monthly basis, the normal course of action is to add the cost of each booking to their accounts. Alternatively, it must be possible for a member to request a bill for the cost of the booking. The member will then pay the receptionist.

When members arrive at the WTC, the receptionist will use the new software to record which member has arrived for a given court or gym session. At this point, the software will amend the member’s account and produce a bill, if necessary.

As there are many more members than courts or gym sessions, a cancellation fee will be charged if the member does not take up a booking. In order to avoid a cancellation fee, members must give 24 hours’ notice if they no longer want a particular court or gym session. The receptionist will apply the cancellation fees that arise at the end of his/her working day.

WTC belongs to a local sports association, The Midshires Racquets Association, which, amongst other things, arranges competitions between its member clubs’ teams and trains coaches. Individuals must be members of a club if they wish to play for a club’s team.

3 M301 AB5

Page 51: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Question 2 [20 marks] This question is based on Unit 4.2

(i) (a) Identify the reasons for representing an actor from a use case diagram as a class in a software system. Use the description of the Walton Tennis Club given above to illustrate your answer. [4 marks]

(b) Use the issue copy of video use case in the example of a video rental business shown in Figure 2.9 on page 32 of Unit 4.2 to explain the difference between the <<extend>> and the <<include>> stereotypes. [2 marks]

(ii) (a) Draw an activity diagram that shows how the Reserver and hotel system interact for the make reservation use case that is described in Figure 2.5 of Unit 4.2.

Hint: use the solution to Exercise 4.1 of Unit 4.2 as a guide in developing your model.

Copy your activity diagram to your Solution Document. [10 marks]

(b) Using your answer to part (ii)(a), explain the difference between a synchronization bar and a decision diamond. [4 marks]

On completion of this question, add your Solution Document to the TMA04 zip archive file. (You should already have added the use case diagram for part (i)(a) and the activity diagram for part (ii)(a) to your Solution Document. If you were unable to do this, ensure that you have added the .mdl file containing your use case diagram and your activity diagram to the TMA04 zip archive file.)

4 M301 AB5

Page 52: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Question 3 [20 marks] This question is based on the material in Unit 4.3 and also Section 5 of Unit 4.1.

(i) Apply the noun identification technique, which is described on pages 54 and 55 of Unit 4.1, to arrive at a set of candidate classes for WTC’s proposed direct booking system, which you would use as the basis of a class diagram.

Work through the list of candidate classes, and decide whether or not to keep or discard each one. Your answer should consist of a table with the following headings

Candidate class name

Keep? Reason for keeping or discarding candidate class Yes / No

[7 marks

(ii) Figure 3.1 and Figure 3.2 below show two alternatives that might be included in a class model of a membership system for a general sports association.

Figure 3.1

Figure 3.2

Study each class diagram then answer the following questions.

(a) For each class diagram, identify the objects and links that must exist in order to create a new Team object. [4 marks]

(b) Which one of the two class diagrams would allow AssociateMember objects to take up the role of captain for a given Team object? Briefly, explain your answer. [2 marks]

5 M301 AB5

Page 53: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

(c) The Midshires Racquets Association has eight clubs: four for tennis and four for squash. Michael Newton is a very keen sportsman. He plays for and captains the WTC first team at tennis and also plays for the Kingston club’s squash team. For each class diagram, explain whether or not this scenario is represented. [4 marks]

(d) In the case of Figure 3.2 only, suppose that you want to capture as an invariant the commonly occurring rule in sports clubs that someone who captains a team cannot also be the coach of the team. Write down the invariant using the notation of Section 4 of Unit 4.3. In which class would you place this invariant? [3 marks]

On completion of this question, add your Solution Document to the TMA04 zip archive file.

6 M301 AB5

Page 54: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Question 4 [20 marks] This question is based on Section 1 of Unit 4.3, Unit 4.4 and Section 2 of Unit 4.5. Suppose you are working on a design for a general sports association that was introduced in Question 3(ii). For this question, you are asked to investigate an operation called appointNewCoach using the class diagram shown in Figure 3.1 of Question 3. In order to consider some design options, we have added a new class called TeamAdministrator where we have placed the operation appointNewCoach, as can be seen in Figure 4.1.

AssociateMember

Club

PlayingMember

Member- nameOfMember- addressOfMember- membershipNumber

+ addToTeamsCoached(newGroup : Team)

0..*11 0..*

TeamAdministrator

+ appointNewCoach(intendedTeam : Team, newCoach : Member)+ identifyMember(membershipNumber : String) : Member+ identifyTeam(teamToCoach : String) : Team

Team

+ addToCoaches(newCoach : Member)+ acceptNewCoach(apointee : Member)

0..*0..* 0..*

+players

0..*

0..10..1 0..1

+captain

0..1

0..*

0..2

0..*

+coaches

0..2

0..*

0..1

0..*

0..1

Figure 4.1

Figure 4.1 also shows some other operations and attributes that have been included in our initial design. Also, it assumes that Member is an abstract class. In order to appoint a new coach to a team, you would need to know which member of the club is intended to take up this new role. From the multiplicity of the coaching role, you can see that there is a maximum of two coaches allowed for each team.

The class diagram in Figure 4.1 can be found in the Rational Rose model file called generalSportsAssociation, which you will have downloaded with this TMA from the M301 web site.

Figure 4.2 shows a pair of object diagrams to help determine a possible design for the operation called appointNewCoach.

7 M301 AB5

Page 55: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

coaches

ta : TeamAdministrator t7 : Team

a55 : AssociateMembernameOfMember: jillBefore

coaches

coaches

ta : TeamAdministrator t7 : Team

a55 : AssociateMember

p11 : PlayingMember nameOfMember: jack

After

Figure 4.2

(a) Figure 4.2 does not show objects from all the classes given in Figure 4.1. Briefly, explain why using object diagrams helps us to understand the constraints upon a particular operation. [2 marks]

(b) Describe the contract for the operation appointNewCoach in terms of objects and links created. [4 marks]

(c) Use the facilities of Rational Rose to draw a sequence diagram to show a design for the operation appointNewCoach, which uses the information given in Figure 4.1 and Figure 4.2. Assume that there is a class called TestUserInterface, which sends messages to a TeamAdministrator object.

Copy the sequence diagram into to your Solution Document. [6 marks]

(d) Use your answer to part (i)(c) to generate the corresponding collaboration diagram.

Copy the collaboration diagram into your Solution Document. [2 marks]

(e) Using your answer to parts (i)(c) and (i)(d), explain why multi-stage decimal message numbering is used in a collaboration diagram but not necessarily in a sequence diagram. [3 marks]

(ii) Using a class such as TeamAdministrator in Figure 4.1 is an example of a design strategy called actor classes. Briefly, explain why this strategy is better than using one central class. Identify a weakness of the actor classes strategy using an example from the general sports association model. [3 marks]

On completion of this question, add the Solution Document to the TMA04 zip archive file. (You should already have added the sequence diagram for part (i)(b) to your Solution Document. If you were unable to do this, ensure that you have added your .mdl file containing the sequence diagram to the TMA04 zip archive file.)

8 M301 AB5

Page 56: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Question 5 [20 marks] This question is primarily based on the material in Unit 4.5

(i) (a) Figure 1.4 of Unit 4.5 shows an interaction within a motorists’ warning system. If you assume that frost is expected when the air temperature drops below 0 ºC, suggest a suitable guard for the frost() message. [3 marks]

(b) In the UML, activity diagrams are treated as a special kind of statechart diagram. Use your answer to Question 2 part (ii)(a) to identify the event that causes a transition from one activity to another. What type of state machine event is it? Briefly, explain your answer. [4 marks]

(c) Figure 5.3 on page 45 of Unit 4.5 shows a three-layered architecture for a software system. Choose which classes from Figure 4.1 and part (i)(c) of Question 4 should go into each package. Briefly, justify your choice. [3 marks]

(ii) In Unit 2.2, you studied the behaviour of processes in a computing system. Use the following description of the class Process that models the life cycle of a simplified process.

When a Process is created, it must request the necessary resources from the operating system. Once the resources have been made available, a Process is said to be runnable. The scheduler will then tell the Process when it can execute on a processor. If the Process runs out of time before completing its task, it must return to the previous state and wait its turn. If a Process requests more memory than is currently available, it is said to be blocked until that resource becomes available. However, it must wait until the scheduler allows it to continue its execution. When a Process has completed successfully, it must release the resources it used before being removed from the system.

Draw a statechart diagram that represents the typical history of an object of the class Process. You should identify the state that is entered upon object creation and the transitions that take an object from one state to another until it completes.

Copy the statechart diagram into your Solution Document. [10 marks]

On completion of this question, add your Solution Document to the TMA04 zip archive file. (You should already have added the state diagram for part (ii) to your Solution Document. If you were unable to do this, ensure that you have added your .mdl file containing the state diagram to the TMA04 zip archive file). This should complete your work on the TMA. Your zip archive should contain just one file, if you have been able to add each of the UML diagrams to your Solution Document (otherwise it should contain no more than one .mdl file in addition to your Solution Document). You should now submit your completed TMA04 zip archive file to the e-TMAs system on or before the cut-off date.

9 M301 AB5

Page 57: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Appendix: Putting diagrams from the modelling tool into a Word document This section is included to help you prepare a single file for submission to your tutor. The following instructions apply to users of Microsoft Word software. We do not guarantee that the procedure will apply to other word processing software. To place a diagram from the modelling tool at a particular point in your Word document, follow the steps below.

1. Place the cursor at the point in your document where you want to locate the UML diagram.

2. Switch to the modelling tool. For example, click on the button labelled Rational Rose - yourModelName in the task bar to open its application window.

3. In the modelling tool, open the diagram that you want to copy and paste into your assignment. For example, it may be a use case diagram or state diagram.

4. In your chosen diagram, select all the elements you want to copy. For instance, you can select all the elements of a diagram by using Control-A or Select All from the Edit menu. Then copy them onto the clipboard by using Control-C or Copy from the Edit menu.

5. Switch back to the picture in your document. For example, click on the button labelled Microsoft Word - yourDocumentName in the task bar to open your assignment.

6. Paste the UML diagram into your assignment at the point chosen in step 1 by using either Control-V or Paste after a right click.

7. Right click on the diagram and select Format picture. Select the Position tab. Remove the tick from the checkbox labelled float over text and click OK.

8. Adjust the size of the UML diagram in your assignment by using your mouse. If you cannot copy diagrams from Rational Rose to your word processor, save your complete model (as a .mdl file) and then add it to your zip file for this assignment.

10 M301 AB5

Page 58: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

11 M301 AB5

Page 59: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

12 M301 AB5

Information Technology and Computing: Level 3 M301 Software Systems and their Development

ARAB OPEN UNIVERSITY

Faculty of Computer Studies

M301

Assignment Booklet 5

Contents

TMA M301 2005/2006 Cut-off date: 20 May 2006

Enter your solutions to this Tutor Marked Assignment (TMA) into a single word-processed document known as the Solution Document. The Solution Document (clearly headed with your name, the number of the TMA as given above, and your personal identifier) should contain all text, diagrams and screen dumps requested in the questions. You are not expected to submit additional files containing Java code unless you are asked to do so.

Please submit your solution to this TMA to the electronic TMAs (e-TMAs) system on or before the cut-off date shown above in the form of a zip archive file containing the Solution Document. You will find details on how to create a zip archive file in the Guide to Electronic Tuition. You will find details on how to submit a zip archive file to the e-TMA system in Using the Electronic TMAs System — A Student Guide to e-TMAs.

You do NOT have to submit a PT3 form when submitting electronic TMAs.

The marks allocated to each part of each question are indicated in brackets in the margin.

Note that, in answering the questions in this TMA, more is expected than simply reproducing passages from the course materials. In those instances where you feel it is essential to use extracts from these materials, you must indicate their source. To do otherwise is plagiarism.

To avoid the difficulties that will arise if you inadvertently lose the contents of your Solution Document, we recommend that you add it to the zip archive file (overwriting any previous copy) each time you complete a question.

Page 60: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

M301AB6

TMA M301 05 20 May 2006 Important Please ensure that your Solution Document is readable in Word . If you are in any doubt, try reading your document using WordViewer before submitting it to the e-TMAs system.

To avoid sending over-large files through the e-TMA system (something that can cause problems to those marking your assignment) please:

• avoid sending an RTF document;

• do not copy screen shots (i.e. shots of the whole screen) into your Solution Document. Only window shots will ever be required (e.g. an output window, or an interface window) as a solution to a question. To copy a window, select the window so that it is highlighted and press the Alt-PrintScreen keys together. This will copy the window onto the clipboard. It can then be pasted into your Solution Document using the Edit menu or shortcut key, Ctrl V.

It would be tremendously helpful if, in your Solution Document, you would explicitly state if you have not answered a question or part of a question. This should avoid your tutor having to contact you should a solution (or part of one) appear to be missing from your Solution Document.

Many questions in this TMA refer to the M301 Case Study. You may wish to refamiliarize yourself with the relevant sections of the case study before attempting each question.

Question 1 [20 marks] This question is based on Unit 5.1 and Sections 1 and 16 of the Case Study.

(i) In the Case Study, Design by Contract has been a prescribed approach on major FinSys projects for many years. When specifying the high-level design of the Home Banking System for National Suburban Bank, the FinSys architect decides to interpose an intermediate tier of processing between the BankClient and the BankServer called a transaction monitor, which synchronizes access to the BankAccount objects held by the BankServer. The withdraw operation would be handled as follows.

BankClient int desiredAmount; int status; Transaction t;

status = t.withdraw (desiredAmount) // status = 0 ⇒ successful withdrawal; status = 1 ⇒ insufficient money in Account

Transaction BankAccount acct; int status; public int withdraw (int anAmount) pre { anAmount > 0} post { ((status == 0 && anAmount <= acct.getBalance () + acct.getOverdraftLimit ()) || (status == 1 && anAmount > acct.getBalance () + acct.getOverdraftLimit ())) && // ‘return’ is set to status }

BankAccount public int getBalance () { post { //’return’ is set to the current balance for this account} } public int getOverdraftLimit () { post { //’return’ is set to the overdraft limit for this account } }

public void debit (int sameAmount) { pre { sameAmount <= getBalance () + getOverdraftLimit ()}

Page 61: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

M301AB6

post { getBalance () = getBalance () @ pre – sameAmount }

invariant { getOverdraftLimit () >= 0 && getBalance () + getOverdraftLimit () >= 0; }

}

Give two or more reasons that this design approach is appropriate for distributed software systems such as the Home Banking System. [6 marks]

(ii) Read Sections 16.1 and 16.2 of the Case Study. Taking into account both the stated need for the system to be highly reliable and also the developers’ expressed recommendation, use Rational Rose, or any other modelling tool that conforms to the UML, to draw component and deployment diagrams depicting the nodes and components of the four distributed server components of the Home Banking System. [8 marks]

(iii) To answer the following questions, you will first need to complete Practical Activity 11.1 in the Modelling Tool Handbook.

(a) Following the instructions in the practical activity, use the Rational Rose, or any other modelling tool that conforms to the UML and can recover a model from Java code, to reverse engineer a UML class diagram from the BankClientFrame.java source code that may be found on CD1 in the directory: JavaProjects\CaseStudy\CaseStudyPart\BankClient\src

Paste your class diagram into your solution document. [3 marks]

(b) Explain why only one attribute should be shown in your class diagram, whilst other attributes of the class appear as roles. [3 marks]

On completion of this question, add your Solution Document to the TMA05 zip archive file.

Page 62: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

M301AB6

Question 2 [20 marks] This question is based on Unit 5.2 and Section 8 of the Case Study.

(i) For a project that uses Java as its main programming language and that has based its software development approach on Component Based Development (CBD), what is the relationship between

(a) a component and a class?

(b) a pattern and a framework? [5 marks]

(ii) Look at the design of the Proxy Server and Queue Server in Figure 3, Section 8 of the Case Study. Describe the common elements that you believe might be a candidate for a reusable component. Describe why this component could or could not be a JavaBean or Enterprise JavaBean. [5 marks]

(iii) Considering the Case Study as a whole, which style best characterizes the architecture of the Home Banking System? Justify your decisions. [5 marks]

(iv) In section 15.2, Budd describes the Composite pattern in the form of a tree and provides as an example the relationships between the Container and Component classes in the Java library with the Layout class as a “leaf” of the tree. Draw the UML class diagram that illustrates the relationships between 3 classes, Container, Component and Layout. Briefly describe the Composite pattern under the headings of Motivation, Applicability or context, Problem and Solution. [5 marks]

On completion of this question, add your Solution Document to the TMA05 zip archive file.

Page 63: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

M301AB6

Question 3 [20 marks] This question is based on Unit 5.3 and on the BankingServerThread.java file on Course CD2.

(i) Explain the similarities and differences between verification, validation and testing. Would you characterize the development of an acceptance test specification as verification, validation or testing? [5 marks]

(ii) On Course CD2 you will find some of the Java source files for the Case Study. The source for the proxy server may be found in \CaseStudy \CaseStudy31\CaseStudy31Part\BankingServer\src Calculate the cyclomatic complexity of the run method in the BankingServerThread class in the file BankingServerThread.java. Also calculate the cyclomatic complexity of the run method in the BankingServiceThread (in the file BankingServiceThread.java) and in both cases show your calculations. [5 marks]

(iii) Consider the specification of an operation to calculate the average of a sequence of at most 100 positive whole numbers that lie between two bounding constant values minimumValid and maximumValid. The sequence is terminated by any negative number, typically –1. Using the techniques of Equivalence Partitioning and Boundary Value Analysis, draw up the minimum set of black-box test cases that fully exercises this operation.

The following Java method purports to implement this operation: public static final int minimumValid = 1; public static final int maximumValid = 990; public float mean (int[ ] iarray){ int runningTotal=0; int countInput=0; int countValid=0; while (iarray[countInput] > -1 && countInput < 100) { if (iarray[countInput] > minimumValid-1 && iarray[countInput] < maximumValid) { runningTotal += iarray[countInput]; countValid++; } countInput++; }; return runningTotal/countValid; }

Apply the black-box test cases you developed to this method to identify as many errors in the code as possible. There are at least 4 errors; you will receive full marks for identifying 2 of them. [5 marks]

(iv) During requirements elicitation for the Home Banking System, National Suburban Bank expressed the requirement that the system performance should degrade gracefully as usage approached the limits of the system, and that users receive a warning if responses are expected to be slow (as opposed to the system appearing merely to ‘hang’). How could you test that this requirement had been met and what problems do you foresee in completing these tests? [5 marks]

On completion of this question, add your Solution Document to the TMA05 zip archive file.

Page 64: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

M301AB6

Question 4 [20 marks] This question is based on Unit 5.4 and Sections 11 and 12 of the Case Study.

(i) Using the partially completed use case diagram in Figure 1, Section 11 and the class diagram in Figure 3, Section 12 of the Case Study, perform a function point analysis and estimate the number of KLOCs for the system. Assume a mean WU value of 5 for each use case and a mean WC value of 10 for each class. Show your intermediate calculations including the values you assign for each of the 14 complexity adjustment factors, giving your reasons for each factor. Using COCOMO parameters for a semi-detached software type, calculate the estimated effort and optimal duration of the development project, ignoring effort multipliers. [12 marks]

(ii) An independent study was conducted to assess the current practices of a particular software development organization. It highlighted points such as the project team is untrained and unqualified, the development process is undefined and random, product quality is not measured and the overall success of the products depends on a few ‘heroes’ within the organization. In conclusion, the study has characterized the organization as immature with respect to developing software.

What level of the CMM is this department at now? What would have to change and over what period of time would the organization need to move to higher levels of the CMM? Discuss policy changes, documents, and the people who must carry out these implementations. [8 marks]

On completion of this question, add your Solution Document to the TMA05 zip archive file.

Page 65: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

M301AB6

Question 5 [20 marks] This question is primarily based on Unit 5.5

(i) Page 14 of the Unit outlines 8 widgets that may be used by the user to control a graphical application. For each widget, identify the corresponding object class from the Swing library that the developer of an application written in Java would use and indicate briefly how the widget would be used. [8 marks]

(ii) Consider a user interface for a microwave oven. The microwave has a keypad layout similar to a telephone, with a key for each digit 0 to 9 inclusive. The sequence of keys SECS, 2, 3, ENTER sets a cooking time of 23 seconds.

0 0 0 0

1 2 3

4 5 6

0

87 9ENTER SECS

Assume the keystroking time is the same for any key. Discuss why the time to perform each of the following sequences might be different.

(a) SECS, 1, 0, ENTER

(b) SECS, 2, 2, ENTER [3 marks]

(iii) The view is sometimes expressed that the software tools which software developers themselves use to design, build and test major software systems are difficult to learn and use. Evaluate the usability of two CASE (Computer Aided Software Engineering) tools with which you may be familiar e.g. Borland’s JBuilder IDE and the Rational Rose modelling tool which you may have used in your studies of this course. [3 marks]

(iv) Process-related human factors may have a significant bearing on the productivity of a software development organization. Select the 5 factors you believe exhibit the greatest variation across projects, briefly justifying your choice. By estimating the variation of each individual factor between its optimum and reasonably worst case, compare the relative performance of the best performing project team in the best possible circumstances with the worst performing team in the most difficult of circumstances. [6 marks]

Page 66: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

M301AB6

On completion of this question, add your Solution Document to the TMA05 zip archive file. This should complete your work on the TMA. Your zip archive should contain just one file.

You should now submit your completed TMA05 zip archive file to the e-TMAs system on or before the cut-off date.

Page 67: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

M301AB6

Information Technology and Computing: Level 3 M301 Software Systems and their Development

ARAB OPEN UNIVERSITY

Faculty of Computer Studies

M301

Assignment Booklet 6 Contents Cut-off date

TMA M301 2005/2006 10 June 2006

Enter your solutions to this TMA into a single word-processed document known as the Solution Document. The Solution Document (clearly headed with your name, the number of the TMA as given above, and your personal identifier) should contain all text, diagrams and screen dumps requested in the questions. You are not expected to submit additional files containing Java code or UML diagrams unless unless you are unable to copy diagrams from a CASE tool to your Solution Document.

Please submit your solution to this TMA to the electronic TMAs system on or before the cut-off date shown above in the form of a zip archive file containing the Solution Document. You will find details on how to create a zip archive file in the Guide to Electronic Tuition. You will find details on how to submit a zip archive file to the e-TMA system in Using the Electronic TMAs System — A Student Guide to e-TMAs.

You do NOT have to submit a PT3 form when submitting electronic TMAs.

The marks allocated to each part of each question are indicated in brackets in the margin.

Note that, in answering the questions in this TMA, more is expected than simply reproducing passages from the course materials. In those instances where you feel it is essential to use extracts from these materials, you must indicate their source. To do otherwise is plagiarism.

To avoid the difficulties that will arise if you inadvertently lose the contents of your Solution Document, we recommend that you add it to the zip archive file (overwriting any previous copy) each time you complete a question.

Page 68: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

M301AB6

TMA M301 06 Cut-off date: 10 June 2006

Important Enter your solutions to this TMA into a Solution Document. This document must be readable in Word. If you are in any doubt, try reading your document using WordViewer before submitting it to the e-TMAs system.

To avoid sending over-large files through the e-TMA system (something that can cause problems to those marking your assignment) please:

• avoid sending an RTF document;

• do not copy dumps of the whole screen into your Solution Document. Only dumps of individual windows will ever be required (e.g. an output window, or an interface window). To copy a window, select the window so that it is highlighted and press the Alt-PrintScrn keys together. This will copy the window onto the clipboard. It can then be pasted into your Solution Document using the Edit menu or shortcut key, Ctrl-V.

It would be very helpful if, in your Solution Document, you would explicitly state if you have not answered a question or part of a question. This should avoid your tutor having to contact you should a solution (or part of one) appear to be missing from your Solution Document.

Question 1 [20 marks] This question is based on the material in Unit 6.1

(i) (a) Describe the differences between secret key cryptography and public key cryptography. [2 marks]

(b) Justify the statement, ‘Exchange of keys is a much more complex matter with secret key cryptography than with public key cryptography.’ [2 marks]

(c) Explain how a secure order form can be sent safely via the Internet. [4 marks]

(ii) (a) Explain the process of obtaining a class 1 digital certificate for individual use in e-mail using a browser such as Internet Explorer. Your answer should include reference to the generation of the public and private keys and how these are handled. [4 marks]

(b) When an e-mail has been digitally signed, explain how the recipient can be sure of the identity of the sender (authentication) and that the message has not been modified en route (message integrity). [4 marks]

(iii) (a) Explain what is meant by the expression ‘a Java applet runs in a Sandbox which severely limits what that applet can do’. [2 marks]

(b) How can the limitation mentioned in part (a) be overcome? [2 marks]

When you have completed this question, add your Solution Document to the TMA06 zip archive file.

Page 69: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

M301AB6

Question 2 [20 marks] This question is about human factors and professional issues studied in Unit 5.5 and 6.2. You are asked to apply your knowledge and understanding from there to the following hypothetical situation that might have arisen during the development of a software system. A reservation system for the Cheapo Lorry Rental Company is being developed under contract with a software development company, OSS. During the implementation of the reservation system, Edward, a very experienced software developer who had been leading the Cheapo reservation project, left OSS very abruptly to look after his ailing mother without serving out his notice (for several months he had been travelling considerable distances to visit her on a daily basis). This left the company in severe difficulty, because they had to assign another person, Aysha, to the project. Aysha had only obtained her university degree in Computing a couple of years before, and she took several weeks to familiarise herself with the problem being tackled, the work done so far and the particular development tools being used (with which she was not previously familiar). Edward had developed many reservation systems before, this was the second such system he had tackled this year, and his manager, Sam, had said that “Edward could write these systems in his sleep” so the very tight timescales for the delivery of the system had taken this into account. By contrast Aysha had never developed any systems like this before; her only previous experience had been in real-time embedded systems and she had recently joined the company in order to build up that new side to the business. She protested on several occasions about her unsuitability, and the lack of time to become thoroughly familiar with the development tools, but her protests were overridden with Sam telling her “Do your best” and “If you work on them in the evening, I’ll see whether I can get you a couple of extra days leave later in the year.”

The combination of Edward’s abrupt departure and Aysha’s inexperience in systems of this kind led to the project being two months late in its delivery, and the client invoked a penalty clause which meant, effectively, that the company lost money on the project. The Managing Director of OSS was very angry about this, especially since Edward was highly paid and had been a member of a leading professional society, and because he had taken with him the frameworks that he had developed on his way to implementing the Cheapo reservation system. The Managing Director asked his Human Resources Manager to prepare a confidential report on the incident and about Edward’s actions which he could hold in secret in his own office and use if appropriate.

Answer the following questions about the above scenario. Confine your answers to the information given above. Do not make further assumptions about the situation.

(i) Aysha is less productive that Edward; she delivered the system late whereas Edward might well not have done so. Referring to those human factors associated with the software development process, explain why this variation might have been expected. In your answer, discuss whether or not Edward would have produced the system on time. [4 marks]

(ii) What legal issues are raised by this situation? [4 marks]

(iii) Had any of Edward, Aysha, Sam and the MD behaved unethically in this situation? Determine what the next course of action should be by following the 8-step procedure given in Unit 6.2. [8 marks]

(iv) “Claiming to be competent in a specific area … when in fact you have never set eyes on such equipment and don’t know the first thing about it, may not be illegal, but is it certainly unethical … or is it?” (Unit 6.2 p.6)

In your judgement, is making a false claim of competence ethical or unethical?

Page 70: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

M301AB6

What are the professional implications of making such a claim? When answering this question, you may wish to refer to the BCS Code of Conduct downloaded with this TMA.

Under what circumstances may such a claim be illegal? [4 marks]

When you have completed this question, add your Solution Document to the TMA06 zip archive file.

Page 71: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

M301AB6

Question 3 [30 marks] This question is designed to introduce you to a modern approach to testing. In recent years, a testing framework known as JUnit has become a popular tool for testing Java programs. Question 3 asks you to download a copy of the JUnit tool and work through an example to familiarise yourself with the tool and an approach to unit and regression testing known as test-led design. The question is based on the document entitled Testing with JUnit (downloaded as part of this TMA). When you downloaded this TMA from the M301 web site you will also have downloaded:

• junit.jar – a copy of the JUnit testing tool

• JUnitInstall.doc – a Word file containing instructions on how to install JUnit so that it works with JBuilder. Note that if you are using a development environment other than JBuilder, the principles are the same.

• Testing.doc – a Word document containing a worked example of the use of JUnit and entitled Testing with JUnit.

• TMA06Q3Software – a folder containing software for use with this question.

(i) Carry out the following steps:

(1) Install JUnit by following the instructions in the section Installing JUnit in the document JUnitInstall.doc.

(2) Read Testing with JUnit.

(3) If you are using JBuilder, create a new project named TMA6Q3.jpr, and store it in C:\JavaProjects\TMA06Q3. Set the project’s properties to use the library JUnit as described in the section Using JUnit with a JBuilder Project in the document JUnitInstall.doc. If you are not using JBuilder, the approach will still be very similar; consult www.junit.org for guidance on configuring JUnit to work with your Java Development Environment.

(4) Add three new classes named DocumentInterface, DocumentTest and Document as listed in Figures 1, 3 and 4 of Testing with JUnit. Copies of these classes can be found in the folder TMA06Q3Software downloaded with this TMA.

Add the following println statement as the first statement of the method equals in the Document class:

System.out.println("Running equals");

(5) Run JUnit as described in the section Running JUnit in the document JUnitInstall.doc and reproduce Figures 6 and 8 of Testing with JUnit. You will need to replace the downloaded version of the equals() method (in Document.java) with that shown in Figure 7 of Testing with JUnit in order to reproduce Figure 8.

Add the following to your Solution Document:

(a) copies of the two JUnit windows produced in step (5); [4 marks]

(b) a copy of the message window containing the message(s) "Running equals" produced when you ran the successful JUnit test. [6 marks]

Page 72: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

M301AB6

(ii) The test testInsert given in the document Testing with JUnit should fail because the Document method insert() has not been implemented. Carry out the following steps:

(1) Add testInsert() (see Figure 10 of Testing with JUnit) to the class DocumentTest.

(2) Add the following println statement as the first statement of the method insert() in the Document class:

System.out.println("Running insert");

(3) Edit the class DocumentTest so that it utilizes setUp() as shown in Figure 11 of Testing with JUnit.

(4) Implement insert() – you may find it helpful to use the String method substring() as described at the end of this question.

(5) Use JUnit to test your implementation of insert().

Add the following to your Solution Document:

(a) a listing of your method insert(); [4 marks]

(b) a copy of the message window showing all the output from JUnit when testing insert(). [4 marks]

(iii) Devise a test named testDelete for the Document method delete() and implement delete().

The method delete() removes a specified number of characters from a document’s string, and returns the deleted string. The method has two arguments: the first is the index position in the document’s string of the first character to be deleted and the second specifies the number of characters to be deleted.

The test testDelete should include:

2 tests of the delete() method alone (to show that the method correctly deletes a number of characters from a non-empty document and that the method correctly returns the deleted string), and

2 tests for interaction between the insert() and delete() methods.

Add the following to your Solution Document:

(a) a description, in English, of your proposed tests (follow the descriptive style used in Figure 9 of Testing with JUnit); [4 marks]

(b) a listing of the testDelete() method that runs the tests you described in part (a) suitable for inclusion in DocumentTest; [4 marks]

(c) a listing of your implementation of the method delete(). [4 marks]

When you have completed this question, add your Solution Document to the TMA06 zip archive file.

Obtaining substrings from a Java String A String object in Java can be viewed as an array of characters indexed from 0 upwards. The number of characters in a string is given by the String method length(). A substring (a portion of a string) can be specified using the String method substring() that has two arguments: the index of the first character of the substring followed by the index of the last character in the substring plus 1. Hence, given a string s initialised as follows,

Page 73: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

M301AB6

s = "This is my favourite example";

the substring "is my" can be obtained by writing,

s.substring(5, 10);

The substring "example" can be obtained by writing,

s.substring(21, s.length())

Page 74: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

M301AB6

Question 4 [30 marks] This question is based on the material in the Case Study. The bank in the case study has a new requirement. It wants to offer its home banking customers the facility to change their minds having submitted a request. For example, if a customer has requested the bank to set up a new standing order, the customer should be able to cancel that request within a reasonable period of time.

The idea is to provide a new button on the BankClient window labelled ‘UNDO’ which, when clicked, undoes the last request. Precisely what ‘undoing’ a specific request means will not be a concern at this point in time as the bank wants a prototype built to see how the facility might work.

One of your colleagues at FinSys has already done some analysis of the problem and has a suggestion for the design which you are to follow through. The suggestion is based on the Command Processor Pattern which is an extension to the Command Pattern (see Section 4 of the Case Study). The UNDO button should be treated in a similar way to all the other buttons: clicking on the UNDO button should give rise to a new object of the class UndoRequest, a subclass of Request.

The main functionality of the undo facility should be provided by an object of a new class named RequestManager. RequestManager will have an execute() method which is invoked in place of any call to the execute() methods of an individual request. So, for example, in the actionPerformed method of the BalanceButtonListener, there is a call:

req.execute(arg);

which should be replaced by

requestManager.execute (req, arg);

Similarly for the other listeners.

The RequestManager object (which you will have to create in the BankClientFrame) will examine the request and, if it is an UndoRequest will cause the appropriate undo action to take place, otherwise it will cause the normal request to be carried out.

Whenever the RequestManager object causes a request to be carried out, it should also add the request to a list of requests (a Vector, named historyList, would be a useful container to use) so that, when an undo request occurs, the RequestManager can find out what the last request was. If each individual Request object (such as an object from BalanceRequest) is provided with an additional method named undo(), the RequestManager simply invokes this method on the last request that was added to historyList. Once a request has been undone, it should be removed from the historyList vector. An UndoRequest object is never added to historyList.

Your task is to implement the undo facility. The task has been broken down into stages to help you build up the functionality in small increments. You should use the version CaseStudy31Part which you will find on the CourseSoftware CD or you can download it from the Case Study, Part 6, page of the M301 Web site.

(i) Here is a listing of the BalanceButtonListener which is executed whenever a user requests their balance.

private class BalanceButtonListener implements ActionListener { public void actionPerformed (ActionEvent ea) { if (loginAllowed){ Request req = new BalanceRequest (br, pw); String arg = "B*"+accountIdentity.getText () + "*"; req.execute (arg); details.setText (req.getResponse ()); messages.setText (req.getMessage ()); } else // User has not logged in yet messages.setText ("Not logged in\n"); }

Page 75: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

M301AB6

}

Describe the actions that take place when the BalanceButtonListener’s actionPerformed method is executed assuming that loginAllowed is true. That is, describe, in two or three sentences each, what each of the five statements following if (loginAllowed) achieves. Note, it would not be sufficient in, for example, req.execute(arg), to state that the method execute() is invoked on the object req. Your answer must show that you know what the object req represents, what the execute() method does and what the argument arg represents. [5 marks]

(ii) Add a button labelled ‘UNDO’ to the Bank Client interface (BankClientFrame.java). When clicked this button should output a message "Undo button clicked".

Submit a copy of the BankClient window showing the UNDO button and the message that results after clicking the UNDO button. This can be done without having to run the other components of the banking system. [3 marks]

(iii) (1) Add an undo() method to each individual concrete Request as follows. In the abstract class Request, add the following method heading:

public abstract void undo(); Then, add the following method to each of the classes

BalanceRequest, TransactionsRequest, LoginRequest, ExitRequest:

public void undo() { message = "Cannot undo *** request"; }

where *** should be replaced by the name of the request (Balance, Transactions, Login or Exit as appropriate).

Add the following method to the class SORequest: public void undo() { message = "Cancelling a Standing Order request"; }

(2) Add a new class named RequestManager to your BankClient project. A copy of a suitable RequestManager class will have been downloaded with this TMA. Here is a listing of that class.

import java.util.Vector; class RequestManager { public void execute(Request req, String args) { if (req instanceof UndoRequest) { undo(req); } else { req.execute(args)) addToHistoryList(req); } } public void undo(Request req) { System.out.println("Undoing request " + req.toString()); } private void addToHistoryList(Request request) { System.out.println("Adding " + req.toString() + “ to history”); } }

Page 76: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

M301AB6

(3) Add a new class named UndoRequest to your BankClient project. A

suitable version will have been downloaded with this TMA. Here is a listing of that class: import java.io.*; public class UndoRequest extends Request { BufferedReader reader; PrintWriter writer; public UndoRequest (BufferedReader bf, PrintWriter pw) { reader = bf; writer = pw; } public void execute (String args) { message = "Undoing a request"; } public void undo () { message = "Cannot undo an Undo request"; } }

(4) Amend each action listener’s actionPerformed method (they can all be found in BankClientFrame) by replacing the statement req.execute (arg);

by requestManager.execute(req, arg);

Include the following data field declaration in BankClientFrame RequestManager requestManager = new RequestManager();

(5) Complete the implementation of the actionPerformed method of the class undoButtonListener so that it behaves in the same way as all other action listeners. However, as the Bank Server is not aware of the new undo request, no useful information is returned. Therefore, amend this actionPerformed method to display a message in the messages pane:

messages.setText ("Request undone");

The message to be sent to the Queue Server should be: "U*"+accountIdentity.getText () + "*";

(6) Run all components of the banking system (run your revised version of BankClient last).

Add the following to your Solution Document:

(a) A listing of your completed undoButtonListener class. (b) A copy of the message window after performing the following

sequence of actions:

Page 77: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

M301AB6

Login using the Id & password 009877 Click the Balance button Click the Transactions button. Click the Undo button. Click the Undo button. Click the Balance button.

[5 marks]

(iv) Complete the implementation of RequestManager so that it contains a Vector named historyList to which each new request is added. Arrange matters so that a maximum of 3 requests only may be stored in the vector and, if the vector is full, a new request is added after the earliest request has been deleted. Both the execute() and the undo() methods of RequestManager must be amended.

The undo() method should have the following structure (which will enable messages to be displayed on the Bank Client window):

public void undo(Request req) { System.out.println("Undoing request " + req.toString()); if (historyList.size() > 0) { /* ***Add additional code here*** Request previousRequest = … … */ req.message = previousRequest.getMessage(); req.response = previousRequest.getResponse(); } else { req.message = "Nothing to undo"; } } [8 marks]

(v) (a) Draw a class diagram showing the associations between the following classes in your revised Bank Client project: BankClientFrame, BalanceRequest, ExitRequest, LoginRequest, Request, RequestManager, SORequest, TransactionsRequest and UndoRequest. You may use Rational Rose, or any other modelling tool that conforms to the UML, or just drawing in Word. Do not show data fields or methods in each class, and do not put multiplicities on the associations.

(b) Using Rational Rose, or any other modelling tool that conforms to the UML, or just drawing in Word, draw two sequence diagrams. The first should show the sequence of messages that start with the BankClientFrame executing a BalanceRequest normally. The last message shown should be to a PrintWriter object that communicates with the Queue Server. Use the following layout.

Page 78: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

M301AB6

:BankClientFrame

:RequestManager

:BalanceRequest

:PrintWriter

The second sequence diagram should show the sequence of messages that

start with the BankClientFrame undoing the previous Request which you should assume was a BalanceRequest. Use the following layout.

:BankClientFrame

:RequestManager

:UndoRequest

historyList : Vector

: BalanceRequest

Add the class diagram and 2 sequence diagrams to your Solution

Document. [9 marks]

When you have completed this question, add your Solution Document to TMA06 zip archive file for this TMA.

This should complete your work on this TMA, and your zip archive file should contain a single Solution Document.

You should now submit your completed zip archive file to the electronic TMAs system on or before the cut-off date.

Page 79: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Appendix: Running the Case Study software 1 Copy the contents of the folder named CaseStudy from Course Software

Disk 1 to a new directory named CaseStudy at the top level of your C: drive. (Files copied from the CD-ROM may appear on the hard disk as read only. The attribute must be reset before JBuilder can modify the source files. Use Windows Explorer to do this.) In the subdirectory of CaseStudy named CaseStudy31 you will find two directories:

CaseStudy31Full (the compiled .class files for the operational Case Study);

CaseStudy31Part (the .java source files for a partially complete implementation).

CaseStudy31 consists of six client–server components. A seventh component named BranchOperations can be found in the subdirectory CaseStudyBranchOps. The seven components are linked as shown in Figure 1.

BankClient

QueueServer

ProxyServer

NamingServer

BankingServer

Dat aBaseServer

BranchOperat ions

Figure 1 Client–server components of the Case Study

For this exercise, you should use the contents of the directories named CaseStudy31Part (there are two such directories, one contained in CaseStudy31 and one in CaseStudyBranchOps).

You should also find that the NamingServer directory contains the project file NamingService.jpr and three text files named accountFile, bankFile and portFile. It is essential that these text files are present and in the same folder as the NamingService.jpr project file.

2 Launch the IDE.

3 Run the Case Study implementation as follows.

Open the project file DataBaseServer.jpr (it will be in the directory named DataBaseServer contained in the directory:

CaseStudy\CaseStudy31\CaseStudy31Part\DataBaseServer

downloaded in step (1)). That is, in the IDE, click on File, then Open, then OpenFile… and finally select the project file DataBaseServer.jpr from the Open File window.

M301AB6

Page 80: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

4 Build the project (right-click on the project name and select Rebuild).

5 Run the project (click on the Run menu and select Run project).

6 Click on the Start button on the DataBaseServer window that appears.

7 Run the server components BankingServer, NamingServer, ProxyServer and QueueServer in the same way (but do not launch the IDE again).

Run the project BankingServer four times each time selecting a different port number before clicking on the Start button. If you do not run the BankingServer four times with different port numbers, you will find that you cannot access some of the accounts because the BankingServer representing the branch at which the accounts are kept is not running.

Then, run the BankClient (it will not work correctly unless the QueueServer component is already running).

8 Log in to the BankClient by typing 009877 for both the Account Identity and the Password, and then click on the button labelled Login. Click on the Balance button to obtain the current value of the balance of this account.

9 Determine the standing order(s) that exist for this account by clicking on the appropriate button.

10 Without closing any of the running components, open the BankOperation project — it can be found in the directory:

C:\CaseStudy\CaseStudyBranchOps\CaseStudy31Part\BranchOperation

Build and then run the BranchOperation project (it will not work unless the BankingServer is already running). Select the Milton Keynes branch and then click on the Start button.

The BranchOperation component will execute a variety of operations on the accounts kept at the selected branch. In particular, it will execute the standing orders, if any, for each account. Read Section 9.6 of the Case Study, ‘Regular updating jobs’ for more information.

11. Click on the Daily button.

In the BankClient window, click on the Balance button. The balance should have been reduced by the amount of the standing order.

12 Exit from all Case Study projects unless you are proceeding to work on the assignment straight away.

M301AB6

Page 81: M301 TMA01,TMA02,TMA03 TMA04,TMA05,TMA06

Appendix: Putting diagrams from the Rational Rose modelling tool into a Word document This section is included to help you prepare a single file for submission to your tutor. The following instructions apply to users of Microsoft Word software. We do not guarantee that the procedure will apply to other word processing software. To place a diagram from the modelling tool at a particular point in your Word document, follow the steps below.

9. Place the cursor at the point in your document where you want to locate the UML diagram.

10. Switch to the modelling tool. For example, click on the button labelled Rational Rose - yourModelName in the task bar to open its application window.

11. In the modelling tool, open the diagram that you want to copy and paste into your assignment. For example, it may be a use case diagram or state diagram.

12. In your chosen diagram, select all the elements you want to copy. For instance, you can select all the elements of a diagram by using Control-A or Select All from the Edit menu. Then copy them onto the clipboard by using Control-C or Copy from the Edit menu.

13. Switch back to the picture in your document. For example, click on the button labelled Microsoft Word - yourDocumentName in the task bar to open your assignment.

14. Paste the UML diagram into your assignment at the point chosen in step 1 by using either Control-V or Paste after a right click.

15. Right click on the diagram and select Format picture. Select the Position tab. Remove the tick from the checkbox labelled float over text and click . OK

16. Adjust the size of the UML diagram in your assignment by using your mouse. If you cannot copy diagrams from Rational Rose to your word processor, save your complete model (as a .mdl file) and then add it to your zip file for this assignment.

M301AB6