• Lucid Dreaming - Dream Views




    Results 1 to 2 of 2
    1. #1
      Member Rakjavik's Avatar
      Join Date
      Nov 2007
      Gender
      Location
      USA
      Posts
      462
      Likes
      7

      Help with some Java code that is throwing an exception for clearing a list

      Ok, I can't figure out this attachment process, and holy hell, I know it's been a while since I posted, but not a big fan of the new interface. But anyway, Exception on line 135 fileList.clear() and dirList.clear(). I'm having issues with clearing a list, which I thought was a pretty basic function. If anyone can tell me why it is throwing an exception that would be awesome, code below. Also any experienced programmers that want to give me pointers is welcome too



      /* Copyright Joel none of ur business 2010
      * Version .95 - changes: added log file creation and addition, added logging into other methods
      * .
      */

      package foldermonitor;

      /**
      *
      * @author 501282234
      */
      import java.io.*;
      import java.text.SimpleDateFormat;
      import java.util.*;
      import java.util.logging.Level;
      import java.util.logging.Logger;
      import javax.mail.*;
      import javax.mail.internet.*;


      public class Main {


      public static void main(String[] args) throws Exception
      {
      // pull in the config file //
      Properties config = writeProp();

      // <editor-fold>declare all starting variables //
      boolean countDirs = false;
      String path;
      String appName;
      int[] ageThreshold = new int[2];
      String auditFormat;
      int countLimit = 0;
      List<String> exclusionString = new ArrayList();
      String emailTo;
      String subject;
      String docLocation;
      boolean updateDash = false;
      String smtpAddress = config.getProperty("SMTPAddress");
      // </editor-fold>declare all starting variables //

      // x is used as the app # //
      int x = 3;


      // start an infinite loop //
      while(true)
      {
      // end of config file //
      if (config.getProperty("App" + x) == null)
      {
      System.exit(0);
      }

      // <editor-fold> set all variables from config file //
      appName = config.getProperty("App" + x);
      path = config.getProperty(appName + "LogFolder");
      if (config.getProperty(appName + "DirectorySwitch") != null)
      countDirs = Boolean.parseBoolean(config.getProperty(appName + "DirectorySwitch"));
      if (config.getProperty(appName + "AgeThreshold") != null)
      {
      String[] tmpString = new String[2];
      tmpString = config.getProperty(appName + "AgeThreshold").split(",");
      ageThreshold[0] = Integer.parseInt(tmpString[0]);
      ageThreshold[1] = Integer.parseInt(tmpString[1]);
      }
      auditFormat = config.getProperty(appName + "AuditFormat");
      if (config.getProperty(appName + "CountLimit") != null)
      countLimit = Integer.parseInt(config.getProperty(appName + "CountLimit"));
      if (config.getProperty(appName + "ExclusionString") != null)
      exclusionString = parseExclusionString(config.getProperty(appName + "ExclusionString"));
      emailTo = config.getProperty(appName + "EmailTo");
      subject = config.getProperty(appName + "Subject");
      docLocation = config.getProperty(appName + "Doc");
      if (config.getProperty(appName + "UpdateDash") != null)
      updateDash = Boolean.parseBoolean(config.getProperty(appName + "UpdateDash"));
      // </editor-fold>set all variables from config file //


      // get list of files //
      List<File> fileList = getFiles(path,new FilesOnly());
      List<File> dirList = getFiles(path,new FoldersOnly());
      // if there are exclusions //
      if (!exclusionString.isEmpty())
      {
      fileList = removeExclusions(fileList,exclusionString);
      dirList = removeExclusions(dirList,exclusionString);
      }

      //<editor-fold>
      if (auditFormat != null)
      {
      fileList = parseAuditString(fileList,auditFormat);
      // send an e-mail alert if the file was not found //
      if (fileList == null)
      sendAlert(emailTo,"Log File not found " + path + "\\" + auditFormat,
      "",smtpAddress,"Log File not found for app - " + appName + " - " + path + "\\" + auditFormat,
      appName);
      }
      //</editor-fold> if there is a specific file to look at
      //<editor-fold>
      if(countLimit != 0)
      {
      // if files count is over threshold //
      if (overCount(fileList,dirList,countLimit))
      {
      sendAlert(emailTo,subject,docLocation,smtpAddress, appName +
      " has generated this alert due to passing the file count threshold of "
      + countLimit + " with a count of " + fileList.size(),appName);
      }
      }
      //</editor-fold> if looking for a count limit
      //<editor-fold>
      if((ageThreshold[0] != 0) && (!fileList.isEmpty()))
      {
      // runs the file list through the overagethreshold method to check if it is over //
      // result holds true or false for whether it is over age threshold and what the last updated file was //
      String[] result = overAgeThreshold(fileList,ageThreshold[0]);
      // if the 1 spot in the returned string array shows true then it is over agethreshold //
      if(Boolean.parseBoolean(result[1]))
      {
      sendAlert(emailTo,subject,docLocation,smtpAddress, appName +
      " has generated this alert due to the file or files being over the age of "
      + ageThreshold + " minutes. \n\n Last modified date - " + result[0],appName);
      }
      }
      //</editor-fold> if looking for an age threshold
      // <editor-fold>
      exclusionString.clear();
      auditFormat = null;
      ageThreshold[0] = 0;
      countLimit = 0;
      fileList.clear();
      dirList.clear();
      // </editor-fold> Clear Startup Variables

      System.out.println("App" + x + "Complete");
      // increment app variable //
      x++;
      }



      }
      // tests to see if the amount of files is over the count limit //
      public static boolean overCount(List<File> files, List<File> dirs, int countLimit)
      {
      // if the size of the list is over the count limit //
      if ((files != null) &&((files.size() + dirs.size()) > countLimit))
      {
      // return true that it is over the count //
      return true;
      }
      else
      {
      // else return false //
      return false;
      }
      }
      // gets list of files and folders //
      public static List<File> getFiles(String path, FileFilter filter)
      {

      // create new file array to return //
      List<File> fileList = new ArrayList();
      // create new file array to hold file and folder information //
      File[] fileInfo = new File(path).listFiles(filter);
      // check to make sure that the path has files in it //
      fileList = Arrays.asList(fileInfo);
      // return file list //
      return(fileList);
      }

      // reads the properties file //
      public static Properties writeProp() throws IOException
      {
      try
      {
      Properties config = new Properties();
      FileInputStream configFile = new FileInputStream("Config.xml");
      try
      {
      config.loadFromXML(configFile);
      }
      catch(Exception ex)
      {
      System.out.println(ex);
      }
      configFile.close();
      return(config);
      }
      catch(java.lang.Exception ex)
      {
      updateLog("Unable to locate config file, Config.xml");
      System.exit(0);
      return null;
      }
      }

      // gets the number of exclusion strings //
      public static List<String> parseExclusionString(String exclusionString)
      {
      // create a list to hold the exclusion strings //
      List<String> exclusionList = new ArrayList();
      // adds the elements to the array by seperating the strings using a comma //
      exclusionList.addAll(Arrays.asList(exclusionString .split(",")));
      // returns the string list //
      return exclusionList;
      }

      // removes elements from file list that are in exclusions strings //
      public static List<File> removeExclusions(List<File> fileList,List<String> exclusions)
      {
      // loops through all exclusion strings //
      for(int x =0;x < exclusions.size();x++)
      {
      // loops through all files //
      for(int y =0; y < fileList.size();y++)
      {
      // if the current exclusion string is found in the current file name //
      if (fileList.get(y).getName().indexOf(exclusions.get( x)) > -1)
      {
      // remove the element from the file list //
      fileList.remove(y);
      }
      }
      }
      // return the modified file list //
      return fileList;
      }

      // parses audit string //
      public static List<File> parseAuditString(List<File> fileList,String fileFormat) throws IOException
      {
      // the final name of the file to look for //
      String fileNameToLookFor;
      // if there is a date that needs to be figured out in the file format //
      if (fileFormat.indexOf(",") > -1)
      {
      // create a string array with the 3 pieces //
      String[] splitString = fileFormat.split(",");
      // create a date format using the 2nd string in array //
      SimpleDateFormat format = new SimpleDateFormat(splitString[1]);
      // create variable for the current day //
      Date today = Calendar.getInstance().getTime();
      // change the 2nd string in array to the format specified //
      splitString[1] = format.format(today);
      // add all 3 pieces of the split string to make the file name //
      fileNameToLookFor = splitString[0] + splitString[1] + splitString[2];
      }
      // if there is not date format //
      else
      {
      fileNameToLookFor = fileFormat;
      }

      // loops through all files in file list //
      for(int x = 0; x < fileList.size();x++)
      {
      // if the current filename matches the file to look for //
      if(fileList.get(x).getName().equals(fileNameToLook For))
      {
      // create new file list //
      List<File> foundFile = new ArrayList();
      // add the file to the new list //
      foundFile.add(fileList.get(x));
      // return the file list back //
      return(foundFile);
      }
      }
      // return null if file was not found //
      updateLog("File not found - " + fileNameToLookFor);
      return(null);
      }


      // scans through file list comparing the date to threshold //
      public static String[] overAgeThreshold(List<File> fileList,int ageThreshold)
      {
      // create a calendar with an old time to start so last modified gets changed right away //
      Calendar oldTime = Calendar.getInstance();
      oldTime.set(2000, 05, 5);
      // set last modified to the old time //
      Date lastModified = oldTime.getTime();
      // makes sure that the file list isn't empty //
      if (fileList != null)
      {
      // loops through the file list //
      for(int x =0;x < fileList.size();x++)
      {
      // get the last modified date of the current file //
      Date fileDate = new Date(fileList.get(x).lastModified());
      // if the current file date is newer then the last modified date //
      if(fileDate.after(lastModified))
      // change the last modified date to the current files last modified date //
      lastModified = fileDate;

      }
      }
      // get current time //
      Calendar now = Calendar.getInstance();
      // subtract the age threshold from current time //
      now.add(Calendar.MINUTE, -ageThreshold);
      // create a date object for the new time //
      Date ageLimit = now.getTime();

      // String array is created to hold last modified date and whether it is over age //
      String[] returns = new String[2];
      // adds the last modified date to the return string //
      returns[0] = lastModified.toString();
      //if the last modified date is newer then the age limit date //
      if(lastModified.after(ageLimit))
      {
      // return that it is not over the age threshold //
      returns[1] = "false";
      return(returns);
      }
      else
      {
      // return that it is over the age threshold //
      returns[1] = "true";
      return(returns);
      }
      }

      // send E-mail Alert //
      public static void sendAlert(String emailTo,String subject, String docLocation, String server,String body, String appName) throws IOException
      {
      try
      {
      // get authentication information for smpt server //
      Authenticator auth = new SMTPAuthenticator();
      // create new properties file for the session //
      Properties props = new Properties();
      props.put("mail.smtp.host", server);
      props.put("mail.smtp.auth", "true");
      // great new sessions using the properties and authentication information //
      Session session = Session.getInstance(props, auth);
      session.setDebug(false);
      // create new E-mail message //
      MimeMessage message = new MimeMessage(session);
      // set who the e-mail is from //
      InternetAddress addressFrom = new InternetAddress("[email protected]");
      message.setFrom(addressFrom);
      // set who the e-mail is going to //
      InternetAddress[] addressTo = new InternetAddress[1];
      addressTo[0] = new InternetAddress(emailTo);
      message.setRecipients(Message.RecipientType.TO, addressTo);
      // set subject of e-mail //
      message.setSubject(subject);
      // set body of e-mail //
      message.setContent(body, "text/plain");

      updateLog("E-mail alert sent for App - " + appName);
      // send e-mail //
      Transport.send(message);
      }
      catch (MessagingException ex)
      {
      updateLog("Could not send E-mail for App - " + appName);
      Logger.getLogger(Main.class.getName()).log(Level.S EVERE, null, ex);
      }


      }

      // Update Log File //
      public static void updateLog(String update) throws IOException
      {
      // Create new file object for the log //
      File log = new File("log.log");
      // if the log file doesn't exist then create it //
      if(!log.exists())
      log.createNewFile();
      // create new file writer with for log with option for appending //
      FileWriter outFile = new FileWriter(log,true);
      // create a buffered writer for writing to log //
      BufferedWriter out = new BufferedWriter(outFile);
      // create new date object with the current date and time //
      Date currentDate = Calendar.getInstance().getTime();
      // create a date format //
      SimpleDateFormat format = new SimpleDateFormat("MM.dd hh:mm aaa");
      // format the current date using the formatter //
      String currentTime = format.format(currentDate);
      // add the current time and the message to the log file //
      out.append(currentTime + " - " + update);
      // add a line //
      out.newLine();
      // close the log file //
      out.close();
      }
      }
      class SMTPAuthenticator extends javax.mail.Authenticator
      {

      public PasswordAuthentication getPasswordAuthentication()
      {
      try
      {
      Properties props = Main.writeProp();
      String username = "501287113";
      String password = props.getProperty("MailPassword");
      return new PasswordAuthentication(username, password);
      }
      catch (Exception ex)
      {
      Logger.getLogger(SMTPAuthenticator.class.getName() ).log(Level.SEVERE, null, ex);
      return(null);
      }
      }
      }

      class FilesOnly implements FileFilter
      {

      public boolean accept(File pathname)
      {
      if (pathname.isDirectory())
      return false;
      else
      return true;
      }

      }

      class FoldersOnly implements FileFilter
      {

      public boolean accept(File pathname)
      {
      if (pathname.isDirectory())
      return true;
      else
      return false;
      }

      }

    2. #2
      Member Achievements:
      1 year registered Veteran First Class 5000 Hall Points

      Join Date
      Sep 2004
      Gender
      Location
      Seattle, WA
      Posts
      2,503
      Likes
      217
      First of all: AAAAAHHH!!!! This isn't Java, it's C, using java syntax! *wrist slap for all the statics* p.s. nice student ID

      Aaand we're back. Now, first things first... WHAT exception is it throwing? Is there an error? Is it a NullPointerException? Have you tried catching it, and doing a "printStackTrace" or something similar?

      Second point: According to List (Java 2 Platform SE 5.0) the "clear" method has been deprecated for ever, and you should just use removeAll.

    Similar Threads

    1. Throwing wicked curves
      By CRAZY BONE in forum Dream Control
      Replies: 13
      Last Post: 04-24-2009, 09:29 PM
    2. Paper Throwing
      By poog in forum Senseless Banter
      Replies: 0
      Last Post: 10-27-2008, 12:24 AM
    3. Throwing Ice Balls
      By northcave in forum Introduction Zone
      Replies: 4
      Last Post: 01-24-2008, 08:38 PM
    4. Kinfe And Tomahawk Throwing
      By Infraredkelp in forum Entertainment
      Replies: 0
      Last Post: 04-30-2007, 06:49 AM

    Bookmarks

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •