Example #1
0
  /** store the given RenderingHints to a Properties object */
  public static void formatRenderingHints(RenderingHints rh, Properties preferences) {

    if (rh.get(RenderingHints.KEY_ANTIALIASING).equals(RenderingHints.VALUE_ANTIALIAS_ON))
      preferences.put("rendering.antialiasing", "on");
    else if (rh.get(RenderingHints.KEY_ANTIALIASING).equals(RenderingHints.VALUE_ANTIALIAS_OFF))
      preferences.put("rendering.antialiasing", "off");

    if (rh.get(RenderingHints.KEY_TEXT_ANTIALIASING).equals(RenderingHints.VALUE_TEXT_ANTIALIAS_ON))
      preferences.put("rendering.text-antialiasing", "on");
    else if (rh.get(RenderingHints.KEY_TEXT_ANTIALIASING)
        .equals(RenderingHints.VALUE_TEXT_ANTIALIAS_OFF))
      preferences.put("rendering.text-antialiasing", "off");

    if (rh.get(RenderingHints.KEY_RENDERING).equals(RenderingHints.VALUE_RENDER_SPEED))
      preferences.put("rendering.render", "speed");
    else if (rh.get(RenderingHints.KEY_RENDERING).equals(RenderingHints.VALUE_RENDER_QUALITY))
      preferences.put("rendering.render", "quality");

    if (rh.get(RenderingHints.KEY_DITHERING).equals(RenderingHints.VALUE_DITHER_ENABLE))
      preferences.put("rendering.dither", "on");
    else if (rh.get(RenderingHints.KEY_DITHERING).equals(RenderingHints.VALUE_DITHER_DISABLE))
      preferences.put("rendering.dither", "off");

    if (rh.get(RenderingHints.KEY_FRACTIONALMETRICS)
        .equals(RenderingHints.VALUE_FRACTIONALMETRICS_ON))
      preferences.put("rendering.fractional-metrics", "on");
    else if (rh.get(RenderingHints.KEY_FRACTIONALMETRICS)
        .equals(RenderingHints.VALUE_FRACTIONALMETRICS_OFF))
      preferences.put("rendering.fractional-metrics", "off");
  }
Example #2
0
 private void setTarget(Info info) {
   String factionInfo = info.getMessage().substring(11);
   String[] splitInfo = factionInfo.split("/");
   if (splitInfo.length != 2) {
     info.sendMessage("usage for !setTarget is !setTarget <faction>/<location>");
   } else {
     raidTarget.put(info.getChannel(), splitInfo[0]);
     raidLocation.put(info.getChannel(), splitInfo[1]);
     target(info);
   }
 }
Example #3
0
 /**
  * Gets a new Properties object initialised with the values from a Map. A null input will return
  * an empty properties object.
  *
  * @param map the map to convert to a Properties object
  * @return the properties object
  */
 public static Properties toProperties(Map map) {
   Properties answer = new Properties();
   if (map != null) {
     for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) {
       Map.Entry entry = (Map.Entry) iter.next();
       Object key = entry.getKey();
       Object value = entry.getValue();
       answer.put(key, value);
     }
   }
   return answer;
 }
Example #4
0
 /**
  * Helper method to convert properties to string.
  *
  * @param prop a <code>Properties</code> value
  * @return a <code>String</code> value
  */
 public static String convertPropsToString(Properties prop) {
   if (prop == null) {
     return "{null}";
   }
   StringBuffer strBuf = new StringBuffer("{ ");
   for (Enumeration enum1 = prop.propertyNames(); enum1.hasMoreElements(); ) {
     Object obj = enum1.nextElement();
     strBuf.append("[ ").append(obj).append("->");
     Object val = prop.getProperty((String) obj);
     if (val == null) strBuf.append("null");
     else strBuf.append((String) val);
     strBuf.append(" ] ");
   }
   strBuf.append("}");
   return strBuf.toString();
 }
  public static void sfSendEmail(String subject, String message) throws Exception {

    String SMTP_HOST_NAME = "smtp.gmail.com";
    String SMTP_PORT = "465";
    // message = "Test Email Notification From Monitor";
    // subject = "Test Email Notification From Monitor";
    String from = "*****@*****.**";
    String[] recipients = {
      "*****@*****.**", "*****@*****.**", "*****@*****.**"
    };
    String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    // String[] recipients = { "*****@*****.**"};
    // String[] recipients = { "*****@*****.**", "*****@*****.**",
    // "*****@*****.**", "*****@*****.**", "*****@*****.**",
    // "*****@*****.**", "*****@*****.**"};
    // String[] recipients = {"*****@*****.**"};

    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

    boolean debug = true;

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", "true");
    // props.put("mail.debug", "true");
    props.put("mail.smtp.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.put("mail.smtp.socketFactory.fallback", "false");

    Session session =
        Session.getDefaultInstance(
            props,
            new Authenticator() {

              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                    "*****@*****.**", "els102sensorweb");
              }
            });

    // session.setDebug(debug);

    Message msg = new MimeMessage(session);
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
      addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);

    System.out.println("Sucessfully Sent mail to All Users");
  }
Example #6
0
 /**
  * Return a integer parsed from the value associated with the given key, or "def" in key wasn't
  * found.
  */
 public static int parseProperty(Properties preferences, String key, int def) {
   String val = preferences.getProperty(key);
   if (val == null) return def;
   try {
     return Integer.parseInt(val);
   } catch (NumberFormatException nfe) {
     nfe.printStackTrace();
     return def;
   }
 }
Example #7
0
  /** Returns a RenderingHints parsed from the given Properties */
  public static RenderingHints parseRenderingHints(Properties preferences) {

    RenderingHints rh = new RenderingHints(null);
    String str;
    str = preferences.getProperty("rendering.antialiasing");
    if (str != null) {
      if (str.equals("on"))
        rh.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      else if (str.equals("off"))
        rh.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
    }
    str = preferences.getProperty("rendering.text-antialiasing");
    if (str != null) {
      if (str.equals("on"))
        rh.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
      else if (str.equals("off"))
        rh.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
    }
    str = preferences.getProperty("rendering.render");
    if (str != null) {
      if (str.equals("speed"))
        rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
      else if (str.equals("quality"))
        rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    }
    str = preferences.getProperty("rendering.dither");
    if (str != null) {
      if (str.equals("on"))
        rh.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
      else if (str.equals("off"))
        rh.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
    }
    str = preferences.getProperty("rendering.fractional-metrics");
    if (str != null) {
      if (str.equals("on"))
        rh.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
      else if (str.equals("off"))
        rh.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
    }
    return rh;
  }
Example #8
0
 /**
  * @return an ArrayList containing recent file names, fetched from the given key (e.g.
  *     PEMenuBar.KEY_RECENT_FILE)
  */
 public static ArrayList<String> parseRecentFiles(Properties preferences) {
   int i = 1;
   String fileName;
   ArrayList<String> list = new ArrayList<String>();
   // build key by appending ".X" where "X" runs from 1 to ...
   // i.e. fetch as many names as possible, until no key is found :
   while ((fileName = preferences.getProperty(KEY_RECENT_FILE + "." + Integer.toString(i++)))
       != null) {
     // System.out.println("filename=" + fileName + ";");
     if (!fileName.equals("") && !fileName.equals(" ")) {
       list.add(fileName);
     }
   }
   return list;
 }
Example #9
0
 private void target(Info info) {
   if (raidTarget.containsKey(info.getChannel())) {
     info.sendMessage(
         COLOR
             + "The raid target is "
             + raidTarget.get(info.getChannel())
             + " located at "
             + raidLocation.get(info.getChannel()));
   } else info.sendMessage("No target is set.");
 }
 public static Properties getEnvironmentVariables() {
   synchronized (cygstartPath) {
     if (envVars != null) return envVars;
     envVars = new Properties();
     try (BufferedReader br =
         new BufferedReader(
             new InputStreamReader(RUNTIME.exec(comSpec + "env").getInputStream()))) {
       for (String line = null; (line = br.readLine()) != null; ) {
         // if (debug) System.out.println("getEnvironmentVariables(): line=" + line);
         int idx = line.indexOf('=');
         if (idx > 0) envVars.put(line.substring(0, idx), line.substring(idx + 1));
       }
     } catch (IOException e) {
       e.printStackTrace();
     }
     return envVars;
   }
 }
