Guest User

Untitled

a guest
Jul 1st, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 17.95 KB | None | 0 0
  1. package task3;
  2.  
  3. import java.io.*;
  4. import java.util.*;
  5.  
  6. /*
  7.  * Helpdesk class, containing all file I/O functionality. Objects of this class
  8.  * consist of the attributes of a record for a question and answer system. The
  9.  * class methods read archived questions from a text file and and write answers
  10.  * corresponding to associated questions.
  11.  */
  12.  
  13. public class Helpdesk {
  14.  
  15.     /*
  16.      * Class fields -
  17.      *   record -> array containing all other class fields
  18.      *   recordID -> unique string used to identify individual questions
  19.      *   question -> user-supplied question
  20.      *   answer -> user-supplied answer
  21.      *   status -> contains either "Pending" or "Answered" depending on state
  22.      *   questionDate -> date that the question was posted
  23.      *   answerDate -> date that the answer was posted
  24.      *   delimiter -> delimiter used to convert Strings to String arrays
  25.      *   responseTime -> Time differencer between questionDate and answerDate
  26.      *
  27.      *   archivePath -> host's path to the archive.txt file
  28.      *   path -> host's path to live web folder
  29.      *   loginEntry, passwordEntry, userName, password -> data constants
  30.      */
  31.    
  32.     private String record[] = null;
  33.     private String recordID = "0", status = "Pending";
  34.     private String question = "-", answer = "-";
  35.     private Date questionDate = null, answerDate = null, summaryDate = null;
  36.     private char delimiter = '|'; // global delimiter
  37.     private long responseTime = -1; // in hours
  38.    
  39.     private String archivePath = "";
  40.     private String path = "";
  41.     private String loginEntry = "", passwordEntry = "";
  42.     final private String userName = "admin";
  43.     final private String password = "1234";
  44.  
  45.     /*
  46.      * Getters and setters - these methods change or retrieve specific fields
  47.      */
  48.  
  49.     public String[] getRecord() { return this.record; }
  50.     public void setRecord(String[] record) { this.record = record; }
  51.  
  52.     public String getQuestion() { return this.question; }
  53.     public void setQuestion(String question) { this.question = question; }
  54.  
  55.     public String getAnswer() { return this.answer; }
  56.     public void setAnswer(String question) { this.answer = question; }
  57.  
  58.     public String getRecordID() { return this.recordID; }
  59.     public void setRecordID(String id) { this.recordID = id; }
  60.  
  61.     public String getPath() { return this.path; }
  62.     public void setPath(String x) { this.path = x; }
  63.  
  64.     public String getArchivePath() {
  65.         archivePath = path + "archive.txt";
  66.         return archivePath;
  67.     }
  68.    
  69.     public String getSummaryPath() {
  70.         archivePath = path + "stastics.txt";
  71.         return archivePath;
  72.     }
  73.  
  74.     public String getLoginEntry() { return this.loginEntry; }
  75.     public void setLoginEntry(String x) { this.loginEntry = x; }
  76.  
  77.     public String getPasswordEntry() { return this.passwordEntry; }
  78.     public void setPasswordEntry(String x) { this.passwordEntry = x; }
  79.  
  80.     public void setStatus(String x) { this.status = x; }
  81.  
  82.     public String getPassword() { return this.password; }
  83.     public String getUserName() { return this.userName; }
  84.  
  85.     /*
  86.      * Helpdesk constructor, currently empty as all fields are initialised
  87.      * within other methods.
  88.      */
  89.  
  90.  
  91.     public Helpdesk() {
  92.         // add constructor code
  93.     }
  94.    
  95.     /*
  96.      * checkFile() method - This method checks to see whether or not a file at
  97.      * the archivePath variable exists. If the file does not exist, the method
  98.      * attempts to create it.
  99.      */
  100.    
  101.     public void checkFile() {
  102.         File file = new File(getArchivePath());
  103.        
  104.         if(!file.exists()) {
  105.             try{
  106.                 file.createNewFile();
  107.             } catch (IOException ioe) {
  108.                 logException(ioe);
  109.             }
  110.         }
  111.     }
  112.    
  113.     /*
  114.      * addQuestion() method - This method accepts a String question passed as
  115.      * an argument. This question is then assigned to a String array element,
  116.      * along with other fields that are currently known at the time. The array
  117.      * is then written to the file as a single record.
  118.      */
  119.    
  120.     public void addQuestion(String question) {
  121.         questionDate = new Date();
  122.         this.recordID = String.valueOf(questionDate.getTime());
  123.         this.question = question;
  124.         setStatus("Pending");
  125.         record = new String[7];
  126.  
  127.         record[0] = this.recordID;
  128.         record[1] = questionDate.toString();
  129.         record[2] = this.question;
  130.         record[3] = status;
  131.         record[4] = "-"; // these fields are assigned meaningful values later
  132.         record[5] = "-";
  133.         record[6] = "-";
  134.  
  135.         writeRecord(record);
  136.     }
  137.    
  138.     /*
  139.      * addAnswer() method - This method accepts two String arguments, the first
  140.      * to update the record, and the second to identify the record that needs
  141.      * updating. It changes the status of the record to "Answered", and writes
  142.      * the rest of the record to the file. All fields are known at this time.
  143.      */
  144.    
  145.     public void addAnswer(String input) {
  146.         answerDate = new Date();
  147.  
  148.         status = "Answered"; // status is no longer "Pending"
  149.         record = readRecord(input);
  150.         responseTime = (this.answerDate.getTime() - Long.parseLong(record[0]))
  151.                 / (1000 * 60 * 60);
  152.        
  153.         if (record == null) { // checks to make sure the record exists,
  154.                 System.out.println("Record does not exist.");
  155.                 return;
  156.         }
  157.  
  158.         record[3] = status;
  159.         record[4] = this.answer;
  160.         record[5] = answerDate.toString();
  161.         record[6] = String.valueOf(responseTime);
  162.        
  163.         condenceFile(record[0]);
  164.         writeRecord(record);
  165.     }
  166.    
  167.     /*
  168.      * writeRecord() methods - The first method accepts a String array argument,
  169.      * which is to be written to file as a new record. The end of the record is
  170.      * marked by two delimiters, to be able to identify it. The second method is
  171.      * is the exact same as the first, but takes a second String argument,
  172.      * containing the name of the file that needs to be written to, and uses
  173.      * this instead.
  174.      */
  175.    
  176.     public void writeRecord(String[] record) {
  177.         try {
  178.             FileWriter file = new FileWriter(getArchivePath(), true);
  179.             PrintWriter fileOut = new PrintWriter(file);
  180.  
  181.             for (int index  = 0; index < 6; index++) {
  182.                 fileOut.print(record[index] + delimiter);
  183.                 if (index == 5) {
  184.                    
  185.                     // add two delimiters to signify the end of the record
  186.                     fileOut.println(record[index + 1] + delimiter + delimiter);
  187.                 }
  188.             }
  189.  
  190.             fileOut.close();
  191.         } catch (Exception exc) {
  192.                 logException(exc);
  193.         }
  194.     }
  195.    
  196.     /*
  197.      * writeSummary() - This method accepts one int array and writes its
  198.      * contents to file in a user-friendly and human-readable format.
  199.      */
  200.    
  201.     public void writeSummary(int[] summary) {
  202.         try {
  203.             FileWriter file = new FileWriter(getSummaryPath(), true);
  204.             PrintWriter fileOut = new PrintWriter(file);
  205.            
  206.             summaryDate = new Date();
  207.             fileOut.println("-------------------------------------------");
  208.             fileOut.println("Stastics From: " + summaryDate);
  209.             fileOut.println("-------------------------------------------");
  210.            
  211.             if(summary[0] == 0) {
  212.                 fileOut.println("Maximum Hours to reply: Less than one hour");    
  213.             } else {
  214.                 fileOut.println("Maximum Hours to reply: " +
  215.                     Integer.toString(summary[0]));
  216.             }
  217.             if(summary[1] == 0) {
  218.                 fileOut.println("Mean Hours to reply: Less than one hour ");    
  219.             } else {
  220.                 fileOut.println("Mean Hours to reply: " +
  221.                     Integer.toString(summary[1]));
  222.             }
  223.             if(summary[2] == 0) {
  224.                 fileOut.println("Median Hours to reply: Less than one hour ");    
  225.             } else {
  226.                 fileOut.println("Median Hours to reply: " +
  227.                     Integer.toString(summary[2]));
  228.             }
  229.             fileOut.println("Total Un-answered Requests: " +
  230.                     Integer.toString(summary[3]));
  231.             fileOut.println("Total Messages in Archive: " +
  232.                     Integer.toString(summary[4]));
  233.            
  234.             fileOut.println("-------------------------------------------");
  235.             fileOut.println(" ");
  236.             fileOut.println(" ");
  237.             fileOut.close();
  238.         } catch (Exception exc) {
  239.             logException(exc);
  240.         }
  241.  
  242.     }
  243.    
  244.     /*
  245.      * readMostRecent() method - This method first calculates the many lines
  246.      * down the file the 5th last line is. Once it encounters this line, it
  247.      * begins to read each record into a two-dimensional array, and this array
  248.      * is then returned to the caller.
  249.      */
  250.    
  251.     public String[][] readMostRecent() {
  252.         int[] intValues = calculateSummary();
  253.         int lines = 0;
  254.         int calculatedLines = calculateTotal();
  255.        
  256.         if (calculatedLines > 5) {
  257.             lines = 5;
  258.         } else {
  259.             lines = calculatedLines;
  260.         }
  261.        
  262.         int startLine = calculateTotal() - lines;
  263.         int lineCounter = 0;
  264.         String[][] helpdeskArray = new String[5][7];
  265.  
  266.         try {
  267.             BufferedReader fileIn = new BufferedReader(new
  268.                     FileReader(getArchivePath())); // file name
  269.             String record = null;
  270.             String[] recordArray = null;
  271.            
  272.             while ((record = fileIn.readLine()) != null) {
  273.                 lineCounter++;
  274.                 if (lineCounter == startLine) {
  275.                     for (int count = 0; count < lines; count++) {
  276.                         record = fileIn.readLine();
  277.                         recordArray = record.split("[" + delimiter + "]");
  278.                         for (int counter = 0; counter < 7; counter++) {
  279.                                 helpdeskArray[count][counter] =
  280.                                         recordArray[counter];
  281.                         }
  282.                     }
  283.                     return helpdeskArray;
  284.                 }
  285.             }
  286.             fileIn.close();
  287.         } catch (Exception exc) {
  288.                 logException(exc);
  289.         }
  290.        
  291.         return null;  
  292.     }
  293.    
  294.     /*
  295.      * readAll() method - This method simply reads all the records in file and
  296.      * returns the contents in a two-dimensional String array.
  297.      */
  298.  
  299.     public String[][] readAll() {
  300.         int totalEntries = calculateTotal();
  301.  
  302.         String[][] helpdeskArray = new String[totalEntries][7];
  303.  
  304.         try {
  305.             BufferedReader fileIn = new BufferedReader(new
  306.                     FileReader(getArchivePath())); // file name
  307.             String record = null;
  308.             String[] recordArray = null;
  309.  
  310.             while ((record = fileIn.readLine()) != null) {
  311.                     for (int count = 0; count < totalEntries; count++) {
  312.                             record = fileIn.readLine();
  313.                             recordArray = record.split("[" + delimiter + "]");
  314.                             for (int counter = 0; counter < 7; counter++) {
  315.                                     helpdeskArray[count][counter] =
  316.                                             recordArray[counter];
  317.                             }
  318.                     }
  319.                     return null;
  320.             }
  321.             fileIn.close();
  322.         } catch (Exception exc) {
  323.             logException(exc);
  324.         }
  325.         return helpdeskArray;
  326.     }
  327.    
  328.     /*
  329.      * readRecord() method - This method reads a single record, equivalent to
  330.      * one line in the file, into a String, which is the parsed by the global
  331.      * delimiter into an array. This array is returned to the caller.
  332.      */
  333.  
  334.     public String[] readRecord(String recordID) {
  335.         String[] recordArray = null;
  336.  
  337.         try {
  338.             BufferedReader fileIn = new BufferedReader(new
  339.                     FileReader(getArchivePath()));
  340.             String record = null;
  341.             while ((record = fileIn.readLine()) != null) {
  342.                 recordArray = record.split("[" + delimiter + "]");
  343.                 if (recordID.equals(recordArray[0]))
  344.                     return recordArray;
  345.             }
  346.             fileIn.close();
  347.         } catch (Exception exc) {
  348.             logException(exc);
  349.         }
  350.         return null;
  351.     }
  352.    
  353.     /*
  354.      * condenseFile() method - This method accepts one String argument used to
  355.      * identify a record in the disk file. It then reads in all the records on
  356.      * the disk file, except the one that the recordID matches to. This record
  357.      * is skipped, and all the others are written to the new file.
  358.      */
  359.  
  360.     public void condenceFile(String recordID) {
  361.         String[] recordArray = null;
  362.         File inFile = new File(getArchivePath());
  363.         String recordLine = null;
  364.  
  365.         // read input file into memory as List of Strings
  366.         List<String> lines = new ArrayList<String>();
  367.        
  368.         try {
  369.             BufferedReader fileIn = new BufferedReader(new FileReader(inFile));
  370.            
  371.             while ((recordLine = fileIn.readLine()) != null) {
  372.                 lines.add(recordLine);
  373.             }
  374.            
  375.             fileIn.close();
  376.         } catch (IOException ioe) {
  377.             logException(ioe);
  378.         }
  379.  
  380.         // loop over record outputting to file, ignoring record to delete
  381.         try {
  382.             PrintWriter fileOut = new PrintWriter(new FileWriter(inFile));
  383.             for (String record : lines) {
  384.                 recordArray = record.split("[" + delimiter + "]");
  385.  
  386.                 if (recordID.equals(recordArray[0])) {
  387.                     continue;
  388.                 }
  389.  
  390.                 for (int index  = 0; index < 6; index++) {
  391.                     fileOut.print(recordArray[index] + delimiter);
  392.                     if (index == 5) {
  393.                         fileOut.println(recordArray[index + 1] +
  394.                                 delimiter + delimiter);
  395.                     }
  396.                 }
  397.             }
  398.            
  399.             fileOut.close();
  400.         } catch (IOException ioe) {
  401.             logException(ioe);
  402.         }
  403.     }
  404.    
  405.     /*
  406.      * calculateTotal() method - This method simply calulates and returns the
  407.      * number of lines read in a file, and therefore the number of lines
  408.      * contained within the file.
  409.      */
  410.  
  411.     public int calculateTotal() {
  412.         int lines = 0;
  413.         try {
  414.             BufferedReader fileIn = new BufferedReader(new
  415.                     FileReader(getArchivePath()));
  416.             while (fileIn.readLine() != null) lines++;
  417.             fileIn.close();
  418.             return lines;
  419.         } catch (Exception exc) {
  420.             logException(exc);
  421.         }
  422.         return lines;
  423.     }
  424.    
  425.     /*
  426.      * calculateSummary() method - This method calculates 5 variables and
  427.      * returns them as an int array. All but two of them require reading the
  428.      * responseTime value from the disk file, used to evaluate them.
  429.      */
  430.  
  431.     public int[] calculateSummary() {
  432.         String[] recordArray = null;
  433.         Vector<Integer> calculationsVector = new Vector<Integer>();
  434.         int maxHours = -1, meanHours = -1, medianHours = -1, numberAnswered = 0,
  435.                 numberExisting = 0;
  436.         int[] excArray = { maxHours, meanHours, medianHours, numberAnswered,
  437.             numberExisting };
  438.  
  439.         try {
  440.             BufferedReader fileIn = new BufferedReader(new
  441.                     FileReader(getArchivePath()));
  442.             String record = null;
  443.  
  444.             while ((record = fileIn.readLine()) != null) {
  445.                 numberExisting++;
  446.  
  447.                 recordArray = record.split("[" + delimiter + "]");
  448.  
  449.                 if (recordArray[3].equals("Answered")) {
  450.                     numberAnswered++;
  451.  
  452.                     // Only answered questions will have a responseTime field
  453.                     // that is meaningful.
  454.                     calculationsVector.add(Integer.parseInt(recordArray[6]));
  455.                 }
  456.             }
  457.  
  458.             Integer[] intValues = new Integer[calculationsVector.size()];
  459.             calculationsVector.toArray(intValues);
  460.  
  461.             Arrays.sort(intValues);
  462.  
  463.             // Calculate maxHours
  464.             maxHours = intValues[intValues.length - 1];
  465.  
  466.             // Calculate meanHours
  467.             int sum = 0;
  468.  
  469.             for (int count = 0; count < intValues.length; count++) {
  470.                 sum += intValues[count];
  471.             }
  472.  
  473.             meanHours = sum / intValues.length;
  474.  
  475.             // Calculate medianHours
  476.             if (intValues.length % 2 != 0)
  477.                 medianHours = intValues[(intValues.length - 1) / 2];
  478.             else
  479.                 medianHours = (intValues[(intValues.length / 2)] +
  480.                                 intValues[(intValues.length / 2) - 1]) / 2;
  481.  
  482.             fileIn.close();
  483.             int[] returnArray = { maxHours, meanHours, medianHours,
  484.                 numberAnswered, numberExisting };
  485.  
  486.             return returnArray;
  487.         } catch (Exception exc) {
  488.             logException(exc);
  489.         }
  490.  
  491.         return excArray;
  492.     }
  493.    
  494.     /*
  495.      * logException method - This method accepts one Exception argument and
  496.      * writes it to disc along with the time it occurred at. It is called from
  497.      * other exception catching code.
  498.      */
  499.  
  500.     public static void logException(Exception exc) {
  501.         try {
  502.             FileWriter file = new FileWriter("exceptions.log", true);
  503.             PrintWriter fileOut = new PrintWriter(file);
  504.  
  505.             fileOut.println("Date: " + new Date() + ", Exception: " + exc);
  506.             fileOut.close();
  507.         } catch (IOException e) {
  508.             // ignore
  509.         }
  510.     }
  511. }
Add Comment
Please, Sign In to add comment