File Handler program

111
Cover page has been removed for security reasons

description

University report documenting a Java program designed t

Transcript of File Handler program

Page 1: File Handler program

Cover page has been removed for security reasons

Page 2: File Handler program

- 2 -

CONTENTS

1. Introduction To The Problem ................................................................................................................ - 4 -

2. Explanation Of Process .......................................................................................................................... - 5 -

3. Section One ........................................................................................................................................... - 7 -

3.1 Features List ..................................................................................................................................... - 8 -

3.2 Context Diagram .............................................................................................................................. - 9 -

3.3 Use Case Diagram .......................................................................................................................... - 10 -

3.4 Requirements Specification Document ........................................................................................... - 12 -

3.5 Class, Responsibilities And Collaborators ........................................................................................ - 13 -

3.6 Class Diagrams ............................................................................................................................... - 15 -

3.7 Hierarchical Task Analysis ............................................................................................................... - 17 -

3.8 Pseudocode – Level One ................................................................................................................ - 18 -

3.9 Pseudocode Level Two ................................................................................................................... - 19 -

3.10 Pseudocode – Level Three ............................................................................................................ - 21 -

3.11 Commented Code Listing ............................................................................................................. - 23 -

3.12 Testing (Software Validation) ....................................................................................................... - 27 -

3.13 Component Testing .................................................................................................................. - 28 -

3.14 Black Box Testing ...................................................................................................................... - 29 -

3.15 Design (Stage 2) ........................................................................................................................... - 34 -

3.16 Acceptance Testing .................................................................................................................. - 36 -

3.17 White Box Testing .................................................................................................................... - 37 -

4. Section Two ......................................................................................................................................... - 39 -

4.1 Features List ................................................................................................................................... - 40 -

4.2 Context Diagram ............................................................................................................................ - 42 -

4.3 Use Case Diagram .......................................................................................................................... - 43 -

4.4 Requirements Specification Document ........................................................................................... - 45 -

4.5 Class, Responsibilities And Collaborators ........................................................................................ - 46 -

4.6 Class Diagrams ............................................................................................................................... - 48 -

4.7 Hierarchical Task Analysis ............................................................................................................... - 51 -

4.8 Graphical User Interface Designs .................................................................................................... - 52 -

4.9 Pseudocode – Level One ................................................................................................................ - 58 -

Page 3: File Handler program

- 3 -

4.10 Pseudocode – Level Two .............................................................................................................. - 61 -

4.11 Possible Problems And Solutions .................................................................................................. - 64 -

4.12 Commented Code Listing ............................................................................................................. - 65 -

4.13 Testing (Software Validation) ....................................................................................................... - 84 -

4.14 Filehandler Component Test..................................................................................................... - 85 -

4.15 Defect Testing / Debugging .......................................................................................................... - 88 -

4.16 Acceptance Testing .................................................................................................................. - 90 -

5. Section Three ...................................................................................................................................... - 91 -

5.1 System testing ............................................................................................................................ - 92 -

6. Reflection .......................................................................................................................................... - 106 -

7. Glossary ............................................................................................................................................ - 107 -

8. Bibliography ...................................................................................................................................... - 108 -

9. Appendix ........................................................................................................................................... - 110 -

Page 4: File Handler program

- 4 -

1. INTRODUCTION TO THE PROBLEM

PROBLEM STATEMENT

Design an application that reads a specific file / set of files. Once read they should be displayed.

REQUIREMENTS

R1. Design problem: design an application that reads a specific file, once read the file should be

displayed.

R2. Plan the design phase and develop implementation of design.

R3. Test implementation.

R4. Design problem: design an application that reads a sequence (set) of files, once read the files

should be displayed.

R5. Plan the design phase and develop implementation of design

R6. Test implementation

R7. Reflection

Page 5: File Handler program

- 5 -

2. EXPLANATION OF PROCESS

INTRODUCTION

The Waterfall model, developed in the 1970’s, can be defined as having ‘distinct stages’ – namely requirements specification, software design, implementation and testing – whereby each stage is completed before the next one commences. The major disadvantage to this approach is due to its “inflexible partitioning” (Sommerville, 2007), meaning that commitments must be made early on in the development. Therefore, if requirements are likely to change during the course of the project, then the Waterfall model may not be the best approach. In 2000, a study of failure factors in IT projects in the UK showed that ‘scope management’1

A more flexible approach is evolutionary development, in which initial solutions are developed and shown to the user of the system, then “refining it through many versions until an adequate system has been developed” (Sommerville, 2007). Another way of defining it is that it encompasses “quickly evolving towards stakeholder values and product qualities, while learning through early feedback” (FIRM, 2005). This implies that a higher quality of system will be produced as the requirements can be amended easily; therefore more time can be spent on the overall design and functionality of the system.

related to using the Waterfall model was the largest problem in 82% of all projects (Taylor, 2000).

It can be argued that evolutionary development will be the most efficient approach to solve the problems proposed in this report. Although requirements are not likely to change radically as there are no end-users, requirements still can change as new techniques are discovered. Evolutionary development allows for new ideas to develop and be implemented which, although they may not be a key requirement, add to the overall usability and efficiency of the system. In addition to this, the problem seems to lend itself to evolutionary development. This is because requirements 1-3 can be implemented primarily and requirements 4-6 can be seen as the evolution of the software, and will refine the system to produce an adequate solution to the problem. The stages of evolutionary development are displayed in Figure 1. Sommerville suggests that there are two types of evolutionary development; exploratory development and throwaway prototyping. Exploratory development involves the system being designed using the requirements which are known, and then expanding and evolving this by adding new features. Throwaway prototyping involves developing different types of system to better understand the requirements. This is done by showing prototypes2

to the user and evaluating the response. With regard to this, it is suggested that exploratory development would be more effective for use in this project. This is due to the idea that throwaway prototypes are often time-consuming and concentrate on further understanding the requirements. The requirements are clear in this project but there is room for expansion, so exploratory development is the most appropriate tool to utilise.

1 Scope Management: the processes required to ensure that the project includes all the work required, and only the work required, to complete the project successfully. (Project Smart, 2008)

2 Prototype: A less formal experimental development process of a proposed application for the purpose of demonstrating some or all of its functional capabilities (California State University, 2005).

Page 6: File Handler program

- 6 -

REFLECTION

This report will be separated into three main sections; section 1 (which covers requirements 1-33) and section 2 (which covers requirements 4-64

). In section 1, requirements will be gathered by using a number of UML tools and an initial version prototype will be developed. This prototype will complete requirements 1-3. In section 2, more requirements will be elicited and the initial version will be updated and redefined. New prototypes will be made which will aim to increase the efficiency of the initial system and incorporate the new requirements (requirements 4-6). After the system has been developed it will be tested to ensure that it satisfies all requirements. The testing stage (section 3) will be the last stage in the report. This will also include reflection statements on the processes undertaken. To summarise, this project will follow an evolutionary development framework using exploratory development to develop a fully functioning system that fulfils all the requirements.

FIGURE 1

3 Requirements 1-3 summarised: Design, plan and test an application that reads and displays a specific file.

4 Requirements 4-6 summarised: Design, plan and test an application that reads and displays a sequence of files with appropriate user interface.

Page 7: File Handler program

- 7 -

3. SECTION ONE

At the end of this section the first iteration of the system will be made. The general structure of the section comprises of:-

1. Requirements elicitation

During this stage UML diagrams will be used to determine the functionality that the system must produce. A final list of requirements will be defined in order to test that the system has been designed and developed correctly.

2. Design

More UML diagrams will be designed at this stage to give a better understanding of how the system will be built.

3. Implementation

The finished code listing will be in this section.

4. Testing

The code will be tested using component, system, and acceptance testing. If any errors are found they will be documented in this section.

The final product will be evaluated and expanded in Section 2.

Page 8: File Handler program

- 8 -

3.1 FEATURES LIST

INTRODUCTION TO FEATURES LISTS

A features list is an abstract tool used to gather the most basic of requirements. Essentially it is “a list of features that the proposed system should possess” (Neville, Feature List, 2008).

FEATURES LIST

The initial program must:-

1. Read a specific file

2. Display the contents of the file

3. Display the file name

REFLECTION

At this stage there is too little detail given to start the implementation of the system. However, it highlights the fact that the main feature will be the system’s ability to read files. Java provides classes to implement such tasks. Data can be encoded in three ways; text encoding, binary encoding and object-encoding (Charatan & Kans, 2006), and the different types of encoding offer different ways of reading files.

Binary encoding is stored as the internal representation of the data (for example the number 107 would be stored as 1101011). Binary files cannot be properly read by a text editor and so will not be appropriate in this project, as the files that will be used to test the functionality of the program are text (.txt) files.

Object-encoding is a Java tool in which a whole object 5

The FileReader and BufferedReader are used to read text encoded files. The FileReader “deals with the low-level details involved in the process of reading a file” (Charatan & Kans, 2006). The BufferedReader then ‘wraps

can be input or output.

Text encoding, where the data is stored as characters on the disk, will be the encoding used in this project. This is due to the aforementioned files being .txt files.

6’ the FileReader object to a BufferedReader object. This allows us to call methods7

Also in Java is a ‘File’ class, which is “an abstract representation of file and directory pathnames” (Sun Microsystems, 2001). It creates a File object when it is passed the path name of a file.

on that object to read it, e.g. the readLine() method, which reads a line of text from a file.

5 Object: An instantiation of a class

6 Wrapper classes in Java: Converts a primitive data type, e.g. int, to a class, e.g. Integer (Charatan & Kans, 2006)

7 Method: “Performs a single, well-defined task” by implementing a particular set of instructions

Page 9: File Handler program

- 9 -

3.2 CONTEXT DIAGRAM

INTRODUCTION TO CONTEXT DIAGRAMS

Context diagrams show the environment that the system (artifact) will work in (Neville, Context Diagrams, 2008).

Key:

An actor8

A message that is passed

of the system

Declares an interaction between system and actor

Object / artifact

CONTEXT DIAGRAM

REFLECTION

The main actor of the system is the user. The user inputs data to the system and is shown output from it. The other two actors – display and keyboard – can be combined to make one actor; the ‘system’.

8 Actor: The users of the system

Page 10: File Handler program

- 10 -

3.3 USE CASE DIAGRAM

INTRODUCTION TO USE CASE DIAGRAMS

Use case diagrams “define the interaction between actors and the system”, and “encapsulate a set of scenarios”9

(Sommerville, 2007). They are a high level of abstraction and are primarily used to determine interactions; therefore they are “not as effective for eliciting constraints and non-functional requirements” (Sommerville, 2007).

Although there is no standard way to write a use case, a common style is to first choose the main scenario and write a sequence of steps, written from the perspective of the user. The next stage is to define other scenarios (extensions). From these scenarios, actors and interactions can be established.

USE CASE TEXT

1. User types file that they want to display

GOAL: Display a file

Main success scenario:

2. System displays the name of the file 3. System reads the file and displays its content to the user 4. User chooses to exit the program

Extensions:

1. User chooses a file that does not exist a. System displays message that error occurred

3. The system cannot read the file line by line (e.g. if file was encoded in binary) a. System displays message that error occurred

9 Scenario: a sequence of steps describing an interaction between a user and a system (Fowler, 2004)

Page 11: File Handler program

- 11 -

DIAGRAM:

REFLECTION:

It can be seen from the use-case diagram that the two actors are the user and the system, following on from the context diagram. More requirements have now been established which add to the functionality of the system. One new concept is ‘displaying the file name’.

This can be done if a File object is created using the pathname (location) of a file (e.g. D:\Documents\FileHandlerProject\7179881TextAndSpCh.txt”). Then a method called getName() can be called to get the name of that file.

Another new requirement is the system’s ‘exception10

10 Exception: An event that occurs during the life of a program which could cause that program to behave unreliably.

handling’ requirement. When a file is read using the FileReader and BufferedReader classes, two exceptions can occur. One is the FileNotFoundException, which occurs if the pathname was incorrect and the file does not exist. The other is an IOException, which occurs if there was a general problem reading the file.

Page 12: File Handler program

- 12 -

3.4 REQUIREMENTS SPECIFICATION DOCUMENT

INTRODUCTION

This document contains a formal list of specifications that must be adhered to, and will be used in the acceptance testing of the system. It is the “official statement of what the developers should implement” (Sommerville, 2007). Each specification will be given a number between 1 and 3 corresponding to its importance, i.e. level 1 requirements are essential and level 3 are optional.

There are two main types of requirement; functional requirements and non-functional requirements. Functional requirements “are statements of services the system should provide” (Sommerville, 2007). Non-functional requirements are not “directly concerned with the specific functions” (Sommerville, 2007). Instead, they may relate to the reliability, speed and appearance of the system.

REQUIREMENTS SPECIFICATION

Level Specification Type of requirement 1 The system must display the file name. Functional 1 The system must display the file content. Functional 1 The user must be given a choice of what file to load. Functional 1 The system should provide error handling in case a file cannot be

loaded. Non-functional

1 The user should be informed of any errors in the program. Non-functional 2 The system should respond quickly (within 1 second) to user

commands. Non-functional

Page 13: File Handler program

- 13 -

3.5 CLASS, RESPONSIBILITIES AND COLLABORATORS

INTRODUCTION TO CRC DIAGRAMS

CRC diagrams are used in the form of index cards, which are used as a “visual (textual) abstraction methodology that follows a “divide and conquer” problem/solution methodology” (Neville, Class Responsibilities and Collaborators, 2008). They aim to break down the problem into sub-problems which can then be used to define the structure of the classes of the system.

Responsibilities are the tasks that the class will undertake.

Notation:

Collaborators indicate which tasks are undertaken by other classes.