Example #11
0
 private void go(Info info) {
   String msg = COLOR + Colors.BOLD + "MOVE OUT!";
   if (raidTarget.get(info.getChannel()) != null) {
     msg +=
         Colors.NORMAL
             + COLOR
             + " Target is "
             + raidTarget.get(info.getChannel())
             + " "
             + raidLocation.get(info.getChannel());
   }
   info.sendMessage(msg);
 }
Example #12
0
  /**
   * Add the given file name to the list of recent files in the given Properties object, trimming
   * the length of the list to 10. If the given name is already in the list, move it to the top.
   */
  public static void addRecentFile(Properties preferences, String newName) {

    // - if newName isn't already in the list, we add it to the top of the list.
    // - if it's already in the list, we move it to the top.
    ArrayList<String> list = MiscUtilities.parseRecentFiles(preferences);
    if (list.contains(newName)) {
      // move it to the top :
      list.remove(newName);
      list.add(0, newName);
    } else {
      list.add(0, newName);
    }
    // store to preferences :
    for (int i = 0; i < MAX_RECENT_FILES && i < list.size(); i++) {
      String key = KEY_RECENT_FILE + "." + Integer.toString(i + 1); // starts from 1
      String val = list.get(i);
      preferences.setProperty(key, val);
    }
  }
Example #13
0
File: Macro.java Project: bramk/bnd
 /**
  * Take all the properties and translate them to actual values. This method takes the set
  * properties and traverse them over all entries, including the default properties for that
  * properties. The values no longer contain macros.
  *
  * @return A new Properties with the flattened values
  */
 public Properties getFlattenedProperties() {
   // Some macros only work in a lower processor, so we
   // do not report unknown macros while flattening
   flattening = true;
   try {
     Properties flattened = new Properties();
     Properties source = domain.getProperties();
     for (Enumeration<?> e = source.propertyNames(); e.hasMoreElements(); ) {
       String key = (String) e.nextElement();
       if (!key.startsWith("_"))
         if (key.startsWith("-")) flattened.put(key, source.getProperty(key));
         else flattened.put(key, process(source.getProperty(key)));
     }
     return flattened;
   } finally {
     flattening = false;
   }
 }
Example #14
0
 /**
  * @return a double parsed from the value associated with the given key in the given Properties.
  *     returns "def" in key wasn't found, or if a parsing error occured. If "value" contains a "%"
  *     sign, we use a <code>NumberFormat.getPercentInstance</code> to convert it to a double.
  */
 public static double parseProperty(Properties preferences, String key, double def) {
   NumberFormat formatPercent = NumberFormat.getPercentInstance(Locale.US); // for zoom factor
   String val = preferences.getProperty(key);
   if (val == null) return def;
   if (val.indexOf("%") == -1) { // not in percent format !
     try {
       return Double.parseDouble(val);
     } catch (NumberFormatException nfe) {
       nfe.printStackTrace();
       return def;
     }
   }
   // else it's a percent format -> parse it
   try {
     Number n = formatPercent.parse(val);
     return n.doubleValue();
   } catch (ParseException ex) {
     ex.printStackTrace();
     return def;
   }
 }
