Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package task3;
- import java.io.*;
- import java.util.*;
- /*
- * Helpdesk class, containing all file I/O functionality. Objects of this class
- * consist of the attributes of a record for a question and answer system. The
- * class methods read archived questions from a text file and and write answers
- * corresponding to associated questions.
- */
- public class Helpdesk {
- /*
- * Class fields -
- * record -> array containing all other class fields
- * recordID -> unique string used to identify individual questions
- * question -> user-supplied question
- * answer -> user-supplied answer
- * status -> contains either "Pending" or "Answered" depending on state
- * questionDate -> date that the question was posted
- * answerDate -> date that the answer was posted
- * delimiter -> delimiter used to convert Strings to String arrays
- * responseTime -> Time differencer between questionDate and answerDate
- *
- * archivePath -> host's path to the archive.txt file
- * path -> host's path to live web folder
- * loginEntry, passwordEntry, userName, password -> data constants
- */
- private String record[] = null;
- private String recordID = "0", status = "Pending";
- private String question = "-", answer = "-";
- private Date questionDate = null, answerDate = null, summaryDate = null;
- private char delimiter = '|'; // global delimiter
- private long responseTime = -1; // in hours
- private String archivePath = "";
- private String path = "";
- private String loginEntry = "", passwordEntry = "";
- final private String userName = "admin";
- final private String password = "1234";
- /*
- * Getters and setters - these methods change or retrieve specific fields
- */
- public String[] getRecord() { return this.record; }
- public void setRecord(String[] record) { this.record = record; }
- public String getQuestion() { return this.question; }
- public void setQuestion(String question) { this.question = question; }
- public String getAnswer() { return this.answer; }
- public void setAnswer(String question) { this.answer = question; }
- public String getRecordID() { return this.recordID; }
- public void setRecordID(String id) { this.recordID = id; }
- public String getPath() { return this.path; }
- public void setPath(String x) { this.path = x; }
- public String getArchivePath() {
- archivePath = path + "archive.txt";
- return archivePath;
- }
- public String getSummaryPath() {
- archivePath = path + "stastics.txt";
- return archivePath;
- }
- public String getLoginEntry() { return this.loginEntry; }
- public void setLoginEntry(String x) { this.loginEntry = x; }
- public String getPasswordEntry() { return this.passwordEntry; }
- public void setPasswordEntry(String x) { this.passwordEntry = x; }
- public void setStatus(String x) { this.status = x; }
- public String getPassword() { return this.password; }
- public String getUserName() { return this.userName; }
- /*
- * Helpdesk constructor, currently empty as all fields are initialised
- * within other methods.
- */
- public Helpdesk() {
- // add constructor code
- }
- /*
- * checkFile() method - This method checks to see whether or not a file at
- * the archivePath variable exists. If the file does not exist, the method
- * attempts to create it.
- */
- public void checkFile() {
- File file = new File(getArchivePath());
- if(!file.exists()) {
- try{
- file.createNewFile();
- } catch (IOException ioe) {
- logException(ioe);
- }
- }
- }
- /*
- * addQuestion() method - This method accepts a String question passed as
- * an argument. This question is then assigned to a String array element,
- * along with other fields that are currently known at the time. The array
- * is then written to the file as a single record.
- */
- public void addQuestion(String question) {
- questionDate = new Date();
- this.recordID = String.valueOf(questionDate.getTime());
- this.question = question;
- setStatus("Pending");
- record = new String[7];
- record[0] = this.recordID;
- record[1] = questionDate.toString();
- record[2] = this.question;
- record[3] = status;
- record[4] = "-"; // these fields are assigned meaningful values later
- record[5] = "-";
- record[6] = "-";
- writeRecord(record);
- }
- /*
- * addAnswer() method - This method accepts two String arguments, the first
- * to update the record, and the second to identify the record that needs
- * updating. It changes the status of the record to "Answered", and writes
- * the rest of the record to the file. All fields are known at this time.
- */
- public void addAnswer(String input) {
- answerDate = new Date();
- status = "Answered"; // status is no longer "Pending"
- record = readRecord(input);
- responseTime = (this.answerDate.getTime() - Long.parseLong(record[0]))
- / (1000 * 60 * 60);
- if (record == null) { // checks to make sure the record exists,
- System.out.println("Record does not exist.");
- return;
- }
- record[3] = status;
- record[4] = this.answer;
- record[5] = answerDate.toString();
- record[6] = String.valueOf(responseTime);
- condenceFile(record[0]);
- writeRecord(record);
- }
- /*
- * writeRecord() methods - The first method accepts a String array argument,
- * which is to be written to file as a new record. The end of the record is
- * marked by two delimiters, to be able to identify it. The second method is
- * is the exact same as the first, but takes a second String argument,
- * containing the name of the file that needs to be written to, and uses
- * this instead.
- */
- public void writeRecord(String[] record) {
- try {
- FileWriter file = new FileWriter(getArchivePath(), true);
- PrintWriter fileOut = new PrintWriter(file);
- for (int index = 0; index < 6; index++) {
- fileOut.print(record[index] + delimiter);
- if (index == 5) {
- // add two delimiters to signify the end of the record
- fileOut.println(record[index + 1] + delimiter + delimiter);
- }
- }
- fileOut.close();
- } catch (Exception exc) {
- logException(exc);
- }
- }
- /*
- * writeSummary() - This method accepts one int array and writes its
- * contents to file in a user-friendly and human-readable format.
- */
- public void writeSummary(int[] summary) {
- try {
- FileWriter file = new FileWriter(getSummaryPath(), true);
- PrintWriter fileOut = new PrintWriter(file);
- summaryDate = new Date();
- fileOut.println("-------------------------------------------");
- fileOut.println("Stastics From: " + summaryDate);
- fileOut.println("-------------------------------------------");
- if(summary[0] == 0) {
- fileOut.println("Maximum Hours to reply: Less than one hour");
- } else {
- fileOut.println("Maximum Hours to reply: " +
- Integer.toString(summary[0]));
- }
- if(summary[1] == 0) {
- fileOut.println("Mean Hours to reply: Less than one hour ");
- } else {
- fileOut.println("Mean Hours to reply: " +
- Integer.toString(summary[1]));
- }
- if(summary[2] == 0) {
- fileOut.println("Median Hours to reply: Less than one hour ");
- } else {
- fileOut.println("Median Hours to reply: " +
- Integer.toString(summary[2]));
- }
- fileOut.println("Total Un-answered Requests: " +
- Integer.toString(summary[3]));
- fileOut.println("Total Messages in Archive: " +
- Integer.toString(summary[4]));
- fileOut.println("-------------------------------------------");
- fileOut.println(" ");
- fileOut.println(" ");
- fileOut.close();
- } catch (Exception exc) {
- logException(exc);
- }
- }
- /*
- * readMostRecent() method - This method first calculates the many lines
- * down the file the 5th last line is. Once it encounters this line, it
- * begins to read each record into a two-dimensional array, and this array
- * is then returned to the caller.
- */
- public String[][] readMostRecent() {
- int[] intValues = calculateSummary();
- int lines = 0;
- int calculatedLines = calculateTotal();
- if (calculatedLines > 5) {
- lines = 5;
- } else {
- lines = calculatedLines;
- }
- int startLine = calculateTotal() - lines;
- int lineCounter = 0;
- String[][] helpdeskArray = new String[5][7];
- try {
- BufferedReader fileIn = new BufferedReader(new
- FileReader(getArchivePath())); // file name
- String record = null;
- String[] recordArray = null;
- while ((record = fileIn.readLine()) != null) {
- lineCounter++;
- if (lineCounter == startLine) {
- for (int count = 0; count < lines; count++) {
- record = fileIn.readLine();
- recordArray = record.split("[" + delimiter + "]");
- for (int counter = 0; counter < 7; counter++) {
- helpdeskArray[count][counter] =
- recordArray[counter];
- }
- }
- return helpdeskArray;
- }
- }
- fileIn.close();
- } catch (Exception exc) {
- logException(exc);
- }
- return null;
- }
- /*
- * readAll() method - This method simply reads all the records in file and
- * returns the contents in a two-dimensional String array.
- */
- public String[][] readAll() {
- int totalEntries = calculateTotal();
- String[][] helpdeskArray = new String[totalEntries][7];
- try {
- BufferedReader fileIn = new BufferedReader(new
- FileReader(getArchivePath())); // file name
- String record = null;
- String[] recordArray = null;
- while ((record = fileIn.readLine()) != null) {
- for (int count = 0; count < totalEntries; count++) {
- record = fileIn.readLine();
- recordArray = record.split("[" + delimiter + "]");
- for (int counter = 0; counter < 7; counter++) {
- helpdeskArray[count][counter] =
- recordArray[counter];
- }
- }
- return null;
- }
- fileIn.close();
- } catch (Exception exc) {
- logException(exc);
- }
- return helpdeskArray;
- }
- /*
- * readRecord() method - This method reads a single record, equivalent to
- * one line in the file, into a String, which is the parsed by the global
- * delimiter into an array. This array is returned to the caller.
- */
- public String[] readRecord(String recordID) {
- String[] recordArray = null;
- try {
- BufferedReader fileIn = new BufferedReader(new
- FileReader(getArchivePath()));
- String record = null;
- while ((record = fileIn.readLine()) != null) {
- recordArray = record.split("[" + delimiter + "]");
- if (recordID.equals(recordArray[0]))
- return recordArray;
- }
- fileIn.close();
- } catch (Exception exc) {
- logException(exc);
- }
- return null;
- }
- /*
- * condenseFile() method - This method accepts one String argument used to
- * identify a record in the disk file. It then reads in all the records on
- * the disk file, except the one that the recordID matches to. This record
- * is skipped, and all the others are written to the new file.
- */
- public void condenceFile(String recordID) {
- String[] recordArray = null;
- File inFile = new File(getArchivePath());
- String recordLine = null;
- // read input file into memory as List of Strings
- List<String> lines = new ArrayList<String>();
- try {
- BufferedReader fileIn = new BufferedReader(new FileReader(inFile));
- while ((recordLine = fileIn.readLine()) != null) {
- lines.add(recordLine);
- }
- fileIn.close();
- } catch (IOException ioe) {
- logException(ioe);
- }
- // loop over record outputting to file, ignoring record to delete
- try {
- PrintWriter fileOut = new PrintWriter(new FileWriter(inFile));
- for (String record : lines) {
- recordArray = record.split("[" + delimiter + "]");
- if (recordID.equals(recordArray[0])) {
- continue;
- }
- for (int index = 0; index < 6; index++) {
- fileOut.print(recordArray[index] + delimiter);
- if (index == 5) {
- fileOut.println(recordArray[index + 1] +
- delimiter + delimiter);
- }
- }
- }
- fileOut.close();
- } catch (IOException ioe) {
- logException(ioe);
- }
- }
- /*
- * calculateTotal() method - This method simply calulates and returns the
- * number of lines read in a file, and therefore the number of lines
- * contained within the file.
- */
- public int calculateTotal() {
- int lines = 0;
- try {
- BufferedReader fileIn = new BufferedReader(new
- FileReader(getArchivePath()));
- while (fileIn.readLine() != null) lines++;
- fileIn.close();
- return lines;
- } catch (Exception exc) {
- logException(exc);
- }
- return lines;
- }
- /*
- * calculateSummary() method - This method calculates 5 variables and
- * returns them as an int array. All but two of them require reading the
- * responseTime value from the disk file, used to evaluate them.
- */
- public int[] calculateSummary() {
- String[] recordArray = null;
- Vector<Integer> calculationsVector = new Vector<Integer>();
- int maxHours = -1, meanHours = -1, medianHours = -1, numberAnswered = 0,
- numberExisting = 0;
- int[] excArray = { maxHours, meanHours, medianHours, numberAnswered,
- numberExisting };
- try {
- BufferedReader fileIn = new BufferedReader(new
- FileReader(getArchivePath()));
- String record = null;
- while ((record = fileIn.readLine()) != null) {
- numberExisting++;
- recordArray = record.split("[" + delimiter + "]");
- if (recordArray[3].equals("Answered")) {
- numberAnswered++;
- // Only answered questions will have a responseTime field
- // that is meaningful.
- calculationsVector.add(Integer.parseInt(recordArray[6]));
- }
- }
- Integer[] intValues = new Integer[calculationsVector.size()];
- calculationsVector.toArray(intValues);
- Arrays.sort(intValues);
- // Calculate maxHours
- maxHours = intValues[intValues.length - 1];
- // Calculate meanHours
- int sum = 0;
- for (int count = 0; count < intValues.length; count++) {
- sum += intValues[count];
- }
- meanHours = sum / intValues.length;
- // Calculate medianHours
- if (intValues.length % 2 != 0)
- medianHours = intValues[(intValues.length - 1) / 2];
- else
- medianHours = (intValues[(intValues.length / 2)] +
- intValues[(intValues.length / 2) - 1]) / 2;
- fileIn.close();
- int[] returnArray = { maxHours, meanHours, medianHours,
- numberAnswered, numberExisting };
- return returnArray;
- } catch (Exception exc) {
- logException(exc);
- }
- return excArray;
- }
- /*
- * logException method - This method accepts one Exception argument and
- * writes it to disc along with the time it occurred at. It is called from
- * other exception catching code.
- */
- public static void logException(Exception exc) {
- try {
- FileWriter file = new FileWriter("exceptions.log", true);
- PrintWriter fileOut = new PrintWriter(file);
- fileOut.println("Date: " + new Date() + ", Exception: " + exc);
- fileOut.close();
- } catch (IOException e) {
- // ignore
- }
- }
- }
Add Comment
Please, Sign In to add comment