DIAGRAMS

First draft of diagram

Second draft of diagram

Class Name Responsibilities Collaborators

FileReader Responsibilities Collaborators

Displays the file name Displays the file content Asks the user to input a file path Read a file line by line Check a file exists Handle errors when file is read

TextFile Responsibilities Collaborators

Read a file line by line Check the file exists TextFileProgram Save the name of the file to a variable Save the content of the file to a variable Handle errors when file is read

TextFileProgram Responsibilities Collaborators

Displays the file name TextFile Displays the file content TextFile Asks the user to input a file path

Page 14: File Handler program

- 14 -

REFLECTION

The first draft of the CRC card illustrates that there are a lot of exceptions that could occur. It was decided to create an object that would represent a file, as there is more cohesion in the component. Cohesion is a key principle for software design. It “describes the interactions within components” (Zeng, Software Design Methods, 2007).

Another principle that Zeng suggests is ‘modularity’, where large software systems are decomposed into smaller, more independent components. It allows complexity to be managed. Both of these principles are adhered to in the redesign of the CRC cards.

Thus, in the second version of the CRC cards, the system has two classes, one which will ask the user for a file location and one to store that file as an object.

An interesting point to note here is the use of ‘inheritance’. Inheritance is “the sharing of attributes and methods among classes. New classes inherit all of the attributes and methods of the first class, but also have attributes and methods of their own” (Charatan & Kans, 2006). A File object needs to be created in order to get the name of the file, and to use in the FileReader class to read its content. However, the File class contains a lot of methods but does not contain all the functionality required for this problem. Therefore, a ‘type of’

Another principle suggests maximising the information hiding, where components “hide the internal details and processing from one another” (Zeng, Software Design Methods, 2007). This is the reason for calling a ‘getter’ method (e.g. getName()) rather than trying to get the name attribute of the TextFile object itself. These variables will be made private to increase the information hiding.

File object will be created (called a TextFile) which inherits the methods of the File class and adds its own. This is notated in Java by:

ClassB extends ClassA, or alternatively, TextFile extends File.

The location of the file that the user wants to display is passed to the TextFile class which will get its name and store it, and get its content and store it (by using the FileReader and BufferedReader). Any exceptions caused by the file will be handled in this class.

When the object has been created it will be passed back to the TextFileProgram class which will call methods on the TextFile object to get its name and content.

Page 15: File Handler program

- 15 -

3.6 CLASS DIAGRAMS

INTRODUCTION TO CLASS DIAGRAMS

Class diagrams are widely used in software development and “describes the types of objects in the system and the various kinds of static relationships that exist among them” (Fowler, 2004).

Class Name

Attributes

Methods

Attributes are represented in the form of: Visibility name : type multiplicity = default {property-string}

Methods are represented in the form of: Visibility name (parameter-list) : return-type {property-string} The parameters in the parameter-list are represented as: direction name : type = default value

Arrows represent an association between classes, and the numbers on the arrow represents the multiplicity11

* 1 Fig 2.1

E.g. Fig 2.1 shows that a Class can have zero or more Students but a Student can only have one Class

DIAGRAM

11 Multiplicity: an indication of how many objects may fill the property (Fowler, 2004).

TextFileProgram

-testTextFile : TextFile

TextFile

-name : String

-content : String

+TextFile(s : String) : null

+getName() : String

+getContent() : String

+readFile(f : File) : String

Student Class

1 1

Page 16: File Handler program

- 16 -

REFLECTION

These class diagrams indicate that the TextFileProgram class can have one TextFile and a TextFile can only have one TextFileProgram class. Therefore a user can only enter the pathname of one specific file and that file is created into a TextFile object. Each of those TextFile objects can be accessed by the TextFileProgram class that sent in the original pathname.

The TextFile class contains ‘name’ and ‘content’ variables which are declared as private (represented by the – symbol). This means that they can only be accessed by the TextFile class. The getName() and getContent() methods (commonly referred to as ‘getter’ methods) enable the values of those variables to be passed to the TextFileProgram class when needed, but not changed directly. To summarise, the TextFileProgram class will only get a copy

Errors can occur in the readFile() method as previously discussed (see the

of the name and content data, and not the ‘real’ data.

reflection section on page 11). The readFile() method returns a string. This string will either be a string containing an error message, if an error occurred, or containing the content of the file if no error occurred. The reason for doing this is to ensure that the program does not crash for the user at any time in the TextFileProgram class. Therefore, if an error occurs then the TextFile object will still have the name and content variables for the TextFileProgram class to ‘get’, but the content itself may indicate an error.

Page 17: File Handler program

- 17 -

3.7 HIERARCHICAL TASK ANALYSIS

INTRODUCTION TO HTA DIAGRAMS

Hierarchical task diagrams describe “how tasks are split into sub-tasks, their ordering and when they are performed” (Stevens, 2008).

The structure of a hierarchical task diagrams usually consists of “a goal at the top, followed by sub-goals, unit tasks and artifacts. Sub-goals may be further sub-divided as required” (ACM, 2005). These goals are normally written from the perspective of the user.

DIAGRAM

REFLECTION

This is a very simple diagram which shows the user process through the proposed system.

Main Goal

Do all steps in order

Page 18: File Handler program

- 18 -

3.8 PSEUDOCODE – LEVEL ONE

INTRODUCTION

Pseudocode is used for describing algorithms. It “allows the designer to focus on the logic of the algorithm without being distracted by details of language syntax” (Dalbey, 2003). The first level of the pseudocode is very basic as it is intended to give a better idea of program flow.

PSEUDOCODE

1. System prompts user to enter a pathname – user enters pathname and presses enter

2. System stores pathname to variable

3. System prompts user to enter a filename – user enters filename and presses enter

4. System stores filename to variable

5. Create TextFile object by combining pathname and filename variable to constructor

i. TextFile class sends pathname to superclass File

ii. If error occurs with file name

1. Save error message as name variable

iii. Else,

1. Save name of file as variable

iv. Save content of file as variable

1. Get File object from superclass File

2. Use FileReader on the File object

3. Use BufferedReader on the FileReader object

4. Read file line by line until end of file

5. If error occurs

a. Save error message as content variable

6. System uses getName() method to display the name of the file

7. System uses getContent() method to display the content of the file

REFLECTION

This pseudocode makes it easier to begin to think about the Java code for implementing this system.

Page 19: File Handler program

- 19 -

3.9 PSEUDOCODE LEVEL TWO

INTRODUCTION

The second level of the pseudocode aims to use the syntax of the Java language to describe system processes and artefacts that are produced by the system.

PSEUDOCODE

1. Open the TextFileProgram class

i. In the ‘main’ method

1. Create new Scanner object to read in Strings from the user

2. System println() method – “Please enter a pathname”

3. path variable = next() method of Scanner object

4. System println() method – “Please enter a filename”

5. name variable = next() method of Scanner object

6. pathname variable = path and name combined

7. Create new TextFile and pass pathname variable as parameter

2. To create new TextFile, first open the TextFile class

1. TextFile constructor method

i. Send string variable into superclass by the super() method

ii. name variable= getName() method of the super class

iii. Get File object from superclass with getAbsoluteFile() method

iv. content variable = call readFile() method, passing the File as a parameter

1. readFile() method

a. try:

b. Create new FileReader passing in the file as a parameter

c. Create new BufferedReader passing in FileReader object as a parameter

d. Variable ‘temp’ = call the readLine() method of BufferedReader

e. Loop until the readLine() method returns null

i. Variable ‘contentRead’ adds the ‘temp’ String to itself

ii. temp = call readLine() method

Page 20: File Handler program

- 20 -

f. Close the BufferedReader

g. catch FileNotFoundException exception

i. return the String "The file was not found";

h. catch IOException exception

i. return the String "There was an IO error";

3. Open class TextFileProgram

i. Open main method

1. System calls println() method with the following as a parameter:

a. System calls getName() method of TextFile

b. System calls getContent() method of TextFile

REFLECTION

This pseudocode provides a good foundation upon which entire lines of Java code can be written.

Page 21: File Handler program

- 21 -

3.10 PSEUDOCODE – LEVEL THREE

INTRODUCTION

The third level of the pseudocode aims to entirely use the syntax of the Java language to describe the process in such a way that it can be transferred directly into a Java editor.

PSEUDOCODE

1. class TextFileProgram

i. public static void main(String args[])

1. Scanner sc = new Scanner(System.in);

2. System.out.println(“Please enter a pathname”);

3. path = sc.next();

4. System.out.println(“Please enter a filename”);

5. name = sc.next();

6. pathname = path.trim() + name.trim();

7. TextFile newTextFile = new TextFile(pathname);

2. public TextFile(String s)

i. super(s);

ii. name = super.getName()

iii. content = readFile(super.getAbsoluteFile())

1. public readFile(File file)

a. try:

b. FileReader textfile = new FileReader(file);

c. BufferedReader textfile = new BufferedReader (textfile);

d. temp = stream.readLine();

e. while (temp!=null)

i. contentRead += temp + "\n";

ii. temp = stream.readLine();

f. stream.close();

g. catch (FileNotFoundException e)

Page 22: File Handler program

- 22 -

i. return "The file was not found";

h. catch (IOException e)

i. return "There was an IO error";

3. class TextFileProgram

i. public static void main(String args[])

1. System.out.println(getName() + “\n\n” + getContent());

REFLECTION

This pseudocode now can be transferred to a Java editor to finish the coding.

Page 23: File Handler program

- 23 -

3.11 COMMENTED CODE LISTING

INTRODUCTION

There will be two documents in this section. One document is the code for the TextFile class, the other is for the TextFileProgram class.

CODE LISTING

CLASS TEXTFILE

/************************************************ Class TextFile Description: A class from which objects of TextFiles can be made *************************************************/ //The class is declared as part of the filehandlerproject package. package filehandlerproject; //Import statements. IO is needed in this class to handle the file reading import java.io.*; //The class public class TextFile {

//Variable declaration String name; //To store the name of the file String content; //To store the content of the file /************************************************************** The constructor of the class. Takes a File object as a parameter ***************************************************************/ public TextFile(String s) {

//sends the location string to the File superclass super(s);

/*instantiates name by calling built-in getName() method of File class, it calls the superclass object to get this*/ name = super.getName(); /*instantiates content by calling readFile method of this class and sending it the string containing the location of the file according to the File superclass*/ content = readFile(super.getAbsoluteFile()); } /****************************************************************

Page 24: File Handler program

- 24 -

The getName() method of the class. Returns a String *****************************************************************/ public String getName() {

/*If the getName() method return null then a file was not found. If it is not null then a name was found*/ if (name!=null) {

return name; //returns String name } else //name was null { /*Returns a string that will show when getName() method is called. It will help the user in understanding what went wrong*/ return "The name of the file could not be determined"; }

}

/**************************************************************** The getContent() method of the class. Returns a String *****************************************************************/ public String getContent() {

return content; //returns global private variable }

/*************************************************************** The readFile() method of the class. Returns a String and takes a File as parameter and calls it 'i' *****************************************************************/ public String readFile (File i) {

String contentRead = ""; //declares local empty String variable String temp = ""; //declares local empty String variable //try-catch block is used for the code in which errors can occur try {

/*makes a new FileReader object called textfile by passing in a File object variable called i*/ FileReader textfile = new FileReader(i); /*makes a new BufferedReader object called stream by passing in a FileReader object variable called textfile*/ BufferedReader stream = new BufferedReader(textfile); /*the readLine() method is called on the BufferedReader*/ temp = stream.readLine(); //do this loop until the file reaches the end while (temp!=null)

Page 25: File Handler program

- 25 -

{ /*adds the line from the file to the contentRead variable, and adds a new line after each line so that the whole file will not be on one line*/ contentRead += temp + "\n"; /*the readLine() method is called on the BufferedReader again*/ temp = stream.readLine();

} //closes the file for reading stream.close();

} //if the file was not found in the location catch (FileNotFoundException e) {

/*returns string to let user know that an error occured. This variable is stored as the content of the file*/ return "The file was not found";

} catch (IOException e) {

/*returns string to let user know that an error occured. This variable is stored as the content of the file*/ return "There was an IO error";

} /*if the program has reached this stage then there was no error so the content of the file can be returned as a String to be stored*/ return contentRead;

} }

CLASS TEXTFILEPROGRAM

/************************************************ Class TextFileProgram Description: A tester class for the TextFile class which chooses files to display *************************************************/ //The class is declared as part of the filehandlerproject package. package filehandlerproject; //Import statements import java.io.*; //IO is needed in this class to handle the file creation import java.util.Scanner; //Scanner class is used to read in characters from //the users keyboard //the main class public class TextFileProgram

Page 26: File Handler program

- 26 -

{ //the main method in the class public static void main(String args[]) {

//creates a new Scanner object to read the content from the user Scanner sc = new Scanner(System.in); //prints a line of code to the output window System.out.println("Please enter the location of the file, e.g D:\\Documents\\ : "); //saves the String that the user types to the location variable String location = sc.next(); /*if the user forgets to put the \ character at the end of the location variable then it needs to be added to ensure that the file is found*/ if (!location.endsWith("\\")) {

//the location string adds a \ to the end of it location+="\\";

} //prints a line of code to the output window System.out.println("Please enter the full name of the file: "); //saves the String that the user types to the name variable String name = sc.next(); //creates a TextFile object called testFile by passing the string location of the file TextFile testTextFile = new TextFile(location + name); //prints a line of code to the output window with the name and content of //the file that the user entered by calling the 'getter' methods. System.out.println( "\n\n"+ //creates a new line "Title: " + testTextFile.getName() + //calls getName() method "\n\n" + //creates a new line testTextFile.getContent() //calls getContent() method );

} } //end of class TextFileProgram

Page 27: File Handler program

- 27 -

3.12 TESTING (SOFTWARE VALIDATION)

INTRODUCTION

The first iteration of the system has been completed. At this stage it is essential to test that the system is error-free and it fulfils all requirements.

Software validation comprises of three distinct stages. ‘Component testing’, ‘System testing’ and ‘Acceptance testing’.

A diagrammatical representation of the three stages is shown in Figure 2.

As the system has not been fully completed, only the first stage (component testing), and last stage (acceptance testing) will be undertaken.

FIGURE 2

Page 28: File Handler program

- 28 -

3.13 COMPONENT TESTING

INTRODUCTION

Component testing involves the testing of individual components of the system. They are tested to ensure that they operate correctly.

A “Test harness” will be used to assess the functionality of each of the components. Put simply, test harnesses are “a system to handle the elements you’ll repeat each time you write a test” (Rowe, 2008).

It can be argued that the TestFileProgram component is a form of test harness in itself. This is due to its dependence on the TextFile component. However, as it requires user input from the keyboard it is more susceptible for human errors. For that reason, another test harness will be created for the TextFile component.

Black box testing focuses on “whether the class meets the requirements stated in the specification” (Dennis, Wixom, & Tegarden, 2005). It “assumes no knowledge of the program code or design” (Zeng, Software Testing, 2008).

Test harnesses are a feature of white box testing. White-box testing is when the system developer looks “inside the class to review the code itself to discover errors or assumptions not immediately obvious to someone treating the class as a black box.” (Dennis, Wixom, & Tegarden, 2005)

Page 29: File Handler program

- 29 -

3.14 BLACK BOX TESTING

INTRODUCTION

In this section, test data will be used to run the program to ensure that the system fulfils the requirements set out in the specification.

TEST RUN ONE

DESCRIPTION AND TEST DATA

In the first example the location that will be entered will be entered without the backslash (\) character at the end of it. This is to test that the program adds a backslash character to the end as was intended. If the character is not added then the program will fail. The user input is represented by an arrow.

OUTPUT

REFLECTION

The test run was a success; the file was displayed correctly even though the \ was omitted.

Page 30: File Handler program

- 30 -

TEST RUN TWO

DESCRIPTION AND TEST DATA

In the second example the location that will be entered will be entered with the backslash (\) character at the end of it. This is to test that the program doesn’t add a backslash to the end when one exists. The user input is represented by an arrow.

OUTPUT

REFLECTION

The test run was a success; the file was displayed correctly even though the \ was present.

Page 31: File Handler program

- 31 -

TEST RUN THREE

DESCRIPTION AND TEST DATA

In the third example the filename will be misspelled. The user input is represented by an arrow.

OUTPUT

REFLECTION

The test run was a success, the file name was displayed to the user with a message that the file could not be found. The file name is still shown here (7179881TextAndData.txts) so that the user notices and rectifies their mistake.

Page 32: File Handler program

- 32 -

TEST RUN FOUR

DESCRIPTION AND TEST DATA

In the third example we will test what happens when a different type of file (other than a text file) is loaded. In this example a .jpg (image) file will be loaded. Image files are stored in binary format so the program is expected to show a list of unreadable characters. The user input is represented by an arrow.

OUTPUT

REFLECTION

The test run was a success, the file name was displayed to the user with the content of the readLine() method. However, image files are not shown this way so this can be quite confusing for the user. A way in which this can be avoided is to only allow text files to be entered. First, another type of file will be loaded to see the results.

Page 33: File Handler program

- 33 -

TEST RUN FIVE

DESCRIPTION AND TEST DATA

In the fifth example we will again test what happens when a different type of file (other than a text file) is loaded. In this example a .pdf (portable document format) file will be loaded. It is unsure what to expect the program to display. The user input is represented by an arrow.

OUTPUT

REFLECTION

The test run was a failure; the program only output this data after approximately 25 minutes. This could be problematic and confusing for a user. One of the specifications of the program stipulates that the program will respond within 1 second of user input. Therefore it shows that a filter is needed to ensure that only .txt files are input by the user. We will now return to the design phase to resolve this problem.

Page 34: File Handler program

- 34 -

3.15 DESIGN (STAGE 2)

INTRODUCTION

When the user enters a file other than a text (.txt) file, the system behaves erratically. Therefore a test to ensure that the user only enters a filename with “.txt” as the suffix will be needed.

DESIGN

The constructor method of TextFile is shown below.

As the method call to the superclass must be the first line of code, the check that the filename ends in “.txt” cannot be placed in this class. Therefore, we must incorporate this check into the class that calls this method, namely the TextFileProgram class, shown below.

The String class has a method called ‘endsWith()’ which takes a string as parameter to test. Thus, we can modify the code to include this method. The pseudocode of this code snippet would be:-

1. Get String from user 2. If String does not end in “.txt” 3. Display message that it must be a .txt file 4. Prompt for another String

The Java code for this would be:-

//prints a line of code to the output window System.out.println("Please enter the full name of the file: "); //saves the String that the user types to the name variable String name = sc.next(); //loop until a text file is entered while (!name.endsWith(".txt")) { //prints a line of code to the output window System.out.println("Please enter a filename ending with '.txt'");

public TextFile(String s)

{

//sends the location string to the File superclass

super(s);

//saves the String that the user types to the name variable

String name = sc.next();

Page 35: File Handler program

- 35 -

//prints a line of code to the output window System.out.println("Please enter the full name of the file: "); //saves the String that the user types to the name variable name = sc.next(); }

RESULT

The modifications have been made to the code, and Test 5 will now be repeated to see the outcome. It is expected that the program will loop until a text file is entered. The user input is represented by an arrow.

REFLECTION

The test was a success, now the first iteration need to be checked against its specification.

Page 36: File Handler program

- 36 -

3.16 ACCEPTANCE TESTING

INTRODUCTION

The requirements specification will be checked against the output of the program to ensure that it meets the specification

REQUIREMENTS SPECIFICATION

Level Specification Fulfils requirement? 1 The system must display the file name. YES 1 The system must display the file content. YES 1 The user must be given a choice of what file to load. YES 1 The system should provide error handling in case a file cannot be

loaded. YES

1 The user should be informed of any errors in the program. YES 2 The system should respond quickly (within 1 second) to user

commands. YES

REFLECTION

The system meets all specifications, so the black box testing is complete.

Page 37: File Handler program

- 37 -

3.17 WHITE BOX TESTING

INTRODUCTION

In white-box testing, “every path through the program is executed at some time” (Zeng, Software Testing, 2008). A test harness has been written to test the methods of this class. This test harness will be run and the results will be noted in a table.

TEXTFILE COMPONENT TEST

/************************************************ Class TextFileTester_1 Description: A tester class for TextFile which chooses files to display *************************************************/ //The class is declared as part of the filehandlerproject package. package filehandlerproject; //the main class public class TextFileTester_1 {

//the main method in the class public static void main(String args[]) {

/*creates a TextFile object called testFile by passing the location and name of a file*/ TextFile testTextFile = new TextFile("D:\\Documents\\7179881TextAndData.txt"); //prints a line of code to the output window with the name and content of //the file that the user entered by calling the 'getter' methods. System.out.println( "\n\n"+ "Test 1, get the file name: " + testTextFile.getName() + //calls getName() method "\n\n" + //creates a new line "Test 2, get the content of the file:\n" + testTextFile.getContent() + //calls getContent() method "Test 3, get name and content as String: " + testTextFile.toString() ); /*Test 4 creates a new TextFile with the same path name and calls the equals method to see if they equal each other*/ TextFile testTextFile2 = new TextFile("D:\\Documents\\7179881TextAndData.txt"); boolean equals = testTextFile2.equals(testTextFile); System.out.println("Test 4:does testTextFile2 equal testTextFile? " + equals); /*Test 5 creates a new TextFile with a different path name and calls the equals method to see if they equal each other*/ TextFile testTextFile3 = new TextFile("D:\\Documents\\7179881TextAndSp.txt"); boolean equals2 = testTextFile3.equals(testTextFile); System.out.println("Test 5: does testTextFile3 equal testTextFile? " + equals2);

} } //end of class TextFileTester

Page 38: File Handler program

- 38 -

TABLE OF RESULTS

Now the test harness class will be run, and the results marked down in the table below.

Test Number 1 2 3 4 5 Expected Result 7179881TextAndData.txt the content of

7179881TextAndData.txt (see appendix for file

contents)

7179881TextAndData.txt plus an empty line and then the content (see

appendix for file contents)

true false

Actual Result 7179881TextAndData.txt the content of 7179881TextAndData.txt

(see appendix for file contents)

7179881TextAndData.txt plus an empty line and then the content (see

appendix for file contents)

true false

Pass / Fail Pass Pass Pass Pass Pass

REFLECTION

All tests passed, so the white-box testing test can be concluded for TextFile.

Page 39: File Handler program

- 39 -

4. SECTION TWO

After the first iteration of the system we can see that the system functions efficiently. It successfully creates a new object from the TextFile class (the subclass), containing only the data that it needs from the File superclass. The TextFile class contains the name and content of the file that the user wants to display, and it only allows them to open .txt files.

The next stage of the iteration is to allow the user to get a sequence of files. In this section we will use the first iteration of the system but increase its functionality to include this requirement. An appropriate graphical user interface will also be designed.

This section will contain the following:-

1. Requirements elicitation

During this stage, UML diagrams will be used to determine the additional functionality that the system must produce. A final list of requirements will be defined in order to test that the system has been designed and developed correctly.

2. Design

More UML diagrams will be designed at this stage to give a better understanding of how the system will be built. Designs of the graphical interface will be in this section.

3. Implementation

The finished code listing will be in this section.

4. Testing

The code will be tested using component, system, and acceptance testing. If any errors are found they will be documented in this section.

Page 40: File Handler program

- 40 -

4.1 FEATURES LIST

INTRODUCTION TO FEATURES LISTS

A features list is an abstract tool used to gather the most basic of requirements. Essentially it is “a list of features that the proposed system should possess” (Neville, Feature List, 2008).

In the first section a feature list was made containing the basic functions. The requirements that feature in both lists are highlighted in bold.

FEATURES LIST

The final program must:-

1. Enable the user to choose a file from a file browser

2. Check that the file is of the correct format (.txt)

3. Display the content of a file chosen by the user

4. Show a list of loaded files

5. Allow user to browse through loaded files

6. Display the file name

7. Display the number of the file (e.g. 1/3) from the list

8. Contain no errors

9. Enable user to remove files from the list

10. Allow user to close the program

11. Restrict the amount of files that the user can add to the list

REFLECTION

The features list has increased in size significantly in this second iteration of the program. The final program must implement an appropriate user interface, so graphical components of Java need to be considered at this stage.

For example, a file browser (see Figure 3) is implemented in Java using the JFileChooser class. The JFileChooser class “displays a dialog that enables users to easily select files” (Deitel & Deitel, Java: How to Program, 2005). In the first iteration of the program, the pathname and name of the file that the user wanted to display was directly written into the program by the user. This is susceptible to many human errors. For example, they could spell the path name or file name incorrectly, they could forget to include the whole pathname or they could try and open a file that cannot be used in conjunction with the FileReader/BufferedReader classes. Thus, using a JFileChooser class practically eliminates all human error.

Requirement two implements another function of the JFileChooser class, specifically the addChoosableFileFilter() method. The FileFilter class “can be set on a JFileChooser to keep unwanted files from appearing in the directory listing” (Sun Microsystems, 2008).

Page 41: File Handler program

- 41 -

In this project a custom file filter will be created following an example found on a tutorial website (Demo Source and Support, 2008). This new FileFilter will just filter text (.txt) files from the JFileChooser.

One of the main features in the next iteration of the system is its ability to load a sequence of files. A sequence implies that a collection must be used. The Java Collections Framework is “a group of generic collections classes that grow as more elements are added to them”. This seems to be a more robust method than using a simple array12

The Java Collections Framework provides three different collection interfaces; List, Set and Map. Set interfaces contain no repetition of data and ordering is unimportant. Therefore, it is not suitable for use in this project, as ordering will be important. Map interfaces “process a collection consisting of pairs of objects” (Charatan & Kans, 2006), thus would be inefficient in this example as there is only the title of the file to store in the list. A List interface (specifically the ArrayList) will be used. It is designed for use with an ordered list of objects. Ordering is important here as the number of the file will be shown (feature 7).

. This is because arrays are a fixed size and cannot be changed when the program is run. In future iterations of the system it is likely that the user will want to be able to change the maximum amount of objects (items) that can be stored.

FIGURE 3

12 Array: A container to store a collection of items of the same type (Charatan & Kans, 2006)

Page 42: File Handler program

- 42 -

4.2 CONTEXT DIAGRAM

INTRODUCTION TO CONTEXT DIAGRAMS

Context diagrams show the environment that the system (artifact) will work in (Neville, Context Diagrams, 2008)

An actor of the system

Key:

A message that is passed

Declares an interaction between system and actor

Object / artifact

CONTEXT DIAGRAM

Page 43: File Handler program

- 43 -

4.3 USE CASE DIAGRAM

INTRODUCTION TO USE CASE DIAGRAMS

Use case diagrams “define the interaction between actors and the system”, and “encapsulate a set of scenarios”13

Although there is no standard way to write a use case, a common style is to first choose the main scenario and write a sequence of steps from the perspective of the user. The next stage is to define other scenarios (extensions). From these scenarios, actors

(Sommerville, 2007). They are a high level of abstraction and are used to determine interactions primarily; therefore they are “not as effective for eliciting constraints and non-functional requirements” (Sommerville, 2007).

14