Example #15
0
 /**
  * @return a Color built from the value fetched from the given key in the given properties, or the
  *     "def" value if the key wasn't found
  */
 public static Color parseProperty(Properties preferences, String key, Color def) {
   String val = preferences.getProperty(key);
   if (val == null) return def;
   return new Color(Integer.parseInt(val)); // [pending] should catch NFE here
 }
 /** Returns the setting of an environment variable set inside the JVM. */
 public static String getEnvironmentVariable(String envVarName) {
   if (envVars == null) envVars = getEnvironmentVariables();
   return (String) envVars.get(envVarName);
 }
  protected JFreeChart createChart(
      DSLAMSource source,
      String LID,
      Timeinterval time,
      Properties properties,
      GraphRenderingInput input,
      Map<String, Object> colorScheme,
      Properties outputProperties)
      throws IOException {
    JFreeChart res = null;

    {
      JFreeChart chart = null;

      Timeinterval domainAxisTime = null;

      // Set 'chart':
      {
        String domainAxisTitle = null;

        // Set 'domainAxisTime':
        {
          DateFormat format = (DateFormat) colorScheme.get("date.format");

          domainAxisTitle = "Time (" + time.toString(format) + ")";
        }

        chart =
            ChartFactory.createTimeSeriesChart(
                null, // chart-title
                domainAxisTitle, // domain-axis label
                null, // value-axis label
                null, // dataset
                true, // legends required
                true, // generate tooltips
                false // generate URLs
                );
      }

      XYPlot plot = chart.getXYPlot();

      plot.setOrientation(PlotOrientation.VERTICAL);
      plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
      plot.getRangeAxis().setFixedDimension(15.0);

      // Fix the domain axis:
      {
        fixDateAxisToTimeinterval(plot, time);
        domainAxisTime = time;
      }

      // Set the y-axis:
      {
        String axisTitle = "Count (/900s)";

        ValueAxis a = new LogarithmicAxis(axisTitle);
        a.setLowerBound(0);
        a.setUpperBound(1000); // TODO: '1000' is '900' rounded up to nearest power of 10!
        // TODO: Get unit from data-model!
        // TODO: Get upper bound from data-model!

        plot.setRangeAxis(a);
      }

      String title = getTitle();
      setDefaults(chart, colorScheme);
      setTitle(chart, LID, colorScheme, title, source, time);

      String filter = ""; // an empty string implies the default filter!

      // Set 'filter':
      {
        if (input != null) {
          Properties p = input.getProperties();
          if (p != null) {
            String v = p.getProperty("data.filter");
            if (v != null) {
              filter = v;
            }
          }
        }
      }

      addData(chart, source, time, filter, properties, colorScheme, outputProperties);

      if (outputProperties != null) {
        if (domainAxisTime != null) {
          outputProperties.setProperty("axis.domain.time", time.toString());
        }
      }

      res = chart;
    }

    return res;
  }
 /** Print all system property keys and values. */
 public static void printSystemProperties() {
   Properties p = System.getProperties();
   for (Object key : p.keySet()) System.out.println(key + ": " + p.getProperty(key.toString()));
 }
  private void addData(
      JFreeChart chart,
      DSLAMSource source,
      Timeinterval time,
      Serializable filter,
      Properties properties,
      Map<String, Object> colorScheme,
      Properties outputProperties)
      throws IOException {
    if (chart != null) {
      PerformanceCounterDataCollection cData = null;

      long dataSize = 0;

      try {
        cData =
            getPerformanceCounterDataCollection(source, time, filter, properties, outputProperties);
        Collection<PerformanceCounterData> data = null;

        Date d0 = null; // first timestamp for data
        Date d1 = null; // last timestamp for data
        RegularTimePeriod time0 = null;

        if (cData != null) {
          data = cData.getData();

          {
            int l = data.size();
            outputProperties.setProperty("data.count", Integer.toString(l));
          }

          if (data != null && data.size() > 0) {
            dataSize = data.size();

            // Set 'd0':
            {
              // TODO: Avoid assumption "data is sorted"!
              PerformanceCounterData e = data.iterator().next();
              d0 = e.getTimestamp();
            }

            // Set 'd1':
            {
              // TODO: Avoid assumption "data is sorted"!
              for (PerformanceCounterData e : data) {
                d1 = e.getTimestamp();
              }
            }

            time0 = createRegularTimePeriod(d0);
          }
        }

        XYPlot plot = chart.getXYPlot();

        // Set the first dataset:
        {
          TimeSeriesCollection dataset = new TimeSeriesCollection();

          List<Paint> seriesPaint = new ArrayList<Paint>();
          List<Stroke> seriesStroke = new ArrayList<Stroke>();

          // Add series 'ES':
          {
            if (data != null && data.size() > 0) {
              TimeSeries series = new TimeSeries("ES", time0.getClass());

              for (PerformanceCounterData e : data) {
                Date d = e.getTimestamp();
                RegularTimePeriod timePeriod = createRegularTimePeriod(d);

                // Add point:
                {
                  int value = getES(e);

                  addOrUpdate(series, timePeriod, (double) value);
                }
              }

              seriesPaint.add((Paint) colorScheme.get("color.counter.es"));
              seriesStroke.add(STROKE_COUNTER_ES);

              dataset.addSeries(series);
            }
          }

          // Add series 'SES':
          {
            if (data != null && data.size() > 0) {
              TimeSeries series = new TimeSeries("SES", time0.getClass());

              for (PerformanceCounterData e : data) {
                Date d = e.getTimestamp();
                RegularTimePeriod timePeriod = createRegularTimePeriod(d);

                // Add point:
                {
                  int value = getSES(e);

                  addOrUpdate(series, timePeriod, (double) value);
                }
              }

              seriesPaint.add((Paint) colorScheme.get("color.counter.ses"));
              seriesStroke.add(STROKE_COUNTER_SES);

              dataset.addSeries(series);
            }
          }

          // Add series 'US':
          {
            if (data != null && data.size() > 0) {
              TimeSeries series = new TimeSeries("US", time0.getClass());

              for (PerformanceCounterData e : data) {
                Date d = e.getTimestamp();
                RegularTimePeriod timePeriod = createRegularTimePeriod(d);

                // Add point:
                {
                  int value = getUS(e);

                  addOrUpdate(series, timePeriod, (double) value);
                }
              }

              seriesPaint.add((Paint) colorScheme.get("color.counter.us"));
              seriesStroke.add(STROKE_COUNTER_US);

              dataset.addSeries(series);
            }
          }

          // superspeed
          {
            if (data != null && data.size() > 0) {
              TimeSeries series = new TimeSeries("LEFTRS", time0.getClass());
              for (PerformanceCounterData e : data) {
                Date d = e.getTimestamp();
                RegularTimePeriod timePeriod = createRegularTimePeriod(d);
                {
                  int value = getPreviousLEFTRS(e);
                  addOrUpdate(series, timePeriod, (double) value);
                }
              }
              seriesPaint.add((Paint) colorScheme.get("color.counter.previousleftrs"));
              seriesStroke.add(STROKE_COUNTER_US);
              dataset.addSeries(series);
            }
          }
          // ends
          {
            if (data != null && data.size() > 0) {
              boolean showLinearCurve = getShowLinearCurve();

              if (showLinearCurve) {
                // Add series for a linear curve:
                {
                  TimeSeries series = new TimeSeries("Linear", time0.getClass());

                  long t0 = d0.getTime();
                  long t1 = d1.getTime();

                  if (t0 < t1) {
                    long timeX = 15 * 60 * 1000; // 15 minutes intervals
                    // TODO: Read length of intervals from obtained data!

                    double value0 = 0;
                    double value1 = 900;
                    // TODO: Read '900' from obtained data!

                    long timeDelta = t1 - t0;
                    double valueDelta = value1 - value0;

                    long t = t0;
                    int i = 0;

                    while (t <= t1) {
                      Date d = new Date(t);

                      RegularTimePeriod timePeriod = createRegularTimePeriod(d);
                      double value = value0 + ((t - t0) * valueDelta) / timeDelta;

                      // Add point:
                      {
                        addOrUpdate(series, timePeriod, (double) value);
                      }

                      t += timeX;
                      i += 1;
                    }
                  }

                  seriesPaint.add(Color.red);
                  seriesStroke.add(STROKE_COUNTER_DEFAULT);

                  dataset.addSeries(series);
                }
              }
            }
          }

          setDefaultRenderer(chart, colorScheme, 0, seriesPaint, seriesStroke);
          plot.setDataset(0, dataset);
          plot.mapDatasetToRangeAxis(0, 0);
        }
      } finally {
        if (cData != null) {
          cData.dispose();
          cData = null;
        }
      }

      if (outputProperties != null) {
        outputProperties.setProperty("data.count", Long.toString(dataSize));
      }
    }
  }
