/**
  * startLogger initializes and returns a file at logLoc with the results of logging at level
  * logLevel.
  *
  * @param logLoc location of the output log file- a string
  * @param logLevel logging level (is parsed by level.parse())
  * @return Logger object to log to.
  */
 public Logger startLogger(String logLoc, String logLevel) {
   try {
     fh = new FileHandler(logLoc); // sets output log file at logLoc
   } catch (SecurityException e) {
     e.printStackTrace();
     System.err.println("SecurityException establishing logger. Exiting...\n");
     System.exit(1);
   } catch (IOException e) {
     e.printStackTrace();
     System.err.println("IOException establishing logger. Exiting...\n");
     System.exit(1);
   }
   fh.setFormatter(new SimpleFormatter()); // format of log is 'human-readable' simpleformat
   logger.addHandler(fh); // attach formatter to logger
   logger.setLevel(Level.parse(logLevel)); // set log level
   return logger;
 }
  // TODO add exception for invalid options
  private void loadCLO(String[] args) {
    Options options = new Options();

    String[][] clolist = {
      // {"variable/optionname", "description"},
      {"genConfig", "general configuration file location"},
      {"inWeightsLoc", "input weights configuration file location"},
      {"inDBLoc", "input database file location"},
      {"outWeightsLoc", "output weights configuration file location"},
      {"outDBLoc", "output database file location"},
      {"p3pLocation", "adding to DB: single policy file location"},
      {"p3pDirLocation", "adding to DB: multiple policy directory location"},
      {"newDB", "create new database in place of old one (doesn't check for existence of old one"},
      {"newPolicyLoc", "the policy object to process"},
      {"userResponse", "response to specified policy"},
      {"userIO", "user interface"},
      {"userInit", "initialization via user interface"},
      {"policyDB", "PolicyDatabase backend"},
      {"cbrV", "CBR to use"},
      {"blanketAccept", "automatically accept the user suggestion"},
      {"loglevel", "level of things save to the log- see java logging details"},
      {"policyDB", "PolicyDatabase backend"},
      {"NetworkRType", "Network Resource type"},
      {"NetworkROptions", "Network Resource options"},
      {"confidenceLevel", "Confidence threshold for consulting a networked resource"},
      {"useNet", "use networking options"},
      {"loglocation", "where to save the log file"},
      {"loglevel", "the java logging level to use. See online documentation for enums."}
    };

    for (String[] i : clolist) {
      options.addOption(i[0], true, i[1]);
    }

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
      cmd = parser.parse(options, args);
    } catch (ParseException e) {
      System.err.println("Error parsing commandline arguments.");
      e.printStackTrace();
      System.exit(3);
    }
    /*
    for(String i : args)
    {
    	System.err.println(i);
    }
    */
    for (String[] i : clolist) {
      if (cmd.hasOption(i[0])) {
        System.err.println("found option i: " + i);
        genProps.setProperty(i[0], cmd.getOptionValue(i[0]));
      }
    }
    System.err.println(genProps);
  }
  /**
   * returns the policy object from the policyObject option
   *
   * @return the policy object to be processed
   */
  public void loadPO() {

    if (genProps.getProperty("newPolicyLoc", null) == null)
      System.err.println("newPolLoc == null in gio:loadPO");
    File pLoc = new File(genProps.getProperty("newPolicyLoc", null));
    if (!pLoc.exists()) {
      System.err.println("no file found at p3p policy location specified by the new policy option");
      System.exit(1);
    }

    po = (new P3PParser()).parse(pLoc.getAbsolutePath());
    // TODO make sure that the context is parsed if avaliable
    if (po.getContext().getDomain() == null) {
      po.setContext(
          new Context(
              new Date(System.currentTimeMillis()),
              new Date(System.currentTimeMillis()),
              genProps.getProperty("newPolicyLoc")));
    }
  }
 /**
  * writes a property file to disk
  *
  * @param wprops the property file to write
  * @param wloc where to write to
  */
 private void writePropertyFile(Properties wprops, String wloc) {
   if (wprops == null) System.out.println("wrops null in gio/writepropertyfile");
   if (wloc == null) System.out.println("wloc null in gio/writepropertyfile");
   try {
     wprops.store(new FileOutputStream(wloc), null);
   } catch (IOException e) {
     System.err.println("Error writing weights to file.");
     e.printStackTrace();
     System.exit(3);
   }
 }
  /**
   * converts a string into a valid CBR
   *
   * @param string the string to parse
   * @return the CBR to use
   * @throws Exception
   */
  private CBR parseCBR(String string) throws Exception {

    try {
      return (string == null) ? (null) : (new CBR(this)).parse(string);
    } catch (Exception e) {
      System.err.println("error parsing CBR, exiting.");
      e.printStackTrace();
      System.exit(5);
      return null;
    }
  }
  // TODO add exception for invalid options
  public Properties loadFromConfig(String fileLoc) {
    Properties configFile = new Properties();

    try {
      File localConfig = new File(fileLoc);
      InputStream is = null;
      if (localConfig.exists()) {
        is = new FileInputStream(localConfig);
      } else {
        System.err.println(
            "No configuration file at " + fileLoc + ". Please place one in the working directory.");
        System.exit(3);
      }
      configFile.load(is);
    } catch (IOException e) {
      e.printStackTrace();
      System.err.println("IOException reading first configuration file. Exiting...\n");
      System.exit(1);
    }

    return configFile;
  }
  /** loads [additional] policies from commandline (either -p or -f) */
  private void loadCLPolicies() {
    // we already checked to make sure we have one of the options avaliable
    File pLoc = null;
    PolicyObject p = null;

    if (genProps.getProperty("p3pLocation", null) != null) {
      pLoc = new File(genProps.getProperty("p3pLocation"));
      if (!pLoc.exists()) {
        System.err.println(
            "no file found at p3p policy location specified by the -p3p option: "
                + genProps.getProperty("p3pLocation"));
        System.err.println("current location is " + System.getProperty("user.dir"));
        System.exit(1);
      }
      try {
        p = (new P3PParser()).parse(pLoc.getAbsolutePath());
        if (p.getContextDomain() == null) {
          p.setContext(
              new Context(
                  new Date(System.currentTimeMillis()),
                  new Date(System.currentTimeMillis()),
                  genProps.getProperty("p3pLocation")));
        }
        pdb.addPolicy(p);
      } catch (Exception e) {
        System.err.println("Error with parsing or database");
        e.printStackTrace();
        // System.exit(5);
      }
    }
    if (genProps.getProperty("p3pDirLocation", null) != null) {
      pLoc = new File(genProps.getProperty("p3pDirLocation"));
      File[] pfiles = pLoc.listFiles();

      // System.err.println("pfiles for p3pDirLocation: "+pfiles);
      for (int i = 0; i < pfiles.length; i++) {

        pLoc = (pfiles[i]);
        if (!pLoc.exists()) {
          System.err.println(
              "no file found at p3p policy location specified by the -p3pDirLocation option, "
                  + genProps.getProperty("p3pDirLocation"));
          System.exit(1);
        }
        try {

          p = (new P3PParser()).parse(pLoc.getAbsolutePath());
          if (p.getContext().getDomain() == null) {
            p.setContext(
                new Context(
                    new Date(System.currentTimeMillis()),
                    new Date(System.currentTimeMillis()),
                    pfiles[i].getAbsolutePath()));
          }
          pdb.addPolicy(p);
        } catch (Exception e) {
          System.err.println("Einar needs to fix this parsing error.");
          e.printStackTrace();
        }
      }
    }
  }