and interactions can be established.

The first use case diagram showed that the two actors were the user and the system.

USE CASE TEXT

1. User selects file to add to list

GOAL : Display a file

Main success scenario:

2. User selects file from list to display 3. User presses display file 4. System displays file content and name

Extensions:

1. List is full a. System displays message that list is full b. File is not added to list

1. User chooses a file that is already in the list a. System displays message that item is already in the list b. File is not added to list c. System prompts for another file

13 Scenario: a sequence of steps describing an interaction between a user and a system (Fowler, 2004)

14 Actor: The users of the system

Page 44: File Handler program

- 44 -

DIAGRAM:

REFLECTION:

More functionality has been added to the use case in order to achieve requirement 415. The diagram indicates that the list is the most important feature, and will need to be carefully planned. At this early stage there is no concrete design plan, but it seems apparent that there will need to be at least two classes, one to contain the graphical user interface (GUI) and one to contain the ArrayList itself. Again this is the modularity16

15 Requirement 4: Design an application that can read a sequence (set of files) and display them.

principle of software design. Error handling is much easier when individual components can be tested thoroughly. One suggestion for a design would be to have a ‘FileHandler’ class which contains the list and all the functions needed to access and modify the list, and a graphical user interface class (‘FileHandlerInterface’) which contains a reference to the FileHandler class by creating an object of it. It will also contain the graphical functions, such as the JFileChooser and the text area to display the content of the file. A high quality GUI is needed to ensure the efficiency of the system, and so rigorous testing will be undertaken.

16 Modularity: Where large software systems are decomposed into smaller, more independent components. See page 13

Page 45: File Handler program

- 45 -

4.4 REQUIREMENTS SPECIFICATION DOCUMENT

INTRODUCTION

This document contains a formal list of specifications that must be adhered to, and will be used in the acceptance testing of the system. It is the “official statement of what the developers should implement” (Sommerville, 2007). Each specification will be given a number between 1 and 3 corresponding to its importance, i.e. level 1 requirements are essential and level 3 are optional.

There are two main types of requirement; functional requirements and non-functional requirements. Functional requirements “are statements of services the system should provide”. Non-functional requirements are not “directly concerned with the specific functions”. Instead they may relate to the reliability, speed and appearance of the system.

REQUIREMENTS SPECIFICATION

Level Specification Type of requirement 1 The system must display the file name of the file in the display area Functional 1 The system must display the file content of the file in the display area Functional 1 The user must be given a choice of what file to load from a file

browser Functional

1 The system should provide error handling in case a file cannot be loaded

Non-functional

1 The user should be informed of any errors in the program Non-functional 2 The system should respond quickly (within 1 second) to user

commands Non-functional

1 The user should be able to close the program Functional 1 The user should be able to add a file to the list Functional 1 The user should be able to remove a file from the list Functional 2 The user should be able to clear the list Functional 3 The user should be able to change the maximum size of the list Functional 1 The system should ensure that the list size does not go below the

number of items currently in the list Non-functional

1 The system should ensure that the only files that can be loaded into the program are text files

Functional

2 The user should be able to open a file directly Functional 3 The system should give the user help using tooltips Non-functional 2 The system should contain an error log Non-functional

Page 46: File Handler program

- 46 -

4.5 CLASS, RESPONSIBILITIES AND COLLABORATORS

INTRODUCTION

CRC diagrams are used in the form of index cards, which are used as a “visual (textual) abstraction methodology that follows a “divide and conquer” problem/solution methodology” (Neville, Class Responsibilities and Collaborators, 2008). They aim to break down the problem into sub-problems which can be used to define the structure of the classes of the system.

Responsibilities are the tasks that the class will undertake.

Collaborators indicate which tasks are undertaken by other classes.

Two classes were identified in the first iteration of the program: The TextFile class and the TextFileProgram class. These classes will remain unchanged in this second iteration.

DIAGRAMS

FileHandler Responsibilities Collaborators

Hold an ArrayList of TextFiles Change the maximum size of the ArrayList FileHandlerInterface Allows access to specific TextFiles in the ArrayList when given an index FileHandlerInterface Allows access to the entire ArrayList of files Adds TextFiles to ArrayList FileHandlerInterface Removes TextFiles from ArrayList FileHandlerInterface Clears the ArrayList

Class Name Responsibilities Collaborators

TextFile Responsibilities Collaborators

Read a file line by line Check the file exists TextFileProgram Save the name of the file to a variable Save the content of the file to a variable Handle errors when file is read

TextFileProgram Responsibilities Collaborators

Displays the file name TextFile Displays the file content TextFile Asks the user to input a file path

Page 47: File Handler program

- 47 -

FileHandlerInterface Responsibilities Collaborators

Holds a FileHandler object (instance of class) FileHandler Shows a graphical user interface with 'add', 'remove' and 'show' buttons Contains button to move to next and previous files in list Allows the user to close the program

REFLECTION

These CRC diagrams make it clear that the FileHandlerInterface class will be dependent on the FileHandler class. It will contain graphical features that will interface with the FileHandler class (i.e. calling methods of the FileHandler class when a button is pressed).

Page 48: File Handler program

- 48 -

4.6 CLASS DIAGRAMS

INTRODUCTION

Class diagrams are widely used in software development and “describes the types of objects in the system and the various kinds of static relationships that exist among them” (Fowler, 2004).

Class Name

Attributes

Methods

Attributes are represented in the form of: Visibility name : type multiplicity = default {property-string}

Methods are represented in the form of: Visibility name (parameter-list) : return-type {property-string} The parameters in the parameter-list are represented as: direction name : type = default value

Arrows represent an association between classes, and the numbers on the arrow represents the multiplicity17

* 1 Fig 2.1

E.g. Fig 2.1 shows that a Class can have zero or more Students but a Student can only have one Class

The classes that were found in the first iteration of the program have not changed and so will be re-used in this iteration.

17 Multiplicity: an indication of how many objects may fill the property (Fowler, 2004).

Student Class

Page 49: File Handler program

- 49 -

DIAGRAM

TextFile

-name : String -content : String +TextFile(s:String) : null +getName() : String +getContent() : String +readFile(f : File) : String

TextFileProgram

-testTextFile : TextFile

FileHandler

-arrayList : TextFile[]

-max : int

+FileHandler() : null

+getList() : ArrayList<TextFile>

+getTextFile(int) : TextFile

+getMax() : int

+removeFromList(int) : boolean

+addToList(File) : String

+clearList() : null

+nextFile(int) : TextFile

+prevFile(int) : TextFile

+setMaxSize(int) : String

FileHandlerInterface -addButton : JButton -changeSize : JMenuItem -clearButton : JButton -displayArea : JTextPane -displayButton : JButton -displayList : JList -filesLabel : JLabel -menuAbout : JMenuItem -menuBar : JMenuBar -menuClose : JMenuItem -menuFile : JMenu -menuHelp : JMenu -menuHelpTopics : JMenuItem -menuOpen : JMenuItem -nextButton : JButton -numLabel : JLabel -openButton : JButton -prevButton : JButton -remButton : JButton -remResult : JLabel -titleLabel : JLabel -mainPanel : JPanel -filehandler : FileHandler -listEntry : int = 0 -model : DefaultListModel

+FileHandlerInterface() : null +showList() : null +changeEnabled() : null +main(String) : null +showChangeDialog() : String +showMsg() : String

*

1

1

1 1

1 1

*

Page 50: File Handler program

- 50 -

REFLECTION

The FileHandler class contains no graphical features and so will be able to be implemented and tested without the need of the FileHandlerInterface. This will make debugging easier.

The TextFile class contains ‘arrayList’ and ‘max’ variables which are declared as private (represented by the – symbol). This means that they can only be accessed by the FileHandler class. The getList() and getMax() methods (commonly referred to as ‘getter’ methods) enable the values of those variables to be passed to the FileHandlerInterface class when needed, but not changed directly. It also contains a getTextFile() method which returns a TextFile object in the ArrayList. To summarise, the FileHandlerInterface class will only get a copy of the data, and not the ‘real’ data.

As previously mentioned, ArrayList’s are part of the Java Collections Framework. This provides an interface class called an Iterator. Although this provides functions to move through the ArrayList (using the next() method), it will not be used in this system. This is because it is intended that the user can choose any item in the ArrayList to display, and once it is displayed then they can move between files. Therefore an Iterator is not as useful as writing custom code to handle these events.

Just as ‘getter’ methods are shown in this diagram, so are ‘setter’ methods, namely the setMaxSize() method. It is intended that the maximum size of the list is initially set to 3 (as that is the amount of files that will be entered into the program to test it), but can be altered as the user requires. It can be argued that the most effective way to do this is have an “edit size” in the menu bar of the program, which displays a dialog box to the user prompting for a new maximum size.

In addition to the methods in the FileHandlerInterface, there will be methods pertaining to the event of most of the attributes, i.e. when the mouse is clicked on a button a method is called.

Page 51: File Handler program

- 51 -

4.7 HIERARCHICAL TASK ANALYSIS

INTRODUCTION

Hierarchical task diagrams describe “how tasks are split into sub-tasks, their ordering and when they are performed” (Stevens, 2008).

The structure of a hierarchical task diagrams usually consists of “a goal at the top, followed by sub-goals, unit tasks and artifacts. Sub-goals may be further sub-divided as required” (ACM, 2005). These goals are normally written from the perspective of the user.

DIAGRAM

Page 52: File Handler program

- 52 -

4.8 GRAPHICAL USER INTERFACE DESIGNS

INTRODUCTION

The requirements of the system have been gathered, and the discovery stage of the development process is now complete. The next stage of the process is the design stage. This usually begins with “a conceptual design of the system, which involves organising the information space of the proposed design” (Heim, 2008). Prototypes will be developed, which will then be analysed using a heuristic evaluation proposed by Nielson18

1. Visibility of System Status

. These heuristics are:

2. Match between System and the Real World

3. User Control and Freedom

4. Consistency and Standards

5. Error Prevention

6. Recognition Rather than Recall

7. Flexibility and Efficiency of Use

8. Aesthetic and Minimalist Design

9. Help Users to Recognise, Diagnose and Recover from Errors

10. Help and Documentation

18 Nielson’s heuristics can be found at http://www.useit.com/papers/heuristic/heuristic_list.html

Page 53: File Handler program

- 53 -

DESIGN ONE

EVALUATION OF DESIGN ONE

Heuristic 1.

This design does not give the user much feedback. After the user has chosen a file from the

JFileChooser, it would be advisable to provide feedback to them. The most appropriate way

is to change the mouse cursor from a pointer to an hourglass to indicate that the file is being

loaded.

Heuristic 2.

The button design does not match the real world as much as it could. The ‘close’ button is

ambiguous – does it close the program or close the file from being displayed? The ‘add file’

menu option could be interpreted as ‘add file to list’ or ‘add file to display’. More information

should be provided.

Page 54: File Handler program

- 54 -

Heuristic 3.

There is no ‘emergency exit’ in this design. In the next design it is important to prompt the user,

“are you sure..” when they click on some buttons, e.g. ‘close’.

Heuristic 4.

The aforementioned ‘close’ button being ambiguous is an example of bad design practice.

However, the menu items do follow platform conventions, e.g. the File menu being the leftmost

menu item and the Help item being the rightmost.

Heuristic 5.

Errors can occur in the program when the list size is changed to a size that is smaller than the

amount of files in the list. For example, if there are three items in the list and the user puts the

size at two. Error handling will be dealt by a popup box telling the user that it is not allowed.

This is standard practice and is considered a ‘good’ error message.

Heuristic 6.

The recognition rather than recall heuristic suggests that icons would be appropriate to use in

the system. This makes it easier for the user to remember what they need to do to perform a

certain task.

Heuristic 7.

This heuristic is not applicable in this system as the system is relatively simple to use and

contains very little to remember.

Heuristic 8.

This design is very minimalist, although it may be better if it were more appealing.

Heuristic 9.

There are no error messages that are too confusing for the user in this design. All messages will

be clear and precise so that the user knows exactly what to do if an error occurs.

Heuristic 10.

A help document should be provided for this system, if time allows. It will be found in the ‘help’

item in the menu list.

Page 55: File Handler program

- 55 -

DESIGN TWO

Without files:

With files:

Page 56: File Handler program

- 56 -

EVALUATION OF DESIGN TWO

Heuristic 1.

This design changes the mouse cursor from a pointer to an hourglass to indicate that the file

is being loaded.

Heuristic 2.

More information is provided in this design and the buttons are clearer, i.e. “Add file to list” is easier

to understand. The layout suggests in what order buttons are designed to be pressed, i.e. the add file

button is above the list which suggests that the user should put things in, and the remove button is

below it, which suggests taking things out.

Heuristic 3.

When the user clicks on destructive buttons, such as close and delete, a message is prompted to the

user to confirm that they want to perform the action.

Heuristic 4.

The menu items do follow platform conventions, e.g. the File menu being the leftmost menu item

and the Help item being the rightmost.

Heuristic 5.

Errors can occur in the program when the list size is changed to a size that is smaller than the

amount of files in the list. An example of this is if there are three items in the list and the user puts

the size at two. Error handling will be dealt by a popup box telling the user that it is not allowed.

This is standard practice and is considered a ‘good’ error message.

Heuristic 6.

The recognition rather than recall heuristic is adhered to in this design, as icons are used. This

makes it easier for the user to remember what they need to do to perform a certain task.

Heuristic 7.

This heuristic is not applicable in this system as the system is relatively simple to use and contains

very little to remember.

Page 57: File Handler program

- 57 -

Heuristic 8.

This design is very minimalist, and is designed to be easy to use.

Heuristic 9.

