示例#1
0
  /**
   * Prints the given map with nice line breaks.
   *
   * @param out the stream to print to
   * @param key the key that maps to the map in some other map
   * @param map the map to print
   */
  public static synchronized void debugPrint(PrintStream out, Object key, Map map) {
    debugPrintIndent(out);
    out.println(key + " = ");

    debugPrintIndent(out);
    out.println("{");
    ++debugIndent;

    for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) {
      Map.Entry entry = (Map.Entry) iter.next();
      String childKey = (String) entry.getKey();
      Object childValue = entry.getValue();
      if (childValue instanceof Map) {
        verbosePrint(out, childKey, (Map) childValue);
      } else {
        debugPrintIndent(out);

        String typeName = (childValue != null) ? childValue.getClass().getName() : null;

        out.println(childKey + " = " + childValue + " class: " + typeName);
      }
    }
    --debugIndent;
    debugPrintIndent(out);
    out.println("}");
  }
  private void sendProcessingError(Throwable t, ServletResponse response) {

    String stackTrace = getStackTrace(t);

    if (stackTrace != null && !stackTrace.equals("")) {

      try {

        response.setContentType("text/html");
        PrintStream ps = new PrintStream(response.getOutputStream());
        PrintWriter pw = new PrintWriter(ps);
        pw.print("<html>\n<head>\n</head>\n<body>\n"); // NOI18N

        // PENDING! Localize this for next official release
        pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
        pw.print(stackTrace);
        pw.print("</pre></body>\n</html>"); // NOI18N
        pw.close();
        ps.close();
        response.getOutputStream().close();
        ;
      } catch (Exception ex) {
      }
    } else {
      try {
        PrintStream ps = new PrintStream(response.getOutputStream());
        t.printStackTrace(ps);
        ps.close();
        response.getOutputStream().close();
        ;
      } catch (Exception ex) {
      }
    }
  }
示例#3
0
    //
    // Runnable interface
    //
    public void run() {

      // output all active probes
      for (PerformanceProbe probe : list(ALL_RECORDERS)) {
        probe.output("F");
      }

      // close output if not standard output
      if (!outputStream.equals(System.out)) {
        outputStream.close();
      }
    }
  /**
   * Set current font. Default to Plain Courier 11 if null.
   *
   * @param font new font.
   */
  public void setFont(Font font) {

    if (font != null) {
      m_localGraphicsState.setFont(font);
      if (font.getName().equals(m_psGraphicsState.getFont().getName())
          && (m_psGraphicsState.getFont().getStyle() == font.getStyle())
          && (m_psGraphicsState.getFont().getSize() == yScale(font.getSize()))) return;
      m_psGraphicsState.setFont(
          new Font(font.getName(), font.getStyle(), yScale(getFont().getSize())));
    } else {
      m_localGraphicsState.setFont(new Font("Courier", Font.PLAIN, 11));
      m_psGraphicsState.setFont(getFont());
    }

    m_printstream.println("/(" + replacePSFont(getFont().getPSName()) + ")" + " findfont");
    m_printstream.println(yScale(getFont().getSize()) + " scalefont setfont");
  }