Example #20
0
 private void setPath(Info info) {
   String path = info.getMessage().substring(8);
   raidPath.put(info.getChannel(), path);
   info.sendMessage("The path to the target is set.");
 }
Example #21
0
 private void path(Info info) {
   if (raidPath.containsKey(info.getChannel())) {
     info.sendMessage(COLOR + raidPath.get(info.getChannel()));
   } else info.sendMessage("No path to the target is set.");
 }
Example #22
0
 private void clearStats(Info info) {
   raidTarget.remove(info.getChannel());
   raidLocation.remove(info.getChannel());
   raidPath.remove(info.getChannel());
   info.sendMessage("Raid status cleared.");
 }
Example #23
0
 /**
  * @return a boolean built from the value fetched from the given key in the given properties, or
  *     the "def" value if the key wasn't found
  */
 public static boolean parseProperty(Properties preferences, String key, boolean def) {
   String val = preferences.getProperty(key);
   if (val == null) return def;
   if (val.equals("true") || val.equals("on") || val.equals("yes")) return true;
   return false;
 }
Example #24
0
  /**
   * Takes a vector full of property lists and generates a report.
   *
   * @param args Command line arguments. args[0] should be the config filename.
   */
  public static void main(String[] args) {
    // Load the database properties from properties file
    Properties properties = new Properties();

    // Load config file
    String configFile = null;
    if (args.length > 0) configFile = args[0];

    try {
      if (configFile == null) {
        System.out.println("Database config file not set.");
        return;
      } else properties.load(new FileInputStream(configFile));
    } catch (IOException e) {
      System.out.println("Error opening config file.");
    }

    String url = properties.getProperty("databaseUrl");
    String username = properties.getProperty("username");
    String password = properties.getProperty("password");
    String dir = System.getProperty("user.dir"); // Current working directory
    Connection con = null;

    // Try to open file containing javac output
    String output = "";
    try {
      BufferedReader outputReader = new BufferedReader(new FileReader(dir + "/CompileOut.txt"));

      while (outputReader.ready()) output += outputReader.readLine() + '\n';

      // Close file
      outputReader.close();
    } catch (FileNotFoundException e) {
      System.out.println("Error opening compilation output file.");
      return;
    } catch (IOException e) {
      System.out.println("I/O Exception Occured.");
      return;
    }

    boolean hasDriver = false;
    // Create class for the driver
    try {
      Class.forName("com.mysql.jdbc.Driver");
      hasDriver = true;
    } catch (Exception e) {
      System.out.println("Failed to load MySQL JDBC driver class.");
    }

    // Create connection to database if the driver was found
    if (hasDriver) {
      try {
        con = DriverManager.getConnection(url, username, password);
      } catch (SQLException e) {
        System.out.println("Couldn't get connection!");
      }
    }

    // Check that a connection was made
    if (con != null) {
      long userEventId = -1;

      // Store results from the report into the database
      try {
        BufferedReader rd =
            new BufferedReader(
                new FileReader(dir + "/userId.txt")); // Read userId.txt to get userId
        String userId = rd.readLine(); // Store userId from text file
        rd.close();

        // Insert the report into the table and get the auto_increment id for it
        Statement stmt = con.createStatement();
        stmt.executeUpdate("INSERT INTO userEvents (userId) VALUES ('" + userId + "')");
        ResultSet result = stmt.getGeneratedKeys();
        result.next();
        userEventId = result.getLong(1);

        // Close the statement
        stmt.close();

        // Prepare statement for adding the compilation error to the userEvent
        PreparedStatement compErrorPrepStmt =
            con.prepareStatement(
                "INSERT INTO userEventCompilationErrors(userEventId, output) VALUES (?, ?)");

        // Insert userEventId and docletId into the database
        compErrorPrepStmt.setLong(1, userEventId);
        compErrorPrepStmt.setString(2, output);
        compErrorPrepStmt.executeUpdate();

        // Close the prepare statements
        compErrorPrepStmt.close();
      } catch (Exception e) {
        System.out.println("Exception Occurred");
        System.out.println(e);
      }

      // Store the java files for the report
      try {
        // Prepare statement for storing files
        PreparedStatement filePrepStmt =
            con.prepareStatement(
                "INSERT INTO files(userEventId, filename, contents) VALUES ("
                    + userEventId
                    + ", ?, ?)");

        // Get the list of files from source.txt
        BufferedReader rd =
            new BufferedReader(
                new FileReader(dir + "/source.txt")); // Read userId.txt to get userId
        while (rd.ready()) {
          String filename = rd.readLine(); // Store userId from text file
          // Remove the "src/" from the beginning to get the real file name
          String realname = filename.substring(4);
          filePrepStmt.setString(1, realname);

          // Read in the contents of the files
          String contents = "";
          File javaFile = new File(dir + "/" + filename);
          int length = (int) javaFile.length();

          // Add parameter for file contents to the prepared statement and execute it
          filePrepStmt.setCharacterStream(2, new BufferedReader(new FileReader(javaFile)), length);
          filePrepStmt.executeUpdate();
        }
        rd.close();
      } catch (IOException e) {
        System.err.println("I/O Exception Occured.");
      } catch (SQLException e) {
        System.err.println("SQL Exception Occured.");
      }
    }
  }
  @Override
  public Response serve(String uri, String method, Properties header, Properties parms) {
    if (!uri.equals("/mediaserver")) {
      return super.serve(uri, method, header, parms); // this way we can
      // also serve up
      // normal files and
      // content
    }

    logger.fine(method + " '" + uri + "' ");

    Enumeration<?> e = header.propertyNames();
    while (e.hasMoreElements()) {
      String value = (String) e.nextElement();
      logger.fine("  HDR: '" + value + "' = '" + header.getProperty(value) + "'");
    }
    e = parms.propertyNames();
    while (e.hasMoreElements()) {
      String value = (String) e.nextElement();
      logger.fine("  PRM: '" + value + "' = '" + parms.getProperty(value) + "'");
    }

    // TODO: check the actual path...

    final String mediaPath = parms.getProperty("media");
    final String outputFormatStr = parms.getProperty("format");
    final String mimeType = parms.getProperty("mime");
    logger.info("requested media: " + mediaPath);
    logger.info("requested mime type: " + mimeType);
    if (mediaPath == null)
      return new Response(HTTP_FORBIDDEN, "text/plain", "mediaPath parameter not specified");
    if (mimeType == null)
      return new Response(HTTP_FORBIDDEN, "text/plain", "mimeType parameter not specified");

    // TODO: if we aren't performing any transcoding, just serve the file up
    // directly.
    // TODO: capture sources need to be treated as singletons, with some
    // kind of broadcasting/cloning to ensure
    // that multiple connections can be made.

    final String serverSideUrlStr = mediaPath; // URLUtils.createUrlStr(new
    // File(mediaPath)); // TODO:
    // enforce that we can't just
    // serve up anything anywhere
    final ContentDescriptor outputContentDescriptor =
        new FileTypeDescriptor(ContentDescriptor.mimeTypeToPackageName(mimeType));

    final Format outputFormat;
    if (outputFormatStr == null) {
      outputFormat = null;
    } else {
      try {
        outputFormat = FormatArgUtils.parse(outputFormatStr);
      } catch (ParseException e1) {
        logger.log(Level.WARNING, "" + e1, e1);
        return new Response(HTTP_FORBIDDEN, "text/plain", "" + e1);
      }
    }

    logger.info("serverSideUrlStr: " + serverSideUrlStr);
    logger.info("outputContentDescriptor: " + outputContentDescriptor);
    logger.info("outputFormat: " + outputFormat);

    final InputStream is;
    try {
      is = getInputStream(serverSideUrlStr, outputFormat, outputContentDescriptor);
    } catch (Exception e1) {
      return new Response(HTTP_FORBIDDEN, "text/plain", "" + e1);
    }

    final String responseMimeType;
    // workaround for the problem that the multipart/x-mixed-replace
    // boundary is not stored anywhere.
    // this assumes that if we are serving multipart/x-mixed-replace data,
    // that MultipartMixedReplaceMux is being used.
    if (mimeType.equals("multipart/x-mixed-replace"))
      responseMimeType = mimeType + ";boundary=" + MultipartMixedReplaceMux.BOUNDARY;
    else responseMimeType = mimeType;
    logger.info("Response mime type: " + responseMimeType);
    return new Response(HTTP_OK, responseMimeType, is);
  }
  public static void sendEmail(String subject, String message) throws Exception {
    /*
    String mailhost = "mail.vancouver.wsu.edu";
    String cc = null;
    String bcc = null;
    boolean debug = false;
    String file = null;
    String mailer = "msgsend";
    String sender = "mail.vancouver.wsu.edu";


       Properties props = System.getProperties();

       if (mailhost != null)
    props.put("mail.smtp.host", mailhost);

       // Get a Session object
       Session session = Session.getInstance(props, null);

    if (debug)
    session.setDebug(true);

       // construct the message
       Message msg = new MimeMessage(session);
       if (sender != null)
    msg.setFrom(new InternetAddress(sender));
       else
    msg.setFrom();

       msg.setRecipients(Message.RecipientType.TO,
    			InternetAddress.parse(receivers[0], false));

       if (cc != null)
    msg.setRecipients(Message.RecipientType.CC,
    			InternetAddress.parse(cc, false));
       if (bcc != null)
    msg.setRecipients(Message.RecipientType.BCC,
    			InternetAddress.parse(bcc, false));

       msg.setSubject(subject);

       String text = content;

       if (file != null) {
    // Attach the specified file.
    // We need a multipart message to hold the attachment.
    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(text);
    MimeBodyPart mbp2 = new MimeBodyPart();
    mbp2.attachFile(file);
    MimeMultipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);
    mp.addBodyPart(mbp2);
    msg.setContent(mp);
       } else {
    // If the desired charset is known, you can use
    // setText(text, charset)
    msg.setText(text);
       }

       msg.setHeader("X-Mailer", mailer);
       msg.setSentDate(new Date());

       // send the thing off
       Transport.send(msg);

       System.out.println("\nMail was sent successfully.");
    */

    // Xiaogang: checkbox
    // System.out.println("sendemail"+MainFrame.EMAIL_ENABLE);
    if (MainFrame.EMAIL_ENABLE == false) return;

    String SMTP_HOST_NAME = "smtp.gmail.com";
    String SMTP_PORT = "465";
    // message = "Test Email Notification From Monitor";
    // subject = "Test Email Notification From Monitor";
    String from = "*****@*****.**";
    String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    String[] recipients = {
      "*****@*****.**", "*****@*****.**", "*****@*****.**"
    };
    // String[] recipients = { "*****@*****.**"};
    // String[] recipients = { , "*****@*****.**", "*****@*****.**",
    // "*****@*****.**", "*****@*****.**"};
    // String[] recipients = {"*****@*****.**"};

    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

    boolean debug = true;

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", "true");
    // props.put("mail.debug", "true");
    props.put("mail.smtp.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.put("mail.smtp.socketFactory.fallback", "false");

    Session session =
        Session.getDefaultInstance(
            props,
            new Authenticator() {

              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                    "*****@*****.**", "els102sensorweb");
              }
            });

    // session.setDebug(debug);

    Message msg = new MimeMessage(session);
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
      addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);

    System.out.println("Sucessfully Sent mail to All Users");
  }