There are no error messages that are too confusing for the user in this design. All messages will be

clear and precise so that the user knows exactly what to do if an error occurs.

Heuristic 10.

A help document should be provided for this system, if time allows. It will be found in the ‘help’ item

in the menu list. Tool tips will also be provided.

Page 58: File Handler program

- 58 -

4.9 PSEUDOCODE – LEVEL ONE

INTRODUCTION

Pseudocode is used for describing algorithms. It “allows the designer to focus on the logic of the algorithm without being distracted by details of language syntax” (Dalbey, 2003). The first level of the pseudocode is very basic as it is intended to give a better idea of program flow.

PSEUDOCODE

1. Load GUI

2. Create new ArrayList to store the files

WHEN USER CLICKS ‘ADD FILE’

1. Load file browser - USER CHOOSES TEXT FILE AND PRESSES OK

2. If ArrayList is full

i. Display message that list is full

3. Else, if the file already exists in the ArrayList (check name to see if it matches existing file)

i. Display message that it already exists

ii. Jump back to start

4. If the file doesn’t exist in ArrayList and list is not full

i. Create new TextFile object

ii. Read character stream from file

iii. Save stream to String variable

iv. Save name to String variable

v. Save TextFile object to ArrayList

vi. Display ArrayList

WHEN USER CLICKS ‘OPEN FILE’

1. Load file browser - USER CHOOSES TEXT FILE AND PRESSES OK

2. If ArrayList is full

Page 59: File Handler program

- 59 -

i. Display message that list is full

3. Else, if the file already exists in the ArrayList (check name to see if it matches existing file)

i. Display message that it already exists

ii. Jump back to start

4. If the file doesn’t exist in ArrayList and list is not full

i. Create new TextFile object

ii. Read character stream from file

iii. Save stream to String variable

iv. Save name to String variable

v. Save TextFile object to ArrayList

vi. Display ArrayList

vii. Get filename and print in on the screen

viii. Get content and print on the screen

ix. Get number of file in ArrayList and print it on the screen

WHEN USER PRESSES ‘REMOVE FILE’

1. Remove object from ArrayList

2. Display ArrayList

WHEN USER PRESSES ‘CLEAR LIST’

1. Remove all object from ArrayList

2. Display ArrayList

WHEN USER PRESSES ‘DISPLAY FILE’

1. Get the TextFile that user wants to display

2. Get filename and print in on the screen

3. Get content and print on the screen

4. Get number of file in ArrayList and print it on the screen

WHEN USER PRESSES ‘NEXT FILE’

Page 60: File Handler program

- 60 -

3. Load next TextFile object in list

4. Get filename and print in GUI label

5. Get content and print in GUI

WHEN USER PRESSES ‘PREVIOUS FILE’

6. Load previous TextFile object in ArrayList

7. Get filename and print in GUI label

8. Get content and print in GUI

WHEN USER PRESSES ‘EXIT’ OR ‘X’ ICON

9. Close application

REFLECTION

This pseudocode makes it easier to begin to think about the Java code for implementing this system.

Page 61: File Handler program

- 61 -

4.10 PSEUDOCODE – LEVEL TWO

INTRODUCTION

The second level of the pseudocode aims to use the syntax of the Java language to describe system processes and artefacts that are produced by the system.

PSEUDOCODE

1. Load GUI

2. Create new FileHandler and instantiate ArrayList to hold TextFile objects

WHEN USER CLICKS ‘ADD FILE’

1. Load FileBrowser with TextFileFilter to only accept .txt files - USER CHOOSES FILE AND

PRESSES OK

a. Error handling – IOException, FileNotFoundException

b. Display message in GUI that error occurred

c. Reload FileBrowser

d. Else, if the file already exists in the ArrayList (use contains() method)

i. Display message that it already exists

ii. Jump back to start

e. If the file doesn’t exist in ArrayList

i. Create new TextFile object by sending in File object

ii. Create FileReader object for that file and assign to variable

iii. Create BufferedReader object for variable

iv. Use readLine() method and save to a string

v. Save string to content variable

vi. Save name (getName() method) to String variable

vii. Catch any errors and increment integer error variable

viii. Save TextFile object to ArrayList

ix. Display ArrayList in GUI

x. Display the number of files in the list

WHEN USER CLICKS ‘OPEN FILE’

1. Load FileBrowser with TextFileFilter to only accept .txt files - USER CHOOSES FILE AND

PRESSES OK

a. Error handling – IOException, FileNotFoundException

b. Display message in GUI that error occurred

Page 62: File Handler program

- 62 -

c. Reload FileBrowser

d. Else, if the file already exists in the ArrayList (use contains() method)

i. Display message that it already exists

ii. Jump back to start

e. If the file doesn’t exist in ArrayList

i. Create new TextFile object by sending in File object

ii. Create FileReader object for that file and assign to variable

iii. Create BufferedReader object for variable

iv. Use readLine() method and save to a string

v. Save string to content variable

vi. Save name (getName() method) to String variable

vii. Catch any errors and increment integer error variable

viii. Save TextFile object to ArrayList

ix. Display ArrayList in GUI

x. Get filename (getName() method of TextFile) and print in on the screen

xi. Get content (getContent() method of TextFile) and print on the screen

xii. Get number of file in ArrayList and print it on the screen

WHEN USER PRESSES ‘REMOVE FILE’

1. Check the ArrayList contains() the TextFile that the user wants to remove

2. If found:

a. Remove TextFile from ArrayList

b. Display list

WHEN USER PRESSES ‘DISPLAY FILE’

3. Get the TextFile that user wants to display using FileHandler getFile() method

4. Get filename (getName() method of TextFile) and print in on the screen

5. Get content (getContent() method of TextFile) and print on the screen

WHEN USER PRESSES ‘NEXT FILE’

6. Load next TextFile object in list (using FileHandler getFile(current+1) method)

7. Get filename (getName() method of TextFile) and print in on the screen

8. Get content (getContent() method of TextFile) and print on the screen

WHEN USER PRESSES ‘PREVIOUS FILE’

9. Load next TextFile object in list (using FileHandler getFile(current-1) method)

10. Get filename (getName() method of TextFile) and print in on the screen

Page 63: File Handler program

- 63 -

11. Get content (getContent() method of TextFile) and print on the screen

WHEN USER PRESSES ‘CLOSE FILE’

12. Remove title from GUI label

13. Remove content from GUI

WHEN USER PRESSES ‘EXIT’ OR ‘X’ ICON

14. Close application

REFLECTION

This pseudocode provides a good foundation upon which entire lines of Java code can be written.

Page 64: File Handler program

- 64 -

4.11 POSSIBLE PROBLEMS AND SOLUTIONS

INTRODUCTION

In this section possible problems will be declared. The solutions highlighted in bold will be the solutions that will be implemented.

PROBLEM LIST

1. The user may try to load files once they have reached the maximum size of the array, i.e. if array

holds 3 file objects.

a. Remove the button / menu item to ‘add a file’ once the limit has been reached.

b. Disable the button / menu item to ‘add a file’ once the limit has been reached.

c. Allow the user to change the amount of files that can be entered (but keep the

default as 3).

d. Display a popup message on the screen to say that the limit has been reached.

2. User may press a button to remove a file but the array list is empty.

a. Do not show the button until a file has been loaded into the array list,

e.g. “FileName1 X remove”.

b. Display a message to the user saying that the action cannot be completed.

c. Disable the button / menu item to ‘remove a file’ once the list is empty

3. The user tries to open a file other than a text file. File Browsers allow any type of file to be

added, but it will be hard to display data by the readLine() method if the file was in different

formats (i.e. image files).

a. Change file browser to only allow .txt files

b. If user enters a non-text file, display message to the user (“Please re-select a file, .txt files

only”). Reload the file browser.

Page 65: File Handler program

- 65 -

4.12 COMMENTED CODE LISTING

INTRODUCTION

There will be three documents in this section. One document is the code for the FileHandler class, another is for the FileHandlerInterface class, and the final document is for the TextFileFilter. The code for the TextFile class has already been provided.

CODE LISTING

TEXTFILEFILTER CLASS

//package declaration package filehandlerproject; //import statements import java.io.File; //main class public class TextFileFilter extends javax.swing.filechooser.FileFilter {

/*method returns true if the File is a directory or a text file this means that both will be shown*/ public boolean accept (File file) //returns true or false {

if (file.isDirectory()) //shows directories {

return true; } if (file.getName().toLowerCase().endsWith(".txt")) //shows .txt files {

return true; } return false;

} //gets the description to put in the JFileChooser box. public String getDescription() {

return "Text File (*.txt)"; }

}

Page 66: File Handler program

- 66 -

FILEHANDLER CLASS

/************************************************ Class FileHandler Description: A class which allows users to display files that they have chosen with a file browser. *************************************************/ package filehandlerproject; //import statements import java.io.*; import java.util.*; public class FileHandler {

ArrayList<TextFile> filelist; //declares an arraylist of TextFile objects int max; //stores the maximum items in list /************************************************************** The constructor of the class. ***************************************************************/ public FileHandler() {

max = 3; //sets max to 3 filelist = new ArrayList<TextFile>(max);

} /************************************************************** returns an integer representing the max items in the list ***************************************************************/ public int getMax() {

return max; } /************************************************************** returns a TextFile in a position in the list ***************************************************************/ public TextFile getTextFile(int i) {

//if the filelist is not empty if (!filelist.isEmpty()) {

return filelist.get(i); //get the file at position i } else return null;

} /************************************************************** returns a TextFile in a position in the list ***************************************************************/ public TextFile nextFile(int i) {

if (!filelist.isEmpty()&&i<filelist.size()) {

return filelist.get(i); } else return null;

} /************************************************************** returns a TextFile in a position in the list ***************************************************************/ public TextFile prevFile(int i)

Page 67: File Handler program

- 67 -

{ if (!filelist.isEmpty()&&i>=0) {

return filelist.get(i); } else return null;

} /************************************************************** returns an ArrayList of TextFiles ***************************************************************/ public ArrayList<TextFile> getList() {

return filelist; } /************************************************************** adds a TextFile to the list by turning a File into a TextFile ***************************************************************/ public String addToList(File fileIn) {

/*creates a new TextFile*/ TextFile newFile = new TextFile(fileIn.getAbsolutePath()); //if the filelist is not full if (filelist.size()<max) {

//if it doesnt exist in the list already if (!filelist.contains(newFile)) {

//add the TextFile to the ArrayList if (filelist.add(newFile)) {

return "!The file " + newFile.getName() + " was added"; } else { return "A problem occured when adding " + newFile.getName(); }

} else {

return "The file is already in the list. Please choose another file."; }

} else {

return "There is no more space in the list."; }

} /************************************************************** removes a TextFile to the list ***************************************************************/ public boolean removeFromList(int in) {

//if the list is not empty if (!filelist.isEmpty()) {

//get the file to remove TextFile fileToRemove = filelist.get(in); //if the file is in the list

Page 68: File Handler program

- 68 -

if (filelist.contains(fileToRemove)) {

//remove the file if (filelist.remove(fileToRemove)) { //file was removed return true; } else {

//file was not removed return false;

} }

} return false;

} /************************************************************** clears the arraylist ***************************************************************/ public void clearList() {

filelist.removeAll(filelist); } /************************************************************** sets the max value to the number the user entered ***************************************************************/ public String setMaxSize(int maxIn) {

//if the user entered the same number (eg 3) as max if (maxIn==max) {

return "The size is already " + maxIn + "."; } else if (filelist.size()<maxIn) //if the size of the list is less than the number entered {

max = maxIn; //sets the max value return "Successfully changed the maximum size of the list.";

} else //does not change the max value {

return "You cannot change the maximum size to " + maxIn + " until you remove some items from the list.";

} }

}

Page 69: File Handler program

- 69 -

FILEHANDLERINTERFACE CLASS

Due to problems exporting code using the Netbeans IDE, the following code will not be colour formatted. In addition to this, the code generated by the Netbeans IDE has been removed, only the code written by the author remains.

/* * Class: FileHandlerInterface.java * * Description: An interface for the FileHandler.java program */ package filehandlerproject; //import statements import java.awt.Cursor; import java.awt.event.WindowEvent; import java.io.File; import java.lang.String; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultListModel; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class FileHandlerInterface extends javax.swing.JFrame {

FileHandler filehandler; //declares a FileHandler object int selected; //declares the item that is selected in the list int listEntries = 0; DefaultListModel model = new DefaultListModel(); //for the items in the JList public static void main(String args[]) {

new FileHandlerInterface().setVisible(true); //create new GUI } /** Creates new form FileHandlerInterface */ public FileHandlerInterface() {

try {

/*sets the appearance of the gui depending on the OS. Note: this system was only checked on Windows*/ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

} catch (ClassNotFoundException ex) { Logger.getLogger(FileHandlerInterface.class.getName()) //adds note to log

Page 70: File Handler program

- 70 -

.log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(FileHandlerInterface.class.getName()) .log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(FileHandlerInterface.class.getName()) .log(Level.SEVERE, null, ex); } catch (UnsupportedLookAndFeelException ex) { Logger.getLogger(FileHandlerInterface.class.getName()) .log(Level.SEVERE, null, ex); } initComponents(); //calls method to display components filehandler = new FileHandler(); changeEnabled(); //changes the buttons which are disabled at startup /*adds a method which changes the value of 'selected' (the item in the list which the user has selected)*/ displayList.addListSelectionListener( new ListSelectionListener() {