示例#5
0
 //
 // PROBE OUTPUT
 //
 private void output(String type) {
   StringBuffer result = new StringBuffer(128);
   result.append(time()).append(" ");
   result.append(type).append(" ");
   result.append(probeName).append(": ");
   result.append(toString());
   outputStream.println(result.toString());
 }
 /**
  * Draw a filled rectangle in current pen color.
  *
  * @param x starting x coord
  * @param y starting y coord
  * @param width rectangle width
  * @param height rectangle height
  */
 public void fillRect(int x, int y, int width, int height) {
   if (width == m_extent.width && height == m_extent.height) {
     clearRect(x, y, width, height); // if we're painting the entire background, just make it white
   } else {
     if (DEBUG) m_printstream.println("% fillRect");
     setStateToLocal();
     m_printstream.println(
         xTransform(xScale(x))
             + " "
             + yTransform(yScale(y))
             + " "
             + xScale(width)
             + " "
             + yScale(height)
             + " true Rect");
   }
 }
  /**
   * Executes command using {@code shell} channel.
   *
   * @param ses SSH session.
   * @param cmd Command.
   * @throws JSchException In case of SSH error.
   * @throws IOException If IO error occurs.
   * @throws IgniteInterruptedCheckedException If thread was interrupted while waiting.
   */
  private void shell(Session ses, String cmd)
      throws JSchException, IOException, IgniteInterruptedCheckedException {
    ChannelShell ch = null;

    try {
      ch = (ChannelShell) ses.openChannel("shell");

      ch.connect();

      try (PrintStream out = new PrintStream(ch.getOutputStream(), true)) {
        out.println(cmd);

        U.sleep(1000);
      }
    } finally {
      if (ch != null && ch.isConnected()) ch.disconnect();
    }
  }
 /**
  * Draw text in current pen color.
  *
  * @param str Text to output
  * @param x starting x coord
  * @param y starting y coord
  */
 public void drawString(String str, int x, int y) {
   setStateToLocal();
   m_printstream.println(
       xTransform(xScale(x))
           + " "
           + yTransform(yScale(y))
           + " moveto"
           + " ("
           + escape(str)
           + ") show stroke");
 }
示例#9
0
  /**
   * Changes the output of all probes to the specified file. This method may be called multiple
   * times during the execution of the JVM.
   *
   * @param pathname the pathname of the output file.
   */
  public static void setOutput(String pathname) {

    // open specified file
    PrintStream previous = outputStream;
    try {
      outputStream = new PrintStream(new FileOutputStream(pathname));
    } catch (FileNotFoundException e) {
      // if file cannot be opened, output remains unchanged
      return;
    }

    // close previous output if not standard output
    if (previous != null && !previous.equals(System.out)) {
      previous.close();
    }

    // print date and time
    Format format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    outputStream.println("Starting on " + format.format(new Date()));
  }
 /**
  * Draw a filled Oval in current pen color.
  *
  * @param x x-axis center of oval
  * @param y y-axis center of oval
  * @param width oval width
  * @param height oval height
  */
 public void fillOval(int x, int y, int width, int height) {
   setStateToLocal();
   m_printstream.println(
       xTransform(xScale(x))
           + " "
           + yTransform(yScale(y))
           + " "
           + xScale(width)
           + " "
           + yScale(height)
           + " true Oval");
 }
 /**
  * Draw an outlined rectangle in current pen color.
  *
  * @param x starting x coord
  * @param y starting y coord
  * @param width rectangle width
  * @param height rectangle height
  */
 public void drawRect(int x, int y, int width, int height) {
   setStateToLocal();
   m_printstream.println(
       xTransform(xScale(x))
           + " "
           + yTransform(yScale(y))
           + " "
           + xScale(width)
           + " "
           + yScale(height)
           + " false Rect");
 }
 /**
  * Draw a line in current pen color.
  *
  * @param x1 starting x coord
  * @param y1 starting y coord
  * @param x2 ending x coord
  * @param y2 ending y coord
  */
 public void drawLine(int x1, int y1, int x2, int y2) {
   setStateToLocal();
   m_printstream.println(
       xTransform(xScale(x1))
           + " "
           + yTransform(yScale(y1))
           + " moveto "
           + xTransform(xScale(x2))
           + " "
           + yTransform(yScale(y2))
           + " lineto stroke");
 }
 /**
  * Draw a filled rectangle with the background color.
  *
  * @param x starting x coord
  * @param y starting y coord
  * @param width rectangle width
  * @param height rectangle height
  */
 public void clearRect(int x, int y, int width, int height) {
   setStateToLocal();
   Color saveColor = getColor();
   setColor(Color.white); // background color for page
   m_printstream.println(
       xTransform(xScale(x))
           + " "
           + yTransform(yScale(y))
           + " "
           + xScale(width)
           + " "
           + yScale(height)
           + " true Rect");
   setColor(saveColor);
 }
 /**
  * Set current pen color. Default to black if null.
  *
  * @param c new pen color.
  */
 public void setColor(Color c) {
   if (c != null) {
     m_localGraphicsState.setColor(c);
     if (m_psGraphicsState.getColor().equals(c)) {
       return;
     }
     m_psGraphicsState.setColor(c);
   } else {
     m_localGraphicsState.setColor(Color.black);
     m_psGraphicsState.setColor(getColor());
   }
   m_printstream.print(getColor().getRed() / 255.0);
   m_printstream.print(" ");
   m_printstream.print(getColor().getGreen() / 255.0);
   m_printstream.print(" ");
   m_printstream.print(getColor().getBlue() / 255.0);
   m_printstream.println(" setrgbcolor");
 }
示例#15
0
  /** main method - entry point for the entire program */
  public static void main(String[] args)
      throws IOException // just let IOExceptions terminate the program
      {
    // initialize loan variables from constants
    final double principal = PRINCIPAL;
    final double rate = RATE / 100; // convert rate into decimal form
    final double numPayments = TERM * MONTHS_PER_YEAR;

    // create output and input objects
    final PrintStream out = System.out;
    final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    // display the header for this assignment
    out.println("Name            : David C. Gibbons   ");
    out.println("Assignment      : Workshop 3         ");
    out.println("-------------------------------------");

    // determine interest rate per month
    final double monthlyRate = (rate / MONTHS_PER_YEAR);

    // calculate monthly payment
    final double monthlyPayment =
        principal * (monthlyRate / (1 - Math.pow(1 + monthlyRate, -numPayments)));

    // fetch needed decimal formatters needed for output
    final DecimalFormat numberFmt = new DecimalFormat("#0");
    final DecimalFormat currencyFmt = new DecimalFormat("$0.00");
    final DecimalFormat percentFmt = new DecimalFormat("0.00 %");

    // display overall loan information
    out.println("Principal       : " + currencyFmt.format(principal));
    out.println("Interest Rate   : " + percentFmt.format(rate));
    out.println("# of payments   : " + numberFmt.format(numPayments));
    out.println("Monthly payment : " + currencyFmt.format(monthlyPayment));

    // wait for the user to continue and then display the
    // details of all the payments
    out.println();
    out.println("Hit Enter to list Payment Detail");
    in.readLine();

    // calculate the payment detail in yearly blocks
    double currentPrincipal = principal;
    for (int month = 0; month < numPayments; month++) {
      // display header to match the benchmark at the start of the year
      if (month == 0 || (month % MONTHS_PER_YEAR) == 0) {
        // display a pause prompt if this isn't the first year
        if (month > 0) {
          out.println();
          out.println(" Hit Enter to continue");
          in.readLine();
        }
        out.println();
        out.println("\tInterest  Principal     Principal");
        out.println("Months\tPayment   Payment       Balance");
        out.println();
      }

      // calculate this month's interest payment and then the
      // principal payment and remaining principal balance
      double interestPayment = rate / MONTHS_PER_YEAR * currentPrincipal;
      double principalPayment = monthlyPayment - interestPayment;

      // always get the absolute value of the current principal as
      // sometimes the final value of 0 can be -0.0
      currentPrincipal = Math.abs(currentPrincipal - principalPayment);

      // format the fields and display to match benchmark
      out.print(numberFmt.format(month + 1) + " \t");
      out.print(currencyFmt.format(interestPayment) + "\t  ");
      out.print(currencyFmt.format(principalPayment) + "\t");
      out.println(currencyFmt.format(currentPrincipal));
    }
  }
示例#16
0
  public static void main(String[] args) {
    if (args.length != 2) {
      System.out.println(
          "Usage: java Purger <folder> <date>\n"
              + " - folder: is the path to account.txt and athena.txt files.\n"
              + " - date: accounts created before this date will be purged (dd/mm/yy or yyyy-mm-dd).");
      return;
    }

    int accounts = 0;
    int characters = 0;
    int deletedCharacters = 0;
    Vector activeAccounts = new Vector();

    File folder = new File(args[0]);
    // Do some sanity checking
    if (!folder.exists()) {
      System.out.println("Folder does not exist!");
      return;
    }
    if (!folder.isDirectory()) {
      System.out.println("Folder is not a folder!");
      return;
    }

    File oldAccount = new File(folder, "account.txt");
    File oldAthena = new File(folder, "athena.txt");
    File newAccount = new File(folder, "account.txt.new");
    File newAthena = new File(folder, "athena.txt.new");

    DateFormat dateFormat;
    Date purgeDate = null;

    for (String format : new String[] {"dd/MM/yy", "yyyy-MM-dd"}) {
      dateFormat = new SimpleDateFormat(format);

      try {
        purgeDate = dateFormat.parse(args[1]);
        break;
      } catch (ParseException e) {
      }
    }

    if (purgeDate == null) {
      System.out.println("ERROR: Date format not recognized.");
      return;
    }

    String line;

    // Remove accounts
    try {
      FileInputStream fin = new FileInputStream(oldAccount);
      BufferedReader input = new BufferedReader(new InputStreamReader(fin));
      FileOutputStream fout = new FileOutputStream(newAccount);
      PrintStream output = new PrintStream(fout);

      while ((line = input.readLine()) != null) {
        boolean copy = false;
        String[] fields = line.split("\t");
        // Check if we're reading a comment or the last line
        if (line.substring(0, 2).equals("//") || fields[1].charAt(0) == '%') {
          copy = true;
        } else {
          // Server accounts should not be purged
          if (!fields[4].equals("S")) {
            accounts++;
            dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
              Date date = dateFormat.parse(fields[3]);
              if (date.after(purgeDate)) {
                activeAccounts.add(fields[0]);
                copy = true;
              }
            } catch (ParseException e) {
              System.out.println(
                  "ERROR: Wrong date format in account.txt. (" + accounts + ": " + line + ")");
              // return;
            } catch (Exception e) {
              e.printStackTrace();
              return;
            }
          } else {
            copy = true;
          }
        }
        if (copy) {
          try {
            output.println(line);
          } catch (Exception e) {
            System.err.println("ERROR: Unable to write file.");
          }
        }
      }
      input.close();
      output.close();
    } catch (FileNotFoundException e) {
      System.out.println("ERROR: file " + oldAccount.getAbsolutePath() + " not found.");
      return;
    } catch (Exception e) {
      System.out.println("ERROR: unable to process account.txt");
      e.printStackTrace();
      return;
    }

    System.out.println(
        "Removed " + (accounts - activeAccounts.size()) + "/" + accounts + " accounts.");

    // Remove characters
    try {
      FileInputStream fin = new FileInputStream(oldAthena);
      BufferedReader input = new BufferedReader(new InputStreamReader(fin));
      FileOutputStream fout = new FileOutputStream(newAthena);
      PrintStream output = new PrintStream(fout);

      while ((line = input.readLine()) != null) {
        boolean copy = false;
        String[] fields = line.split("\t");
        // Check if we're reading a comment or the last line
        if (line.substring(0, 2).equals("//") || fields[1].charAt(0) == '%') {
          copy = true;
        } else {
          characters++;
          String id = fields[1].substring(0, fields[1].indexOf(','));
          if (activeAccounts.contains(id)) {
            copy = true;
          } else {
            deletedCharacters++;
          }
        }
        if (copy) {
          output.println(line);
        }
      }
      input.close();
      output.close();
    } catch (FileNotFoundException e) {
      System.out.println("ERROR: file " + oldAthena.getAbsolutePath() + " not found.");
      return;
    } catch (Exception e) {
      System.out.println("ERROR: unable to process athena.txt");
      e.printStackTrace();
      return;
    }

    System.out.println("Removed " + deletedCharacters + "/" + characters + " characters.");
  }
 /**
  * print the overall stats of the <tt>MediaStream</tt> this <tt>MediaStreamStats</tt> keep track
  * to the PrintStream given as argument.
  *
  * @param ps the <tt>PrintStream</tt> used to print the stats
  */
 public void printOverallStats(PrintStream ps) {
   ps.println(getOverallStatsJSON());
 }
示例#18
0
 /**
  * Writes indentation to the given stream.
  *
  * @param out the stream to indent
  */
 protected static void debugPrintIndent(PrintStream out) {
   for (int i = 0; i < debugIndent; i++) {
     out.print("    ");
   }
 }
  /** Output postscript header to PrintStream, including helper macros. */
  private void Header() {
    m_printstream.println("%!PS-Adobe-3.0 EPSF-3.0");
    m_printstream.println(
        "%%BoundingBox: 0 0 " + xScale(m_extent.width) + " " + yScale(m_extent.height));
    m_printstream.println("%%CreationDate: " + Calendar.getInstance().getTime());

    m_printstream.println("/Oval { % x y w h filled");
    m_printstream.println("gsave");
    m_printstream.println("/filled exch def /h exch def /w exch def /y exch def /x exch def");
    m_printstream.println("x w 2 div add y h 2 div sub translate");
    m_printstream.println("1 h w div scale");
    m_printstream.println("filled {0 0 moveto} if");
    m_printstream.println("0 0 w 2 div 0 360 arc");
    m_printstream.println("filled {closepath fill} {stroke} ifelse grestore} bind def");

    m_printstream.println("/Rect { % x y w h filled");
    m_printstream.println("/filled exch def /h exch def /w exch def /y exch def /x exch def");
    m_printstream.println("newpath ");
    m_printstream.println("x y moveto");
    m_printstream.println("w 0 rlineto");
    m_printstream.println("0 h neg rlineto");
    m_printstream.println("w neg 0 rlineto");
    m_printstream.println("closepath");
    m_printstream.println("filled {fill} {stroke} ifelse} bind def");

    m_printstream.println("%%BeginProlog\n%%EndProlog");
    m_printstream.println("%%Page 1 1");
    setFont(null); // set to default
    setColor(null); // set to default
    setStroke(null); // set to default
  }
 /** Clone a PostscriptGraphics object */
 public Graphics create() {
   if (DEBUG) m_printstream.println("%create");
   PostscriptGraphics psg = new PostscriptGraphics(this);
   return (psg);
 }
  /**
   * PS see http://astronomy.swin.edu.au/~pbourke/geomformats/postscript/ Java
   * http://show.docjava.com:8086/book/cgij/doc/ip/graphics/SimpleImageFrame.java.html
   */
  public boolean drawImage(
      Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer) {
    try {
      // get data from image
      int[] pixels = new int[width * height];
      PixelGrabber grabber = new PixelGrabber(img, 0, 0, width, height, pixels, 0, width);
      grabber.grabPixels();
      ColorModel model = ColorModel.getRGBdefault();

      // print data to ps
      m_printstream.println("gsave");
      m_printstream.println(
          xTransform(xScale(x)) + " " + (yTransform(yScale(y)) - yScale(height)) + " translate");
      m_printstream.println(xScale(width) + " " + yScale(height) + " scale");
      m_printstream.println(
          width + " " + height + " " + "8" + " [" + width + " 0 0 " + (-height) + " 0 " + height
              + "]");
      m_printstream.println("{<");

      int index;
      for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
          index = i * width + j;
          m_printstream.print(toHex(model.getRed(pixels[index])));
          m_printstream.print(toHex(model.getGreen(pixels[index])));
          m_printstream.print(toHex(model.getBlue(pixels[index])));
        }
        m_printstream.println();
      }

      m_printstream.println(">}");
      m_printstream.println("false 3 colorimage");
      m_printstream.println("grestore");
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
 /** Finalizes output file. */
 public void finished() {
   m_printstream.flush();
 }