public void valueChanged(ListSelectionEvent event) { selected = displayList.getSelectedIndex(); }

} );

} /** displays the items in the list */ public void showList() {

model.removeAllElements(); //first removes all elements for (int i = 0; i < filehandler.getList().size(); i++) //loops for as many items {

Object test2 = (Object) filehandler.getList().get(i).getName(); model.add(i, test2); //adds them to list

} changeEnabled(); //calls method in case some options need to be disabled

} /* changes the Enabled property of some items. If there is only 1 item in list then the next/prev buttons should not be enabled, if there are no items in the list then the remove button should be disabled*/ public void changeEnabled()

Page 71: File Handler program

- 71 -

{ if (filehandler.getList().size()==0) //list is empty {

//disable buttons remButton.setEnabled(false); displayButton.setEnabled(false); prevButton.setEnabled(false); nextButton.setEnabled(false); clearAll.setEnabled(false);

} else //list is not empty {

clearAll.setEnabled(true); remButton.setEnabled(true); displayButton.setEnabled(true);

} if (filehandler.getList().size() < 2) //1 item in list {

nextButton.setEnabled(false); prevButton.setEnabled(false);

} else //more than 1 item {

nextButton.setEnabled(true); prevButton.setEnabled(true);

} } /*** shows a popup box with a text field for the user to enter the size that they want to change the list to****/ public String showChangeDialog() {

//returns a String containing the user input return (String) JOptionPane.showInputDialog(

new JFrame(), "New size of list:", //message in popup box "Change List Size", //title JOptionPane.INFORMATION_MESSAGE, //type of message //getMax() is called to get the current max value. it becomes the default //value for the text box null, null, filehandler.getMax() );

} /**shows the result of showChangeDialog after calling it*/ public String showMsg() {

String maxSizeString = showChangeDialog(); //calls method to show dialog box //if string is empty if (maxSizeString.trim().equals(null)||maxSizeString.trim().equals("")) {

JOptionPane.showMessageDialog( new JFrame(), "Please enter a number", "Error", //title

JOptionPane.ERROR_MESSAGE); //type of message

Page 72: File Handler program

- 72 -

return null; } try {

Integer.parseInt(maxSizeString); //checks if String entered was a number } catch (NumberFormatException e) {

JOptionPane.showMessageDialog( new JFrame(), "Please enter a number", "Error", JOptionPane.ERROR_MESSAGE); return null;

} //if a number more than 100 was entered if (Integer.parseInt(maxSizeString) > 100) {

JOptionPane.showMessageDialog(new JFrame(), "Please enter a number less than 100", "Error", JOptionPane.ERROR_MESSAGE); return null;

} return maxSizeString; //returns String result

} /*when the display button is pressed*/ private void displayButtonMouseReleased(java.awt.event.MouseEvent evt) { if (displayButton.isEnabled()) {

/*the remove command outputs a message on the screen until another button is pushed*/ remResult.setText(" "); if (selected >= 0) {

//gets the file at the position selected TextFile testFile = filehandler.getTextFile(selected);

if (testFile != null) //if the file is found {

//sets the number displayed to the correct position in list numLabel.setText((displayList.getSelectedIndex() + 1) + "/" + filehandler.getList().size()); //outputs the content of the file displayArea.setText(testFile.getContent()); //outputs the name of the file titleLabel.setText("Filename: " + testFile.getName());

}

Page 73: File Handler program

- 73 -

else {

//error handling - user is informed of any errors displayArea.setText("No file found");

} }

} } /*when the "about" item in the list is pressed*/ private void menuAbout2MouseReleased(java.awt.event.MouseEvent evt) {

/*the remove command outputs a message on the screen until another button is pushed*/ remResult.setText(" "); JOptionPane.showMessageDialog(

new JFrame(), "Written and developed by Carrie Hall" + "\n" + "September - November 2008" + " \n " + "All rights reserved", "About File Viewer", JOptionPane.INFORMATION_MESSAGE //type of message );

} /*when the "change size" item in the list is pressed*/ private void changeSizeMouseReleased(java.awt.event.MouseEvent evt) {

/*the remove command outputs a message on the screen until another button is pushed*/ remResult.setText(" "); //calls the method to ask the user for the new size of the list String result = showMsg(); if (result == null || result.equals("")) {

//calls this method again as the result either null or not a number changeSizeMouseReleased(evt);

} else //result was an integer {

/*turns the String that the user entered into an integer (error checking done in method)*/ int resultInt = Integer.parseInt(result); //changes max size to this number String success = filehandler.setMaxSize(resultInt);

Page 74: File Handler program

- 74 -

//changes the display saying how many files in the list. filesLabel.setText("Files: " + filehandler.getList().size() + "/" + filehandler.getMax()); //outputs message that list size changed OK JOptionPane.showMessageDialog(new JFrame(), success, "Information", JOptionPane.INFORMATION_MESSAGE);

} }

private void addButtonMouseReleased(java.awt.event.MouseEvent evt) {

remResult.setText(" "); //fileBrowser only accepts files, not files and directories fileBrowser.setFileSelectionMode(JFileChooser.FILES_ONLY); //makes the fileBrowser only accept Text Files fileBrowser.addChoosableFileFilter(new TextFileFilter()); int result = fileBrowser.showOpenDialog(jLabel1); //shows the JFileChooser if (result == JFileChooser.CANCEL_OPTION) {

fileBrowser.cancelSelection(); //cancel option } else {

if (filehandler.getList().size() != filehandler.getMax()) //there is still room in the list {

//the remove command outputs a message on the screen until another button is pushed remResult.setText(" "); //changes the cursor to an hourglass setCursor(new Cursor(Cursor.WAIT_CURSOR)); try {

Thread.sleep(400); //halts the program so the user can see the hourglass } catch (InterruptedException ex) {

Logger.getLogger(FileHandlerInterface.class.getName()) .log(Level.SEVERE, null, ex); //adds to log

} File filename = fileBrowser.getSelectedFile(); //gets File that the user chose String resultString = filehandler.addToList(filename); //adds file to list if (resultString.startsWith("!")) //if the file was added successfully {

showList(); //redraws the list changeEnabled(); //calls method in case some buttons need to be enabled

Page 75: File Handler program

- 75 -

/*now the number of files in list and the number of the file being displayed needs to change. if the file that was being displayed was previously 2/3 for example it now needs to be changed to 2/4. the amount of files in the list needs to increase by one*/ int position = 0; for (int j = 0; j < filehandler.getList().size(); j++) {

if (titleLabel.getText().equals("Filename: " + model.get(j).toString())) {

position = j; //the position of the displayed file }

}

if (!titleLabel.getText().equals("Filename: none selected")) {

//changes the number of the file that was being displayed numLabel.setText((position + 1) + "/" + filehandler.getList().size());

}

if (position <= 0) { //if no file was selected previously, or there were no files previously position = 0; }

//changes the selected item in the list displayList.addSelectionInterval(position, position); //changes the label showing how many files are in the list filesLabel.setText("Files: " + (filehandler.getList().size()) + "/" + filehandler.getMax()); //changes the cursor back to the default setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); //increases the variable to the last item in the list listEntries++; }

else //file could not be added {

/*shows a dialog why the file could not be added (eg file in list already) asks user if they want to try another file*/ int option = JOptionPane.showConfirmDialog(new JFrame(),

resultString, "Information", JOptionPane.OK_CANCEL_OPTION);

//user pressed ok, fileChooser is loaded again if (option == 0) {

addButtonMouseReleased(evt); //calls this method again } //changes cursor back to the default setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

}

Page 76: File Handler program

- 76 -

} else //list is full {

JOptionPane.showMessageDialog(new JFrame(), "The list is full, please increase the list size.", "Information", JOptionPane.INFORMATION_MESSAGE);

} }

}

private void nextButtonMouseReleased(java.awt.event.MouseEvent evt) { if (nextButton.isEnabled()) //only if button is enabled {

remResult.setText(" "); if (!titleLabel.getText().equals("Filename: none selected")) //if file is being displayed {

selected += 1; //the selected item is increased if (selected >= filehandler.getList().size()) {

selected = 0; //goes back to the first item in list if the end has been reached } //gets file at next selected position TextFile fileRequest = filehandler.nextFile(selected); if (fileRequest != null) //if file exists {

displayList.setSelectedIndex(selected); //sets next item in list /*changes number of file being displayed*/ numLabel.setText((displayList.getSelectedIndex() + 1) + "/" + filehandler.getList().size()); //changes title to next title titleLabel.setText("Filename: " + fileRequest.getName()); //changes content to next files content displayArea.setText(fileRequest.getContent());

} }

} }

private void prevButtonMouseReleased(java.awt.event.MouseEvent evt) { if (prevButton.isEnabled()) //if action is available {

remResult.setText(" "); if (!titleLabel.getText().equals("Filename: none selected")) //if file is being displayed {

selected -= 1; //the selected item is decreased if (selected < 0) //if beginning of the file is reached {

Page 77: File Handler program

- 77 -

selected = filehandler.getList().size() - 1; //change to last item in list } //gets file at next selected position TextFile fileRequest = filehandler.prevFile(selected); if (fileRequest != null) //if file exists {

displayList.setSelectedIndex(selected); //sets next item in list

/*changes number of file being displayed*/ numLabel.setText((displayList.getSelectedIndex() + 1) + "/" + filehandler.getList().size()); //changes title to previous title titleLabel.setText("Filename: " + fileRequest.getName()); //changes content to previous files content displayArea.setText(fileRequest.getContent());

} }

} }

private void menuOpenMouseReleased(java.awt.event.MouseEvent evt) { //fileBrowser only accepts files, not files and directories fileBrowser.setFileSelectionMode(JFileChooser.FILES_ONLY); //makes the fileBrowser only accept Text Files fileBrowser.addChoosableFileFilter(new TextFileFilter()); //shows the JFileChooser int result = fileBrowser.showOpenDialog(jLabel1); if (result == JFileChooser.CANCEL_OPTION) {

fileBrowser.cancelSelection(); //cancel option } else {

if (filehandler.getList().size() != filehandler.getMax()) //there is still room in the list {

/*the remove command outputs a message on the screen until another button is pushed*/ remResult.setText(" "); //changes the cursor to an hourglass setCursor(new Cursor(Cursor.WAIT_CURSOR)); try {

Thread.sleep(400); //halts the program so the user can see the hourglass } catch (InterruptedException ex) {

Page 78: File Handler program

- 78 -

Logger.getLogger(FileHandlerInterface.class.getName()) .log(Level.SEVERE, null, ex); //adds to log

} File filename = fileBrowser.getSelectedFile(); //gets File that the user chose String resultString = filehandler.addToList(filename); //adds file to list if (resultString.startsWith("!")) //if the file was added successfully {

/*changes the amount of files in the list*/ numLabel.setText((listEntries + 1) + "/" + filehandler.getList().size()); /*gets the content of the last added file and displays it*/ displayArea.setText(filehandler.getTextFile(listEntries).getContent()); /*gets the title of the last added file and displays it*/ titleLabel.setText("Filename: " + filehandler.getTextFile(listEntries).getName()); showList(); //redraws the list changeEnabled(); //changes the enabled status of buttons if needed /*now the number of files in list and the number of the file being displayed needs to change. if the file that was being displayed was previously 2/3 for example it now needs to be changed to 2/4. the amount of files in the list needs to increase by one*/ int position = 0; for (int j = 0; j < filehandler.getList().size(); j++) {

if (titleLabel.getText().equals("Filename: " + model.get(j).toString())) {

position = j; //the position of the displayed file }

} /*changes the number of the file being displayed*/ numLabel.setText((position + 1) + "/" + filehandler.getList().size()); //selects the item in the list that is being displayed displayList.addSelectionInterval(position, position); //changes the amount of files filesLabel.setText("Files: " + (filehandler.getList().size())+ "/" + filehandler.getMax()); //sets the cursor back to default setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); //increases the count for the last entry in the list listEntries++;

} else //if the file was not added successfully {

/*prompts the user to see if they want to try opening another file*/ int option = JOptionPane.showConfirmDialog(new JFrame(),

resultString, "Information", JOptionPane.OK_CANCEL_OPTION); if (option == 0) //user pressed yes

Page 79: File Handler program

- 79 -

{ menuAddFile1MousePressed(evt);

} if (option == 2) //user pressed cancel { } //changes cursor back to default setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); }

} else //list is full { //displays message to user JOptionPane.showMessageDialog(new JFrame(),

"The list is full, please increase the list size.", "Information", JOptionPane.INFORMATION_MESSAGE);

} }

}

private void openButtonMouseReleased(java.awt.event.MouseEvent evt) { //fileBrowser only accepts files, not files and directories fileBrowser.setFileSelectionMode(JFileChooser.FILES_ONLY); //makes the fileBrowser only accept Text Files fileBrowser.addChoosableFileFilter(new TextFileFilter()); //shows the JFileChooser int result = fileBrowser.showOpenDialog(jLabel1); if (result == JFileChooser.CANCEL_OPTION) {

fileBrowser.cancelSelection(); //cancel option } else {

if (filehandler.getList().size() != filehandler.getMax()) //there is still room in the list {

/*the remove command outputs a message on the screen until another button is pushed*/ remResult.setText(" "); //changes the cursor to an hourglass setCursor(new Cursor(Cursor.WAIT_CURSOR)); try {

Thread.sleep(400); //halts the program so the user can see the hourglass } catch (InterruptedException ex) {

Logger.getLogger(FileHandlerInterface.class.getName()) .log(Level.SEVERE, null, ex); //adds to log

}

Page 80: File Handler program

- 80 -

File filename = fileBrowser.getSelectedFile(); //gets File that the user chose String resultString = filehandler.addToList(filename); //adds file to list if (resultString.startsWith("!")) //if the file was added successfully {

/*changes the amount of files in the list*/ numLabel.setText((listEntries + 1) + "/" + filehandler.getList().size()); /*gets the content of the last added file and displays it*/ displayArea.setText(filehandler.getTextFile(listEntries).getContent()); /*gets the title of the last added file and displays it*/ titleLabel.setText("Filename: " + filehandler.getTextFile(listEntries).getName()); showList(); //redraws the list changeEnabled(); //changes the enabled status of buttons if needed /*now the number of files in list and the number of the file being displayed needs to change. if the file that was being displayed was previously 2/3 for example it now needs to be changed to 2/4. the amount of files in the list needs to increase by one*/ int position = 0; for (int j = 0; j < filehandler.getList().size(); j++) {

if (titleLabel.getText().equals("Filename: " + model.get(j).toString())) {

position = j; //the position of the displayed file }

} /*changes the number of the file being displayed*/ numLabel.setText((position + 1) + "/" + filehandler.getList().size()); //selects the item in the list that is being displayed displayList.addSelectionInterval(position, position); //changes the amount of files filesLabel.setText("Files: " + (filehandler.getList().size())+ "/" + filehandler.getMax()); //sets the cursor back to default setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); //increases the count for the last entry in the list listEntries++;

} else //if the file was not added successfully {

/*prompts the user to see if they want to try opening another file*/ int option = JOptionPane.showConfirmDialog(new JFrame(),

resultString, "Information", JOptionPane.OK_CANCEL_OPTION); if (option == 0) //user pressed yes {

menuAddFile1MousePressed(evt); } if (option == 2) //user pressed cancel

Page 81: File Handler program

- 81 -

{ } //changes cursor back to default setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); }

} else //list is full { //displays message to user JOptionPane.showMessageDialog(new JFrame(),

"The list is full, please increase the list size.", "Information", JOptionPane.INFORMATION_MESSAGE);

} }

}

private void clearAllMouseReleased(java.awt.event.MouseEvent evt) { if (clearAll.isEnabled()) //if fucntion is available {

//prompt user to see if they want to delete all int option = JOptionPane.showConfirmDialog(new JFrame(),

"Are you sure you want to clear the list?", "Confirm", JOptionPane.OK_CANCEL_OPTION);

if (option == 0) //user pressed ok {

filehandler.clearList(); //clears the ArrayList of TextFiles showList(); //redraws the list //removes the file title from the display(if any) titleLabel.setText("Filename: none selected"); //removes the file content from the display(if any) displayArea.setText("Please choose a file to display"); //shows a message that the list was cleared remResult.setText("** List cleared"); //removes the position number from the display(if any) numLabel.setText(" "); //calls method to disable buttons changeEnabled(); //changes the display of how many files there are filesLabel.setText("Files: " + (filehandler.getList().size()) + "/" + filehandler.getMax()); //sets the last item in the list to 0, ie there are no files. listEntries = 0;

} }

} private void menuCloseMouseReleased(java.awt.event.MouseEvent evt) {

Page 82: File Handler program

- 82 -

//prompts the user that they want to close int option = JOptionPane.showConfirmDialog(new JFrame(),

"Are you sure you want to exit the program?", "Confirm Exit", JOptionPane.OK_CANCEL_OPTION);

//user presses yes if (option == 0) {

processEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); //close program }

}

private void remButtonMouseReleased(java.awt.event.MouseEvent evt) { if (remButton.isEnabled()) //if there are items in the list {

//outputs message to user asking if they want to delete file //ensures they do not accidentally delete wanted files int option = JOptionPane.showConfirmDialog(new JFrame(),

"Are you sure you want to remove this file from the list?", "Confirm File Removal", JOptionPane.OK_CANCEL_OPTION);

if (option == 0) //they pressed yes to deleting the file {

if (filehandler.removeFromList(selected)) //if the file was removed successfully {

/*changes the display of how many files there are*/ filesLabel.setText("Files: " + (filehandler.getList().size()) + "/" + filehandler.getMax());

//outputs message that file was removed remResult.setText("**The file was removed."); //the position of the last entry in list is decreased listEntries--;

//the list is shown again showList(); /*now the file that is being displayed in the text area needs to be checked. If a file was being displayed that has been removed, then the output will need to be cleared. Else, a different file is being displayed so that will need to stay in the display area*/ boolean inList = false; //set to false initially to say its not in the list int position = 0; //position of the displayed item in list //loops through items in the list for (int j = 0; j < filehandler.getList().size(); j++) {

/*if the file that is being displayed IS found in the list. this is checked by comparing the name of each item in the list with the name being displayed*/ if (titleLabel.getText().equals("Filename: "+ filehandler.getTextFile(j).getName()))

Page 83: File Handler program

- 83 -

{ position = j + 1; inList = true;

} } /*the file being displayed is no longer in the list*/ if (!inList) {

titleLabel.setText("Filename: none selected"); displayArea.setText("Please choose a file to display"); numLabel.setText(" "); //selects the first item in the list to ensure that an item is always selected displayList.addSelectionInterval(0, 0);

} else //the file displayed is in the list and the selected item needs reselecting {

//changes the text in the display to show what file is being displayed numLabel.setText(position + "/" + filehandler.getList().size()); //changes the selected item to the one that the user had previously chosen //to display displayList.addSelectionInterval(position - 1, position - 1);

} } else //file was not removed {

displayArea.setText("Please choose a file to display"); remResult.setText("**There was a problem removing this file");

} } /*if there is now less than 2 items in the list then some buttons will be disabled*/ changeEnabled();

}

}

Page 84: File Handler program

- 84 -

4.13 TESTING (SOFTWARE VALIDATION)

INTRODUCTION

Software validation comprises of three distinct stages. Component testing, System testing and Acceptance testing.

A diagrammatical representation of the three stages is shown in Figure 4.

FIGURE 4

Page 85: File Handler program

- 85 -

4.14 FILEHANDLER COMPONENT TEST

TEST HARNESS CODE

A test harness has been written to test the methods of this class. The code is printed below package filehandlerproject; public class FileHandlerTester {

public static void main(String args[]) {

TextFile testFile1 = new TextFile("7179881TextAndSpCh.txt"); TextFile testFile2 = new TextFile("7179881TextAndData.txt"); TextFile testFile3 = new TextFile("7179881TextPlain.txt"); TextFile testFile4 = new TextFile("test.txt"); FileHandler filehandler = new FileHandler(); /*Test one: Test the getMax() method*/ System.out.println("Test 1 - getMax: " + filehandler.getMax()); /*Test two: Test the addToList() method*/ String addResult1 = filehandler.addToList(testFile1); System.out.println("Test 2 - addToList: " + addResult1); /*Test three: Test the addToList() method*/ String addResult2 = filehandler.addToList(testFile1); System.out.println("Test 3 - addToList: " + addResult2); filehandler.addToList(testFile2); filehandler.addToList(testFile3); /*Test four: Test the addToList() method*/ String addResult3 = filehandler.addToList(testFile4); System.out.println("Test 4 - addToList: " + addResult3); /*Test five: Test the removeFromList() method*/ boolean remResult1 = filehandler.removeFromList(0); System.out.println("Test 5 - removeFromList: " + remResult1); /*Test six: Test the removeFromList() method*/ System.out.println("Test 5 & 6 - show that item has been removed and the getList() method: " + remResult1); for (int i = 0 ; i < filehandler.getList().size() ; i++) { System.out.print(filehandler.getTextFile(i).toString()); } /*Test seven: Test the setMaxSize() method*/ String maxSize1 = filehandler.setMaxSize(3); System.out.println("Test 7 - setMaxSize: " + maxSize1); /*Test eight: Test the setMaxSize() method*/ String maxSize2 = filehandler.setMaxSize(0);

Page 86: File Handler program

- 86 -

System.out.println("Test 8 - setMaxSize: " + maxSize2); /*Test nine: Test the setMaxSize() method*/ String maxSize3 = filehandler.setMaxSize(5); System.out.println("Test 9 - setMaxSize: " + maxSize3); /*Test ten: Test the clearList() method*/ filehandler.clearList(); System.out.println("Test 10 - list cleared. Begin output of list"); for (int i = 0 ; i < filehandler.getList().size() ; i++) {

System.out.print(filehandler.getTextFile(i).toString()); } System.out.println("Test 10 - end of list"); filehandler.addToList(testFile1); filehandler.addToList(testFile2); filehandler.addToList(testFile3); int k = 1; /*Test eleven - test the getTextFile method*/ System.out.print(filehandler.getTextFile(k).getName()); /*Test twelve - test the nextFile method*/ System.out.print(filehandler.nextFile(k+1).getName()); /*Test thirteen - test the prevFile method*/ System.out.print(filehandler.prevFile(k-1).getName()); k = 2; /*Test fourteen - test the nextFile method*/ TextFile isNext = filehandler.nextFile(k+1); if (isNext==null) {

System.out.print("Test fourteen success - no file was found"); } else { System.out.print("Test fourteen failed - a file was found"); } k=0; /*Test fifteen - test the prevFile method*/ TextFile isPrev = filehandler.nextFile(k-1); if (isNext==null) {

System.out.print("Test fifteen success - no file was found"); } else {

System.out.print("Test fifteen failed - a file was found"); }

} }

Page 87: File Handler program

- 87 -

TABLE OF RESULTS

Now the class will be ran, and the results marked down in the table below.

Test Number 1 2 3 4 5 Expected Result 3 !The file

7179881TextAndSpCh.txt was added

The file is already in the

list. Please choose another

file.

There is no more space in the list.

True

Actual Result 3 !The file 7179881TextAndSpCh.txt

was added

The file is already in the

list. Please choose another

file.

There is no more space in the list.

True

Pass / Fail Pass Pass Pass Pass Pass Test Number 6 7 8 9 10

Expected Result Should show name and content of

7179881TextAndData.txt and

7179881TextPlain.txt

The size is already 3

You cannot change the

maximum size to 0 until you

remove some items from the

list.

Successfully changed the

maximum size of the list.

Test 10 - list cleared. Begin output of list

Test 10 - end of list

Actual Result shows name and content of

7179881TextAndData.txt and

7179881TextPlain.txt

Successfully changed the

maximum size of the list.

You cannot change the

maximum size to 0 until you

remove some items from the

list.

Successfully changed the

maximum size of the list.

Test 10 - list cleared. Begin output of list

Test 10 - end of list

Pass / Fail Pass Fail Pass Pass Pass Test Number 11 12 13 14 15

Expected Result 7179881TextAndData.txt

7179881TextPlain.txt

7179881TextAndSpCh.txt

Test 14 success - no file was found

Test 15 success - no file was found

Actual Result 7179881TextAndData.txt

7179881TextPlain.txt

7179881TextAndSpCh.txt

Test 14 success - no file was found

Test 15 success - no file was found

Pass / Fail Pass Pass Pass Pass Pass

REFLECTION

Test 7 failed so debugging is needed to find out why and where the error occured. The test was designed to output a message that the maximum size of the list is already the number that was put in. The maximum size of the list is set to 3 at the beginning of the program, so when ‘3’ is sent into the changeListSize() method it should return a string saying “The size is already 3”.

Page 88: File Handler program

- 88 -

4.15 DEFECT TESTING / DEBUGGING

INTRODUCTION

Debugging “reveals program defects that must be removed from the program” (Sommerville, 2007). According to Somerville, there is one main difference between defect testing and debugging; namely that testing establishes the existence of defects, whereas debugging is concerned with locating and correcting these defects.

The stages of debugging are shown below.

DEBUG FILEHANDLER CLASS

The testing stage has uncovered an error in the FileHandler class, specifically in the public String setMaxSize() method below (comments removed).

public String setMaxSize(int maxIn) {

if (filelist.size()<maxIn) {

max = maxIn; return "Successfully changed the maximum size of the list.";

} else if (maxIn==max) {

return "The size is already " + maxIn + "."; } else {

return "You cannot change the maximum size to " + maxIn + " until you remove some items from the list.";

} }

Although there is no syntax error19

19 Syntax error: An error found during compilation of the file, usually due to a misspelling of a key word in a programming language.

, there is a logic error in the program. This means that the program does not contain any obvious errors to the system, but that the system does not perform as it should.

The problem here lies with the ‘if..else’ statements. It first checks to see if the size of the ArrayList is smaller than the number that the user wants to change the maximum size to. If it is, then the maximum value can be changed. However, what the program should do first is check to see if the maximum number in the list matches the number sent into the method.

Page 89: File Handler program

- 89 -

Here we can see the corrected code (comments removed) public String setMaxSize(int maxIn) {

if (maxIn==max) {

return "The size is already " + maxIn + "."; } else if (filelist.size()<maxIn) {

max = maxIn; return "Successfully changed the maximum size of the list.";

} else {

return "You cannot change the maximum size to " + maxIn + " until you remove some items from the list.";

} }

TESTING

Now the test will be re-run and results checked to see if the error has been resolved.

REFLECTION

The component FileHandler has now passed its component testing.

Test Number 7 Expected Result The size is

already 3

Actual Result The size is already 3

Pass / Fail Pass

Page 90: File Handler program

- 90 -

4.16 ACCEPTANCE TESTING

INTRODUCTION

The requirements specification will be checked against the output of the program to ensure that it meets the specification.

REQUIREMENTS SPECIFICATION

Level Specification Fulfils requirement? 1 The system must display the file name of the file in the display area YES 1 The system must display the file content of the file in the display area YES 1 The user must be given a choice of what file to load from a file

browser YES

1 The system should provide error handling in case a file cannot be loaded

YES

1 The user should be informed of any errors in the program YES 2 The system should respond quickly (within 1 second) to user

commands YES

1 The user should be able to close the program YES 1 The user should be able to add a file to the list YES 1 The user should be able to remove a file from the list YES 2 The user should be able to clear the list YES 3 The user should be able to change the maximum size of the list YES 1 The system should ensure that the list size does not go below the

number of items currently in the list YES

1 The system should ensure that the only files that can be loaded into the program are text files

YES

2 The user should be able to open a file directly YES 3 The system should give the user help using tooltips YES 2 The system should contain an error log YES

REFLECTION

The system meets all specifications, so the black box testing is complete.

Page 91: File Handler program

- 91 -

5. SECTION THREE

INTRODUCTION

Software validation comprises of three distinct stages. Component testing, System testing and Acceptance testing.

A diagrammatical representation of the three stages is shown in Figure 5.

FIGURE 5

Component testing and acceptance testing have been completed for all classes.

Page 92: File Handler program

- 92 -

5.1 SYSTEM TESTING

INTRODUCTION

In this section, test data will be used to run the program to ensure that the system fulfils the requirements set out in the specification.

TEST RUN ONE

DESCRIPTION AND TEST DATA

In the first example a file will be opened directly from the ‘open file’ button, to check that the file displays correctly. It should show a file name, the files content, and number should be “1/1”. The file should be added to the list and the number of items in the list should change to “1/3”. The “next”, “display” and “previous” buttons should still be disabled as there is only one item in the list. The “remove” and “clear list” buttons should become enabled. The system should automatically highlight the first item in the list (7179881TextAndSpCh.txt) to ensure that an item is always selected.

OUTPUT

Before:

Page 93: File Handler program

- 93 -

After:

CONCLUSION

The test run was a success.

Page 94: File Handler program

- 94 -

TEST RUN TWO

DESCRIPTION AND TEST DATA

In the second example a file will be added to the list. It should not change the opened file name or the files content, but the number of the file displayed should change to “1/2”. The first file should still be selected in the list. The new file should be added to the list and the number of items in the list should change to “2/3”. The “next” and “previous” buttons should become enabled.

OUTPUT

Before:

Page 95: File Handler program

- 95 -

After:

CONCLUSION

The test run was a success.

Page 96: File Handler program

- 96 -

TEST RUN THREE

DESCRIPTION AND TEST DATA

In the third example a file (7179881TextAndData.txt) will be removed from the list. The file should be removed from display and the ‘next’ and ‘previous’ buttons should be disabled. The system should prompt to ensure the user did intend to delete the file. The amount of files in the list should reduce to 1/3. A message should appear in a label to say the file was removed. The system should automatically highlight the first item in the list (7179881TextAndSpCh.txt) to ensure that an item is always selected.

OUTPUT

Before:

After:

Page 97: File Handler program

- 97 -

CONCLUSION

The test run was a success.

Page 98: File Handler program

- 98 -

TEST RUN FOUR

DESCRIPTION AND TEST DATA

In the fourth example the list size will be increased. The system should prompt the user to enter a number. The number that is entered by default should be the current size of the list (3). The system should change the amount of files from 1/3 to 1/5 after displaying a successful message to the user.

OUTPUT

Before:

After:

CONCLUSION

The test run was a success.

Page 99: File Handler program

- 99 -

TEST RUN FIVE

DESCRIPTION AND TEST DATA

In the fifth example the list size will try to be increased. The system should prompt the user to enter a number, which will be left blank. The system should inform the user that a number needs to be entered, and then show the dialog box to change the size again.

OUTPUT

Before:

After:

CONCLUSION

The test run was a success.

Page 100: File Handler program

- 100 -

TEST RUN SIX

DESCRIPTION AND TEST DATA

In the sixth example the list size will try to be increased. The system should prompt the user to enter a number, but a string of characters will be entered. The system should inform the user that a number needs to be entered, and then show the dialog box to change the size again.

OUTPUT

Before:

After:

CONCLUSION

The test run was a success.

Page 101: File Handler program

- 101 -

TEST RUN SEVEN

DESCRIPTION AND TEST DATA

In the seventh example the ‘about’ menu item will be pressed. It should show a dialog describing the program.

OUTPUT

Before:

After:

CONCLUSION

The test run was a success.

Page 102: File Handler program

- 102 -

TEST RUN EIGHT

DESCRIPTION AND TEST DATA

In the eighth example a file that is already in the list will try to be added. The system should display a message that it is already in the list, and show two options to choose another file or to cancel.

OUTPUT

Before:

After:

CONCLUSION

The test run was a success.

Page 103: File Handler program

- 103 -

TEST RUN NINE

DESCRIPTION AND TEST DATA

In the ninth example a file will try to be added when the list is full. The system should display a message that it the list is full

OUTPUT

Before:

After:

CONCLUSION

The test run was a success.

Page 104: File Handler program

- 104 -

TEST RUN TEN

DESCRIPTION AND TEST DATA

In the tenth example the list will be cleared. The system should display a prompt message to confirm that the user does want to remove all files. The system should show a message that the list was cleared.

OUTPUT

Before:

After:

Page 105: File Handler program

- 105 -

CONCLUSION

The test run was a success.

Page 106: File Handler program

- 106 -

6. REFLECTION

Overall, the project was a success. The system performs all of the functions that were set out in the requirements, and it has been designed to be error-free and easy to use.

One problem that was faced during the project was lack of knowledge about certain graphical Java functions. Time was spent researching about different ways to implement functions which greatly added to the time spent on the project. However, thorough research has led to a more effective and efficient system.

Another problem that occurred in the execution of the project was due to time constraints. A help guide for the user was not actually able to be produced in time, which would have been essential had the system been designed to give to an end-user.

The other feature that was not implemented fully was a test log. Although a test log exists, it only enters information when errors occur, rather than giving a full description of the program running.

An aspect of the system that was both rewarding and interesting was the test harnesses. They made it easy to test the components of the system rather than taking a ‘hacking’ approach until all of the bugs were resolved.

Prototypes also made the system easier to test. After the first prototype had been developed, it was tested. That meant that the second iteration of the program had a strong foundation upon which to build and develop new ideas.

A particular issue to note about the project was that it emphasized how important it is to plan and design, before programming. It is easy at the beginning to have a ‘hacker’ mentality which may lead to problems in the future. This project was methodically planned, although at times new ideas were implemented as they were discovered. A good example of this was the “about” item in the help menu.

UML was used throughout the program. At the beginning of the project it was possible just to take the designs created on paper, and code it directly into the IDE.

Overall, I learned a great deal from developing and designing this project. In addition to the actual Java code which I have learned, I have learned the importance of planning and design, and how to effectively use UML to make designing easier.

Page 107: File Handler program

- 107 -

7. GLOSSARY

Actor: The users of the system

Array: A container to store a collection of items of the same type (Charatan & Kans, 2006)

Exception: An event that occurs during the life of a program which could cause that program to behave unreliably.

Integer: A positive or negative whole number or zero.

Method: “Performs a single, well-defined task” by implementing a particular set of instructions

Modularity: Where large software systems are decomposed into smaller, more independent components.

Multiplicity: an indication of how many objects may fill the property (Fowler, 2004).

Object: An instantiation of a class

Prototype: A less formal experimental development process of a proposed application for the purpose of demonstrating some or all of its functional capabilities (California State University, 2005).

Scenario: a sequence of steps describing an interaction between a user and a system (Fowler, 2004)

Scenario: a sequence of steps describing an interaction between a user and a system (Fowler, 2004)

Scope Management: the processes required to ensure that the project includes all the work required, and only the work required, to complete the project successfully. (Project Smart, 2008)

Wrapper: Converts a primitive data type, e.g. int, to a class, e.g. Integer (Charatan & Kans, 2006)

Page 108: File Handler program

- 108 -

8. BIBLIOGRAPHY

ACM. (2005, January/February). A Tale of Two Tutorials: A Cognitive Approach to Interactive System Design and Interaction Design Meets Agility. Interactions Magazine , pp. 49-51.

Benyon, D., Turner, P., & Turner, S. (2005). Designing Interactive Systems. Mateu Cromo: Pearson Education Limited.

California State University. (2005, 12 1). Information Technology - Glossary. Retrieved November 7, 2008, from California State University, Monterey Bay: http://www.csumb.edu/site/x7101.xml

Charatan, Q., & Kans, A. (2006). Java in Two Semesters. Berkshire: McGraw Hill.

Dalbey, J. (2003). Psuedocode Standard. Retrieved October 25, 2008, from Cal Poly State University: http://users.csc.calpoly.edu/~jdalbey/SWE/pdl_std.html

Davis, A. M. (1993). Software Requirements: Objects, Functions and States. NJ: Prentice Hall.

Deitel, H. M., & Deitel, P. J. (2002). Advanced Java 2 Platform. New Jersey: Prentice-Hall.

Deitel, H. M., & Deitel, P. J. (2005). Java: How to Program. New Jersey: Prentice-Hall.

Demo Source and Support. (2008). JFileChooser: addChoosableFileFilter(FileFilter filter). Retrieved August 15, 2008, from www.java2s.com: http://www.java2s.com/Code/JavaAPI/javax.swing/JFileChooseraddChoosableFileFilterFileFilterfilter.htm

Demo Source and Support. (2003, January 1). www.java2s.com. Retrieved November 1, 2008, from Java 2's: http://www.java2s.com/Code/Java/Swing-JFC/Informationdialogwithcustomizedlogo.htm

Dennis, A., Wixom, B. H., & Tegarden, D. (2005). Systems Analysis and Design with UML Version 2.0. Minion: Leyh Publishing.

FIRM. (2005). From Waterfall to Evolutionary Development (Evo). INCOSE.

Fowler, M. (2004). UML Distilled. Addison-Wesley.

Heim, S. (2008). The Resonant Interface. Boston: Pearson Education.

Horstmann. (2008). Big Java. Hoboken: John Wiley & Sons.

Neville, R. (2008). Class Responsibilities and Collaborators. Manchester: University Of Manchester.

Neville, R. (2008). Context Diagrams. Manchester: University Of Manchester.

Neville, R. (2008). Feature List. Manchester: University Of Manchester.

O'Reilly. (2002). Java In A Nutshell. California: O'Reilly & Associates.

Project Smart. (2008, January 5). Scope Management. Retrieved November 7, 2008, from Project Smart : http://www.projectsmart.co.uk/scope-management.html

Rowe, S. (2008, 4 28). Test Harness Basics. Retrieved November 6, 2008, from Testing Reflections: http://www.testingreflections.com/node/view/3655

Page 109: File Handler program

- 109 -

Sommerville, I. (2007). Software Engineering. Essex: Pearson Education Limited.

Stevens, R. (2008). Task Analysis. CS2341 Lecture Notes . Manchester: University Of Manchester.

Sun Microsystems. (2001). Class: File. Retrieved November 7, 2008, from java.sun.com: http://java.sun.com/j2se/1.3/docs/api/java/io/File.html

Sun Microsystems. (2008, February 14). How to use File Choosers. Retrieved October 26, 2008, from java.sun.com: http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html

Taylor, A. (2000). IT projects: sink or swim. Computer Bulletin .

Weiss, M. A. (2002). Data Structures & Problem Solving using Java. Florida: Addison Wesley.

Zeng, X. (2007). Software Design Methods. Software Engineering . University Of Manchester.

Zeng, X. (2008). Software Testing. Software Engineering . University of Manchester.

Page 110: File Handler program

- 110 -

9. APPENDIX

APPENDIX 1

Content of file 7179881TextAndData.txt

Column Name Units Type

1 Cruise none alphanumeric string

2 Date_Sampled dd-mmm-yyyy alphanumeric string

3 Time_Sampled hh:mm GMT alphanumeric string

4 Latitude decimal degrees floating-point

5 Longitude decimal degrees floating-point

6 Site none integer

7 Vessel none alphanumeric string

8 CTD_Cast none alphanumeric string

9 Depth_Sampled none alphanumeric string

10 Temperature °C floating-point

11 Salinity PSU floating-point

12 Tide none alphanumeric string

13 Volume ml floating-point

14 Tower_Diameter mm floating-point

15 Mean_Bact_Per_Field cells/field floating-point

16 SD_Bact_Per_Field cells/field floating-point

17 Bact_Abundance cells/ml exponential

18 Flag_Bact_Abundance none alphanumeric string

Page 111: File Handler program

- 111 -

APPENDIX 2

APPENDIX 3

Content of file 7179881TextPlain.txt

Plain text refers to any string (i.e., finite sequence of characters) that consists entirely of printable characters (i.e., human readable characters) and, optionally, a very few specific types of control characters (e.g., characters indicating a tab or the start of a new line).

A character is any letter, symbol or mark employed in writing or printing a written language (i.e., a language used by humans for which a writing system has been developed). The characters used to write the English language are the 26 lower case (i.e., small) and the 26 upper case (i.e., capital) letters of the English alphabet, the Arabic numerals, punctuation marks and a variety of other symbols (e.g., the ampersand, the equals sign, the tilde and the at symbol). An alphabet is the ordered, standardized set of letters that is used to write or print a written language.

Plain text usually refers to text that consists entirely of the ASCII printable characters and a few of its control characters. ASCII, an acronym for American standard code for information interchange, is based on the characters used to write the English language as it is used in the U.S. It is the de facto standard for the character encoding (i.e., representing characters by numbers) that is utilized by computers and communications equipment to represent text, and it (or some compatible extension of it) is used on most computers, including nearly all personal computers and workstations.

Content of file 7179881TextAndSp.txt

One of the advantage of the Web is that text is automatically wrapped into lines fitting within the current window size. Sometimes though, you will want to disable this behavior. For example when including samples of program code. You do this using the pre element. For instance:

<pre> void Node::Remove() { if (prev) prev->next = next;

else if (parent)

parent->SetContent(null);

if (next) next->prev = prev;

parent = null;

}

</pre>