Ejemplo n.º 1
1
 private String getDate(String timeStampStr, String format) {
   DateFormat formatter = new SimpleDateFormat(format);
   long timeStamp = Long.parseLong(timeStampStr);
   Calendar calendar = Calendar.getInstance();
   calendar.setTimeInMillis(timeStamp);
   return formatter.format(calendar.getTime());
 }
    private Object getValueWithoutWebEditorsFormat(int row, int column) {
      Object r = original.getValueAt(row, column);

      if (r instanceof Boolean) {
        if (((Boolean) r).booleanValue()) return XavaResources.getString(locale, "yes");
        return XavaResources.getString(locale, "no");
      }
      if (withValidValues) {
        MetaProperty p = getMetaProperty(column);
        if (p.hasValidValues()) {
          return p.getValidValueLabel(locale, original.getValueAt(row, column));
        }
      }

      if (r instanceof java.util.Date) {
        MetaProperty p =
            getMetaProperty(column); // In order to use the type declared by the developer
        // and not the one returned by JDBC or the JPA engine
        if (java.sql.Time.class.isAssignableFrom(p.getType())) {
          return DateFormat.getTimeInstance(DateFormat.SHORT, locale).format(r);
        }
        if (java.sql.Timestamp.class.isAssignableFrom(p.getType())) {
          DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
          return dateFormat.format(r);
        }
        return DateFormat.getDateInstance(DateFormat.SHORT, locale).format(r);
      }

      if (r instanceof BigDecimal) {
        return formatBigDecimal(r, locale);
      }

      return r;
    }
Ejemplo n.º 3
0
 /**
  * Create a default filename given the current date selection. If custom dates are selected, use
  * those dates; otherwise, use year and week numbers.
  *
  * @return The default filename.
  */
 private String getDefaultFilename() {
   if (yearCB.getSelectedIndex() == 0 || weekCB.getSelectedIndex() == 0)
     return "timesheet-"
         + dateFormat.format(fromDate.getDate()).replaceAll("/", "")
         + "-"
         + dateFormat.format(toDate.getDate()).replaceAll("/", "")
         + ".txt";
   return "timesheet-" + yearCB.getSelectedItem() + "wk" + weekCB.getSelectedItem() + ".txt";
 }
Ejemplo n.º 4
0
 /**
  * @bug 4139940 Couldn't reproduce this bug -- probably was fixed earlier.
  *     <p>ORIGINAL BUG REPORT: -- basically, hungarian for monday shouldn't have an \u00f4 (o
  *     circumflex)in it instead it should be an o with 2 inclined (right) lines over it..
  *     <p>You may wonder -- why do all this -- why not just add a line to LocaleData? Well, I
  *     could see by inspection that the locale file had the right character in it, so I wanted to
  *     check the rest of the pipeline -- a very remote possibility, but I wanted to be sure. The
  *     other possibility is that something is wrong with the font mapping subsystem, but we can't
  *     test that here.
  */
 public void Test4139940() {
   Locale mylocale = new Locale("hu", "", "");
   Date mydate = new Date(98, 3, 13); // A Monday
   DateFormat df_full = new SimpleDateFormat("EEEE", mylocale);
   String str = df_full.format(mydate);
   // Make sure that o circumflex (\u00F4) is NOT there, and
   // o double acute (\u0151) IS.
   if (str.indexOf('\u0151') < 0 || str.indexOf('\u00F4') >= 0)
     errln("Fail: Monday in Hungarian is wrong");
 }
Ejemplo n.º 5
0
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      DateFormat df = DateFormat.getDateTimeInstance();
      String titleStr = "C3P0 Status - " + df.format(new Date());

      DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = fact.newDocumentBuilder();
      Document doc = db.newDocument();

      Element htmlElem = doc.createElement("html");
      Element headElem = doc.createElement("head");

      Element titleElem = doc.createElement("title");
      titleElem.appendChild(doc.createTextNode(titleStr));

      Element bodyElem = doc.createElement("body");

      Element h1Elem = doc.createElement("h1");
      h1Elem.appendChild(doc.createTextNode(titleStr));

      Element h3Elem = doc.createElement("h3");
      h3Elem.appendChild(doc.createTextNode("PooledDataSources"));

      Element pdsDlElem = doc.createElement("dl");
      pdsDlElem.setAttribute("class", "PooledDataSources");
      for (Iterator ii = C3P0Registry.getPooledDataSources().iterator(); ii.hasNext(); ) {
        PooledDataSource pds = (PooledDataSource) ii.next();
        StatusReporter sr = findStatusReporter(pds, doc);
        pdsDlElem.appendChild(sr.reportDtElem());
        pdsDlElem.appendChild(sr.reportDdElem());
      }

      headElem.appendChild(titleElem);
      htmlElem.appendChild(headElem);

      bodyElem.appendChild(h1Elem);
      bodyElem.appendChild(h3Elem);
      bodyElem.appendChild(pdsDlElem);
      htmlElem.appendChild(bodyElem);

      res.setContentType("application/xhtml+xml");

      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer();
      Source src = new DOMSource(doc);
      Result result = new StreamResult(res.getOutputStream());
      transformer.transform(src, result);
    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new ServletException(e);
    }
  }
Ejemplo n.º 6
0
 // 将从SQL数据库中选择出来的日期性字段格式化为本地日期描述
 public String FormatDate(String DateStr) {
   if (DateStr.equals(null) || DateStr.equals("")) {
     return "    -  -  ";
   } else {
     try {
       DateFormat df = DateFormat.getDateInstance();
       Date d = df.parse(DateStr);
       df = DateFormat.getDateInstance(DateFormat.FULL);
       return df.format(d);
     } catch (ParseException e) {
       System.err.println("bean_ElearnTools.FormatDate error: " + e.getMessage());
       return DateStr;
     }
   }
 }
  @Override
  public synchronized String format(LogRecord record) {
    StringBuilder sb = new StringBuilder();

    sb.append(dateFormat.format(new Date(record.getMillis())));
    sb.append(' ');
    sb.append(record.getLevel().getLocalizedName());
    sb.append(": ");
    sb.append(formatMessage(record));
    sb.append(LINE_SEPARATOR);

    if (record.getThrown() != null) {
      try {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        record.getThrown().printStackTrace(pw);
        pw.close();
        sb.append(sw.toString());
      } catch (Exception e) {
        // ignore
      }
    }

    return sb.toString();
  }
Ejemplo n.º 8
0
  /** Write [DATE] Buy [SYMBOL] [NUMBER]sh @[PRICE] = [VALUE] --> [NUMBER]sh held * */
  public void orderBought(
      TradeOrder order, Date date, StockPosition position, TradingAccount account) {
    double profitOrLoss =
        (order.shares * (order.getExecutedPrice() - position.getCostBasis())
            - account.getTradeFees(order.shares));

    double percent = profitOrLoss / (position.getCostBasis() * order.shares);

    this.writer.println(
        DATE_FORMAT.format(date)
            + " "
            + (position.getShares() != 0 ? "Buy " : "Cover ")
            + order.symbol
            + " "
            + order.shares
            + "sh "
            + "@"
            + DOLLAR_FORMAT.format(order.getExecutedPrice())
            + " = "
            + DOLLAR_FORMAT.format(order.getExecutedValue())
            + " --> "
            + position.getShares()
            + "sh "
            + (position.getShares() <= 0
                ? "left, "
                    + DOLLAR_FORMAT.format(profitOrLoss)
                    + (profitOrLoss > 0
                        ? " (" + PERCENT_FORMAT.format(percent) + " profit)"
                        : profitOrLoss < 0
                            ? " (" + PERCENT_FORMAT.format(percent) + "loss)"
                            : " (even)")
                : "long"));

    this.lastTraceDate = date;
  }
 private void startTag(String aPrefix, String aName, XmlPullParser aParser) throws Exception {
   if ("entry".equals(aName)) {
     tweets.addTweet(currentTweet = new Tweet());
   } else if ("published".equals(aName)) {
     aParser.next();
     currentTweet.setPublished(dateFormat.parse(aParser.getText()));
   } else if (("title".equals(aName)) && (currentTweet != null)) {
     aParser.next();
     currentTweet.setTitle(aParser.getText());
   } else if ("content".equals(aName)) {
     Content _c = new Content();
     _c.setType(aParser.getAttributeValue(null, "type"));
     aParser.next();
     _c.setValue(aParser.getText());
     currentTweet.setContent(_c);
   } else if ("lang".equals(aName)) {
     aParser.next();
     currentTweet.setLanguage(aParser.getText());
   } else if ("author".equals(aName)) {
     currentTweet.setAuthor(currentAuthor = new Author());
   } else if ("name".equals(aName)) {
     aParser.next();
     currentAuthor.setName(aParser.getText());
   } else if ("uri".equals(aName)) {
     aParser.next();
     currentAuthor.setUri(aParser.getText());
   }
 }
Ejemplo n.º 10
0
 /** Write initial cash balance. * */
 public void initialized(Date date, TradingAccount account) {
   writer.println(
       DATE_FORMAT.format(date)
           + ": "
           + "cash="
           + DOLLAR_FORMAT.format(account.getCurrentCashBalance()));
   this.lastTraceDate = date;
 }
  // =====================================================
  // setEXIFpictureMetadaten()
  //
  // Aus dem Image-Original werden die EXIF-Daten f�r die
  // PM_PictureMetadatenX geholt und eingetragen
  // =====================================================
  public static void setEXIFpictureMetadaten(PM_Picture picture) {

    PM_PictureImageMetadaten imageMetadaten = picture.getImageMetadaten();

    // ----------------------------------------------------
    // FujiFilm Makernote:  SequenceNummer --> virtPicture
    // ----------------------------------------------------

    // -------------------------------------------------------
    // Date
    // ------------------------------------------------------

    String tagDatum = "Date/Time Original";
    String description = "";
    if (imageMetadaten.hasTag(tagDatum)) {
      description = imageMetadaten.getDescription(tagDatum);
    }

    // ----------------------------------------------------
    // Datum nicht vorhanden oder ung�ltig
    // ----------------------------------------------------
    Date myDate = null;
    if (description.length() == 0 || description.equals("0000:00:00 00:00:00")) {
      //			  System.out.println("......  Datum = " + description + " kann nicht konvertiert
      // werden");
      File f = picture.getFileOriginal();
      Date date = new Date(f.lastModified());
      picture.meta.setDateImport(date);
      picture.meta.setDateCurrent(new Date(date.getTime()));
      return;
    }

    // ----------------------------------------------------
    // g�ltiges Datum gefunden
    // ----------------------------------------------------
    DateFormat df = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
    try {
      myDate = df.parse(description);
    } catch (ParseException e) {
      //           System.out.println("ParseException fuer Datum = " + description);
      myDate = new Date(System.currentTimeMillis()); // default
    }
    picture.meta.setDateImport(myDate);
    picture.meta.setDateCurrent(new Date(myDate.getTime()));
  }
Ejemplo n.º 12
0
 /**
  * Gets a temporary formatter for a zoneless date time. The same formatter is returned on
  * subsequent calls.
  *
  * @param format a {@link java.text.SimpleDateFormat} format string
  */
 protected DateFormat getFormatter(String format) {
   if ((tempFormatter != null) && lastFormat.equals(format)) {
     return tempFormatter;
   }
   tempFormatter = DateTimeUtil.newDateFormat(format);
   tempFormatter.setTimeZone(DateTimeUtil.gmtZone);
   lastFormat = format;
   return tempFormatter;
 }
Ejemplo n.º 13
0
  /**
   * Parses a string as a date
   *
   * @param str The string containing the date
   * @return The date value parsed from the string
   * @throws IOException If there's an error parsing the date
   */
  public Object parseDate(String str, DateFormat dateFormat) throws IOException {
    // If there isn't any, don't parse
    if (str == null) return null;

    try {
      return dateFormat.parse(str);
    } catch (ParseException exc) {
      throw new IOException("Error parsing date " + str);
    }
  }
Ejemplo n.º 14
0
  public static void main(String args[]) {
    Date now = new Date();
    DateFormat df = DateFormat.getDateInstance();
    String component = "Component : " + args[0];
    String date = "Date : " + df.format(now);
    ;
    String version = "Version : " + args[1];

    try {
      FileWriter fstream = new FileWriter("packInfo.txt");
      BufferedWriter out = new BufferedWriter(fstream);
      out.write(component);
      out.newLine();
      out.write(date);
      out.newLine();
      out.write(version);
      out.close();
    } catch (Exception e) {
      System.err.println("Error in opening a file");
    }
  }
Ejemplo n.º 15
0
  /*==========================================================
   * public methods
   *==========================================================*/
  public Vector parse(Object entry) throws ParseException {
    String logEntry = (String) entry;
    // parsing the log Entry and return segments
    // Debug.println("LogDataModel: DefaultLogParser: parse() -" +logEntry);
    int x = logEntry.indexOf("[");
    if (x == -1) throw new ParseException(logEntry, 0);
    String temp = logEntry.substring(x + 1);
    x = temp.indexOf("]");
    if (x == -1) throw new ParseException(logEntry, 0);

    String dateStr = temp.substring(0, x);
    // Debug.println("LogDataModel: DefaultLogParser: parse() -"+dateStr+" "+temp);
    SimpleDateFormat format = new SimpleDateFormat(DATE_PATTERN);
    Date date = format.parse(dateStr);
    String dateColumn = DateFormat.getDateInstance().format(date);
    String timeColumn = DateFormat.getTimeInstance().format(date);

    // Debug.println("LogDataModel: DefaultLogParser: parse() -"+dateColumn+" "+timeColumn);
    temp = temp.substring(x + 2);
    x = temp.indexOf("]");
    if (x == -1) throw new ParseException(logEntry, 0);
    String source = temp.substring(1, x);
    temp = temp.substring(x + 2);
    x = temp.indexOf("]");
    if (x == -1) throw new ParseException(logEntry, 0);
    String level = temp.substring(1, x);
    temp = temp.substring(x + 2);
    Vector row = new Vector();
    row.addElement(getSourceString(source));
    row.addElement(getLevelString(level));
    row.addElement(dateColumn);
    row.addElement(timeColumn);
    JLabel detail = new JLabel(temp);
    detail.setToolTipText(temp);
    row.addElement(detail);
    return row;
  }
 /** Constructor */
 public SOAPMonitorData(Long id, String target, String soap_request) {
   this.id = id;
   // A null id is used to signal that the "most recent" entry
   // is being created.
   if (id == null) {
     this.time = "Most Recent";
     this.target = "---";
     this.soap_request = null;
     this.soap_response = null;
   } else {
     this.time = DateFormat.getTimeInstance().format(new Date());
     this.target = target;
     this.soap_request = soap_request;
     this.soap_response = null;
   }
 }
Ejemplo n.º 17
0
 /**
  * If writing every day, or shares traded on date,<br>
  * Write [DATE]: cash=[CASHVALUE], stocks=[STOCKVALUE], total=[TOTALVALUE]*
  */
 public void ordersCompleted(Date date, TradingAccount account) {
   // report new balances only if they changed (buy or sell occurred on date)
   if (!this.daysTradedOnly || this.lastTraceDate.equals(date)) {
     double cashBalance = account.getCurrentCashBalance();
     double stockValue = account.getCurrentStockValue();
     double total = cashBalance + stockValue;
     this.writer.println(
         DATE_FORMAT.format(date)
             + ": "
             + "cash="
             + DOLLAR_FORMAT.format(cashBalance)
             + ", "
             + "stocks="
             + DOLLAR_FORMAT.format(stockValue)
             + ", "
             + "total="
             + DOLLAR_FORMAT.format(total));
   }
 }
Ejemplo n.º 18
0
 public void sendResponseHeaders(int rCode, long contentLen) throws IOException {
   if (sentHeaders) {
     throw new IOException("headers already sent");
   }
   this.rcode = rCode;
   String statusLine = "HTTP/1.1 " + rCode + Code.msg(rCode) + "\r\n";
   OutputStream tmpout = new BufferedOutputStream(ros);
   PlaceholderOutputStream o = getPlaceholderResponseBody();
   tmpout.write(bytes(statusLine, 0), 0, statusLine.length());
   boolean noContentToSend = false; // assume there is content
   rspHdrs.set("Date", df.format(new Date()));
   if (contentLen == 0) {
     if (http10) {
       o.setWrappedStream(new UndefLengthOutputStream(this, ros));
       close = true;
     } else {
       rspHdrs.set("Transfer-encoding", "chunked");
       o.setWrappedStream(new ChunkedOutputStream(this, ros));
     }
   } else {
     if (contentLen == -1) {
       noContentToSend = true;
       contentLen = 0;
     }
     /* content len might already be set, eg to implement HEAD resp */
     if (rspHdrs.getFirst("Content-length") == null) {
       rspHdrs.set("Content-length", Long.toString(contentLen));
     }
     o.setWrappedStream(new FixedLengthOutputStream(this, ros, contentLen));
   }
   write(rspHdrs, tmpout);
   this.rspContentLen = contentLen;
   tmpout.flush();
   tmpout = null;
   sentHeaders = true;
   if (noContentToSend) {
     WriteFinishedEvent e = new WriteFinishedEvent(this);
     server.addEvent(e);
     closed = true;
   }
   server.logReply(rCode, req.requestLine(), null);
 }
Ejemplo n.º 19
0
  /** Typical main method ("main program") declaration */
  public static void main(String[] av) {

    Locale l1 = new Locale("en", "US"), l2 = new Locale("es", "ES");

    // Create a Date object for May 5, 1986
    Calendar c = Calendar.getInstance();
    c.set(1986, 04, 05); // May 5, 1986
    Date d1 = c.getTime();

    // Create a Date object for today.
    Date d2 = new Date(); // today

    DateFormat df_us = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, l1),
        df_sp = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, l2);
    System.out.println("Date d1 for US is " + df_us.format(d1));
    System.out.println("Date d1 for Spain is " + df_sp.format(d1));
    System.out.println("Date d2 is " + df_us.format(d2));
  }
Ejemplo n.º 20
0
  /**
   * Creates an NotifyRequest for the specified file. If the specified file is null, a
   * IllegalArgumentException is thrown.
   */
  public NotifyRequest(File file, String command, String parameters) {
    if (file == null) {
      throw new IllegalArgumentException("File must not be null!");
    }

    StringBuffer buffer = new StringBuffer();
    buffer.append("Notify "); // NOI18N
    buffer.append(file.getName());
    buffer.append('\n');
    buffer.append(command);
    buffer.append('\t');
    buffer.append(DATE_FORMAT.format(new Date()));
    buffer.append('\t');
    buffer.append(HOST_NAME);
    buffer.append('\t');
    buffer.append(file.getParent());
    buffer.append('\t');
    buffer.append(parameters);
    buffer.append('\n');
    this.request = buffer.toString();
  }
  /**
   * Tries very, very hard to parse the a date. We assume that the text is neither empty nor <code>
   * null</code>.
   */
  private Date parseDate(String text) {
    DateFormat formats[] =
        new DateFormat[] {
          DateFormat.getDateInstance(DateFormat.SHORT),
          DateFormat.getDateInstance(DateFormat.MEDIUM),
          DateFormat.getDateInstance(DateFormat.LONG),
          DateFormat.getDateInstance(DateFormat.FULL),
        };

    for (int i = 0; i < formats.length; i++) {
      DateFormat df = formats[i];
      try {
        Date date = df.parse(text);
        return date;

      } catch (ParseException ex) {
        continue;
      }
    }

    error("Could not parse date: " + text);
    return null;
  }
Ejemplo n.º 22
0
  private void processRequest(PDU pdu) throws DBException, IOException {
    // Process the request and add to SMS_RECEIVE_QUEUE
    if (pdu.getCommandId() == Data.DELIVER_SM) {

      dsm = (DeliverSM) pdu;
      this.userId = dsm.getSourceAddr().getAddress();
      this.serviceId = dsm.getDestAddr().getAddress();
      this.info = dsm.getShortMessage();

      ByteBuffer da = null;

      try {
        da = dsm.getDestSubaddress();

        String te = Convert.hexToString(da.getHexDump().substring(2));

        //				this.RequestID = te;
        Gateway.util.log(this.getClass().getName(), "getDestSubaddress:" + te);
      } catch (ValueNotSetException ex) {

      }
      short destport = 0;
      try {
        destport = dsm.getDestinationPort();

        Gateway.util.log(this.getClass().getName(), "getDestinationPort:" + destport);
      } catch (ValueNotSetException e) {
        // TODO Auto-generated catch block
        // Tim Dport o day
        // ByteBuffer otaData =new
        // ByteBuffer(info.getBytes(Data.ENC_ISO8859_1));
        ByteBuffer otaData = new ByteBuffer();
        otaData = dsm.getShortMessagebuff();
        try {

          byte udhlength = otaData.removeByte();
          byte udhele1 = otaData.removeByte();
          byte udhele2 = otaData.removeByte();

          short sdport = otaData.removeShort();

          short ssport = otaData.removeShort();

          String newmsg = otaData.removeString(otaData.length(), Data.ENC_ISO8859_1);

          if (udhlength == 6 && udhele1 == 5) {
            destport = sdport;
            this.info = newmsg;
            Gateway.util.log(
                this.getClass().getName(), "getDestinationPort:" + destport + "@info=" + newmsg);
          }

        } catch (NotEnoughDataInByteBufferException e1) {
          // TODO Auto-generated catch block

        }
      }

      this.Dport = Short.toString(destport);

      if (this.info == null) {
        this.info = "null";
      }
      this.userId = removePlusSign(this.userId);
      this.serviceId = rebuildServiceId(this.serviceId);
      this.operator = Preference.mobileOperator;
      // Added on 22//2003 : VinaPhone gui ban tin DeliverReport voi
      // truong esm_class != 0x4. ==> He thong xem nhu ban tin thuong
      // sai format va gui thong bao -- report -- thong bao --> LOOP./
      // To pass over this, set:

      if (dsm.getEsmClass() == 0x4 || info.startsWith("id:")) { // DeliverReport
        // (not
        // processed)!
        Gateway.util.log(this.getClass().getName(), "It can be DeliverReport (not processed)!");
        return; // not processed
      }

      // Normal message (request):
      // Neu mobile o che do tieng viet
      // --> Loai bo space (ky tu 00) giua cac ky tu
      this.info = StringTool.removeChar(this.info, '\00');

      String newserviceid = this.serviceId;

      newserviceid = newserviceid.substring(newserviceid.length() - 4);

      // DANND add
      DateFormat dateFormat = new SimpleDateFormat("MMddHHmmssSSS");
      java.util.Date date = new java.util.Date();
      String datetime = dateFormat.format(date);
      this.RequestID = Preference.prefix_requestid + datetime + threadId;

      dbTools.add2SMSReceiveQueueR(
          this.userId,
          this.serviceId,
          this.operator,
          this.commandCode,
          this.info,
          this.RequestID,
          this.Dport);
    }
  }
Ejemplo n.º 23
0
public class Dashutil {

  // FEATURES
  private static final boolean NATIVE_COMMANDS = false;
  /**
   * If true, all operations (besides upload and native commands) which change something on the file
   * system are permitted
   */
  private static boolean READ_ONLY = false;
  // If true, uploads are allowed even if READ_ONLY = true
  private static final boolean ALLOW_UPLOAD = true;

  // Allow browsing and file manipulation only in certain directories
  private static final boolean RESTRICT_BROWSING = true;
  // If true, the user is allowed to browse only in RESTRICT_PATH,
  // if false, the user is allowed to browse all directories besides RESTRICT_PATH
  private static final boolean RESTRICT_WHITELIST = true;

  // Paths, sperated by semicolon
  // private static final String RESTRICT_PATH = "C:\\;E:\\"; //Win32: Case important!!
  // private static final String RESTRICT_PATH = "C:\\nice\\uploads";
  private static final String RESTRICT_PATH = "C:\\nice\\users";

  // private static final String RESTRICT_PATH = "/etc;/var";

  // The refresh time in seconds of the upload monitor window
  private static final int UPLOAD_MONITOR_REFRESH = 2;
  // The number of colums for the edit field
  private static final int EDITFIELD_COLS = 85;
  // The number of rows for the edit field
  private static final int EDITFIELD_ROWS = 30;
  // Open a new window to view a file
  private static final boolean USE_POPUP = true;
  /**
   * If USE_DIR_PREVIEW = true, then for every directory a tooltip will be created (hold the mouse
   * over the link) with the first DIR_PREVIEW_NUMBER entries. This can yield to performance issues.
   * Turn it off, if the directory loads to slow.
   */
  private static final boolean USE_DIR_PREVIEW = false;

  private static final int DIR_PREVIEW_NUMBER = 10;
  /** The name of an optional CSS Stylesheet file */
  private static final String CSS_NAME = "Browser.css";
  /**
   * The compression level for zip file creation (0-9) 0 = No compression 1 = Standard compression
   * (Very fast) ... 9 = Best compression (Very slow)
   */
  private static final int COMPRESSION_LEVEL = 1;
  /**
   * The FORBIDDEN_DRIVES are not displayed on the list. This can be usefull, if the server runs on
   * a windows platform, to avoid a message box, if you try to access an empty removable drive (See
   * KNOWN BUGS in Readme.txt).
   */
  private static final String[] FORBIDDEN_DRIVES = {"a:\\"};

  /** Command of the shell interpreter and the parameter to run a programm */
  private static final String[] COMMAND_INTERPRETER = {"cmd", "/C"}; // Dos,Windows
  // private static final String[] COMMAND_INTERPRETER = {"/bin/sh","-c"}; 	// Unix

  /** Max time in ms a process is allowed to run, before it will be terminated */
  private static final long MAX_PROCESS_RUNNING_TIME = 30 * 1000; // 30 seconds

  // Button names
  private static final String SAVE_AS_ZIP = "Download selected files as (z)ip";
  private static final String RENAME_FILE = "(R)ename File";
  private static final String DELETE_FILES = "(Del)ete selected files";
  private static final String CREATE_DIR = "Create (D)ir";
  private static final String CREATE_FILE = "(C)reate File";
  private static final String MOVE_FILES = "(M)ove Files";
  private static final String COPY_FILES = "Cop(y) Files";
  private static final String LAUNCH_COMMAND = "(L)aunch external program";
  private static final String UPLOAD_FILES = "Upload";

  // Normally you should not change anything after this line
  // ----------------------------------------------------------------------------------
  // Change this to locate the tempfile directory for upload (not longer needed)
  private static String tempdir = ".";
  private static String VERSION_NR = "1.2";
  private static DateFormat dateFormat = DateFormat.getDateTimeInstance();

  public class UplInfo {

    public long totalSize;
    public long currSize;
    public long starttime;
    public boolean aborted;

    public UplInfo() {
      totalSize = 0l;
      currSize = 0l;
      starttime = System.currentTimeMillis();
      aborted = false;
    }

    public UplInfo(int size) {
      totalSize = size;
      currSize = 0;
      starttime = System.currentTimeMillis();
      aborted = false;
    }

    public String getUprate() {
      long time = System.currentTimeMillis() - starttime;
      if (time != 0) {
        long uprate = currSize * 1000 / time;
        return convertFileSize(uprate) + "/s";
      } else return "n/a";
    }

    public int getPercent() {
      if (totalSize == 0) return 0;
      else return (int) (currSize * 100 / totalSize);
    }

    public String getTimeElapsed() {
      long time = (System.currentTimeMillis() - starttime) / 1000l;
      if (time - 60l >= 0) {
        if (time % 60 >= 10) return time / 60 + ":" + (time % 60) + "m";
        else return time / 60 + ":0" + (time % 60) + "m";
      } else return time < 10 ? "0" + time + "s" : time + "s";
    }

    public String getTimeEstimated() {
      if (currSize == 0) return "n/a";
      long time = System.currentTimeMillis() - starttime;
      time = totalSize * time / currSize;
      time /= 1000l;
      if (time - 60l >= 0) {
        if (time % 60 >= 10) return time / 60 + ":" + (time % 60) + "m";
        else return time / 60 + ":0" + (time % 60) + "m";
      } else return time < 10 ? "0" + time + "s" : time + "s";
    }
  }

  public class FileInfo {

    public String name = null, clientFileName = null, fileContentType = null;
    private byte[] fileContents = null;
    public File file = null;
    public StringBuffer sb = new StringBuffer(100);

    public void setFileContents(byte[] aByteArray) {
      fileContents = new byte[aByteArray.length];
      System.arraycopy(aByteArray, 0, fileContents, 0, aByteArray.length);
    }
  }

  public static class UploadMonitor {

    static Hashtable uploadTable = new Hashtable();

    static void set(String fName, UplInfo info) {
      uploadTable.put(fName, info);
    }

    static void remove(String fName) {
      uploadTable.remove(fName);
    }

    static UplInfo getInfo(String fName) {
      UplInfo info = (UplInfo) uploadTable.get(fName);
      return info;
    }
  }

  // A Class with methods used to process a ServletInputStream
  public class HttpMultiPartParser {

    // private final String lineSeparator = System.getProperty("line.separator", "\n");
    private final int ONE_MB = 1024 * 1;

    public Hashtable processData(
        ServletInputStream is, String boundary, String saveInDir, int clength)
        throws IllegalArgumentException, IOException {
      if (is == null) throw new IllegalArgumentException("InputStream");
      if (boundary == null || boundary.trim().length() < 1)
        throw new IllegalArgumentException("\"" + boundary + "\" is an illegal boundary indicator");
      boundary = "--" + boundary;
      StringTokenizer stLine = null, stFields = null;
      FileInfo fileInfo = null;
      Hashtable dataTable = new Hashtable(5);
      String line = null, field = null, paramName = null;
      boolean saveFiles = (saveInDir != null && saveInDir.trim().length() > 0);
      boolean isFile = false;
      if (saveFiles) { // Create the required directory (including parent dirs)
        File f = new File(saveInDir);
        f.mkdirs();
      }
      line = getLine(is);
      if (line == null || !line.startsWith(boundary))
        throw new IOException("Boundary not found; boundary = " + boundary + ", line = " + line);
      while (line != null) {
        if (line == null || !line.startsWith(boundary)) return dataTable;
        line = getLine(is);
        if (line == null) return dataTable;
        stLine = new StringTokenizer(line, ";\r\n");
        if (stLine.countTokens() < 2) throw new IllegalArgumentException("Bad data in second line");
        line = stLine.nextToken().toLowerCase();
        if (line.indexOf("form-data") < 0)
          throw new IllegalArgumentException("Bad data in second line");
        stFields = new StringTokenizer(stLine.nextToken(), "=\"");
        if (stFields.countTokens() < 2)
          throw new IllegalArgumentException("Bad data in second line");
        fileInfo = new FileInfo();
        stFields.nextToken();
        paramName = stFields.nextToken();
        isFile = false;
        if (stLine.hasMoreTokens()) {
          field = stLine.nextToken();
          stFields = new StringTokenizer(field, "=\"");
          if (stFields.countTokens() > 1) {
            if (stFields.nextToken().trim().equalsIgnoreCase("filename")) {
              fileInfo.name = paramName;
              String value = stFields.nextToken();
              if (value != null && value.trim().length() > 0) {
                fileInfo.clientFileName = value;
                isFile = true;
              } else {
                line = getLine(is); // Skip "Content-Type:" line
                line = getLine(is); // Skip blank line
                line = getLine(is); // Skip blank line
                line = getLine(is); // Position to boundary line
                continue;
              }
            }
          } else if (field.toLowerCase().indexOf("filename") >= 0) {
            line = getLine(is); // Skip "Content-Type:" line
            line = getLine(is); // Skip blank line
            line = getLine(is); // Skip blank line
            line = getLine(is); // Position to boundary line
            continue;
          }
        }
        boolean skipBlankLine = true;
        if (isFile) {
          line = getLine(is);
          if (line == null) return dataTable;
          if (line.trim().length() < 1) skipBlankLine = false;
          else {
            stLine = new StringTokenizer(line, ": ");
            if (stLine.countTokens() < 2)
              throw new IllegalArgumentException("Bad data in third line");
            stLine.nextToken(); // Content-Type
            fileInfo.fileContentType = stLine.nextToken();
          }
        }
        if (skipBlankLine) {
          line = getLine(is);
          if (line == null) return dataTable;
        }
        if (!isFile) {
          line = getLine(is);
          if (line == null) return dataTable;
          dataTable.put(paramName, line);
          // If parameter is dir, change saveInDir to dir
          if (paramName.equals("dir")) saveInDir = line;
          line = getLine(is);
          continue;
        }
        try {
          UplInfo uplInfo = new UplInfo(clength);
          UploadMonitor.set(fileInfo.clientFileName, uplInfo);
          OutputStream os = null;
          String path = null;
          if (saveFiles)
            os = new FileOutputStream(path = getFileName(saveInDir, fileInfo.clientFileName));
          else os = new ByteArrayOutputStream(ONE_MB);
          boolean readingContent = true;
          byte previousLine[] = new byte[2 * ONE_MB];
          byte temp[] = null;
          byte currentLine[] = new byte[2 * ONE_MB];
          int read, read3;
          if ((read = is.readLine(previousLine, 0, previousLine.length)) == -1) {
            line = null;
            break;
          }
          while (readingContent) {
            if ((read3 = is.readLine(currentLine, 0, currentLine.length)) == -1) {
              line = null;
              uplInfo.aborted = true;
              break;
            }
            if (compareBoundary(boundary, currentLine)) {
              os.write(previousLine, 0, read - 2);
              line = new String(currentLine, 0, read3);
              break;
            } else {
              os.write(previousLine, 0, read);
              uplInfo.currSize += read;
              temp = currentLine;
              currentLine = previousLine;
              previousLine = temp;
              read = read3;
            } // end else
          } // end while
          os.flush();
          os.close();
          if (!saveFiles) {
            ByteArrayOutputStream baos = (ByteArrayOutputStream) os;
            fileInfo.setFileContents(baos.toByteArray());
          } else fileInfo.file = new File(path);
          dataTable.put(paramName, fileInfo);
          uplInfo.currSize = uplInfo.totalSize;
        } // end try
        catch (IOException e) {
          throw e;
        }
      }
      return dataTable;
    }

    /** Compares boundary string to byte array */
    private boolean compareBoundary(String boundary, byte ba[]) {
      if (boundary == null || ba == null) return false;
      for (int i = 0; i < boundary.length(); i++)
        if ((byte) boundary.charAt(i) != ba[i]) return false;
      return true;
    }

    /** Convenience method to read HTTP header lines */
    private synchronized String getLine(ServletInputStream sis) throws IOException {
      byte b[] = new byte[1024];
      int read = sis.readLine(b, 0, b.length), index;
      String line = null;
      if (read != -1) {
        line = new String(b, 0, read);
        if ((index = line.indexOf('\n')) >= 0) line = line.substring(0, index - 1);
      }
      return line;
    }

    public String getFileName(String dir, String fileName) throws IllegalArgumentException {
      String path = null;
      if (dir == null || fileName == null)
        throw new IllegalArgumentException("dir or fileName is null");
      int index = fileName.lastIndexOf('/');
      String name = null;
      if (index >= 0) name = fileName.substring(index + 1);
      else name = fileName;
      index = name.lastIndexOf('\\');
      if (index >= 0) fileName = name.substring(index + 1);
      path = dir + File.separator + fileName;
      if (File.separatorChar == '/') return path.replace('\\', File.separatorChar);
      else return path.replace('/', File.separatorChar);
    }
  } // End of class HttpMultiPartParser

  /** This class is a comparator to sort the filenames and dirs */
  class FileComp implements Comparator {

    int mode;
    int sign;

    FileComp() {
      this.mode = 1;
      this.sign = 1;
    }

    /**
     * @param mode sort by 1=Filename, 2=Size, 3=Date, 4=Type The default sorting method is by Name
     *     Negative mode means descending sort
     */
    FileComp(int mode) {
      if (mode < 0) {
        this.mode = -mode;
        sign = -1;
      } else {
        this.mode = mode;
        this.sign = 1;
      }
    }

    public int compare(Object o1, Object o2) {
      File f1 = (File) o1;
      File f2 = (File) o2;
      if (f1.isDirectory()) {
        if (f2.isDirectory()) {
          switch (mode) {
              // Filename or Type
            case 1:
            case 4:
              return sign
                  * f1.getAbsolutePath()
                      .toUpperCase()
                      .compareTo(f2.getAbsolutePath().toUpperCase());
              // Filesize
            case 2:
              return sign * (new Long(f1.length()).compareTo(new Long(f2.length())));
              // Date
            case 3:
              return sign * (new Long(f1.lastModified()).compareTo(new Long(f2.lastModified())));
            default:
              return 1;
          }
        } else return -1;
      } else if (f2.isDirectory()) return 1;
      else {
        switch (mode) {
          case 1:
            return sign
                * f1.getAbsolutePath().toUpperCase().compareTo(f2.getAbsolutePath().toUpperCase());
          case 2:
            return sign * (new Long(f1.length()).compareTo(new Long(f2.length())));
          case 3:
            return sign * (new Long(f1.lastModified()).compareTo(new Long(f2.lastModified())));
          case 4:
            { // Sort by extension
              int tempIndexf1 = f1.getAbsolutePath().lastIndexOf('.');
              int tempIndexf2 = f2.getAbsolutePath().lastIndexOf('.');
              if ((tempIndexf1 == -1) && (tempIndexf2 == -1)) { // Neither have an extension
                return sign
                    * f1.getAbsolutePath()
                        .toUpperCase()
                        .compareTo(f2.getAbsolutePath().toUpperCase());
              }
              // f1 has no extension
              else if (tempIndexf1 == -1) return -sign;
              // f2 has no extension
              else if (tempIndexf2 == -1) return sign;
              // Both have an extension
              else {
                String tempEndf1 = f1.getAbsolutePath().toUpperCase().substring(tempIndexf1);
                String tempEndf2 = f2.getAbsolutePath().toUpperCase().substring(tempIndexf2);
                return sign * tempEndf1.compareTo(tempEndf2);
              }
            }
          default:
            return 1;
        }
      }
    }
  }

  /** Wrapperclass to wrap an OutputStream around a Writer */
  class Writer2Stream extends OutputStream {

    Writer out;

    Writer2Stream(Writer w) {
      super();
      out = w;
    }

    public void write(int i) throws IOException {
      out.write(i);
    }

    public void write(byte[] b) throws IOException {
      for (int i = 0; i < b.length; i++) {
        int n = b[i];
        // Convert byte to ubyte
        n = ((n >>> 4) & 0xF) * 16 + (n & 0xF);
        out.write(n);
      }
    }

    public void write(byte[] b, int off, int len) throws IOException {
      for (int i = off; i < off + len; i++) {
        int n = b[i];
        n = ((n >>> 4) & 0xF) * 16 + (n & 0xF);
        out.write(n);
      }
    }
  } // End of class Writer2Stream

  public static Vector expandFileList(String[] files, boolean inclDirs) {
    Vector v = new Vector();
    if (files == null) return v;
    for (int i = 0; i < files.length; i++) v.add(new File(URLDecoder.decode(files[i])));
    for (int i = 0; i < v.size(); i++) {
      File f = (File) v.get(i);
      if (f.isDirectory()) {
        File[] fs = f.listFiles();
        for (int n = 0; n < fs.length; n++) v.add(fs[n]);
        if (!inclDirs) {
          v.remove(i);
          i--;
        }
      }
    }
    return v;
  }

  /**
   * Method to build an absolute path
   *
   * @param dir the root dir
   * @param name the name of the new directory
   * @return if name is an absolute directory, returns name, else returns dir+name
   */
  public static String getDir(String dir, String name) {
    if (!dir.endsWith(File.separator)) dir = dir + File.separator;
    File mv = new File(name);
    String new_dir = null;
    if (!mv.isAbsolute()) {
      new_dir = dir + name;
    } else new_dir = name;
    return new_dir;
  }

  /**
   * This Method converts a byte size in a kbytes or Mbytes size, depending on the size
   *
   * @param size The size in bytes
   * @return String with size and unit
   */
  public static String convertFileSize(long size) {
    int divisor = 1;
    String unit = "bytes";
    if (size >= 1024 * 1024) {
      divisor = 1024 * 1024;
      unit = "MB";
    } else if (size >= 1024) {
      divisor = 1024;
      unit = "KB";
    }
    if (divisor == 1) return size / divisor + " " + unit;
    String aftercomma = "" + 100 * (size % divisor) / divisor;
    if (aftercomma.length() == 1) aftercomma = "0" + aftercomma;
    return size / divisor + "." + aftercomma + " " + unit;
  }

  /**
   * Copies all data from in to out
   *
   * @param in the input stream
   * @param out the output stream
   * @param buffer copy buffer
   */
  public static void copyStreams(InputStream in, OutputStream out, byte[] buffer)
      throws IOException {
    copyStreamsWithoutClose(in, out, buffer);
    in.close();
    out.close();
  }

  /**
   * Copies all data from in to out
   *
   * @param in the input stream
   * @param out the output stream
   * @param buffer copy buffer
   */
  public static void copyStreamsWithoutClose(InputStream in, OutputStream out, byte[] buffer)
      throws IOException {
    int b;
    while ((b = in.read(buffer)) != -1) out.write(buffer, 0, b);
  }

  /** Returns the Mime Type of the file, depending on the extension of the filename */
  public static String getMimeType(String fName) {
    fName = fName.toLowerCase();
    if (fName.endsWith(".jpg") || fName.endsWith(".jpeg") || fName.endsWith(".jpe"))
      return "image/jpeg";
    else if (fName.endsWith(".gif")) return "image/gif";
    else if (fName.endsWith(".pdf")) return "application/pdf";
    else if (fName.endsWith(".htm") || fName.endsWith(".html") || fName.endsWith(".shtml"))
      return "text/html";
    else if (fName.endsWith(".avi")) return "video/x-msvideo";
    else if (fName.endsWith(".mov") || fName.endsWith(".qt")) return "video/quicktime";
    else if (fName.endsWith(".mpg") || fName.endsWith(".mpeg") || fName.endsWith(".mpe"))
      return "video/mpeg";
    else if (fName.endsWith(".zip")) return "application/zip";
    else if (fName.endsWith(".tiff") || fName.endsWith(".tif")) return "image/tiff";
    else if (fName.endsWith(".rtf")) return "application/rtf";
    else if (fName.endsWith(".mid") || fName.endsWith(".midi")) return "audio/x-midi";
    else if (fName.endsWith(".xl")
        || fName.endsWith(".xls")
        || fName.endsWith(".xlv")
        || fName.endsWith(".xla")
        || fName.endsWith(".xlb")
        || fName.endsWith(".xlt")
        || fName.endsWith(".xlm")
        || fName.endsWith(".xlk")) return "application/excel";
    else if (fName.endsWith(".doc") || fName.endsWith(".dot")) return "application/msword";
    else if (fName.endsWith(".png")) return "image/png";
    else if (fName.endsWith(".xml")) return "text/xml";
    else if (fName.endsWith(".svg")) return "image/svg+xml";
    else if (fName.endsWith(".mp3")) return "audio/mp3";
    else if (fName.endsWith(".ogg")) return "audio/ogg";
    else return "text/plain";
  }

  /** Converts some important chars (int) to the corresponding html string */
  public static String conv2Html(int i) {
    if (i == '&') return "&amp;";
    else if (i == '<') return "&lt;";
    else if (i == '>') return "&gt;";
    else if (i == '"') return "&quot;";
    else return "" + (char) i;
  }

  /** Converts a normal string to a html conform string */
  public static String conv2Html(String st) {
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < st.length(); i++) {
      buf.append(conv2Html(st.charAt(i)));
    }
    return buf.toString();
  }

  /**
   * Starts a native process on the server
   *
   * @param command the command to start the process
   * @param dir the dir in which the process starts
   */
  static String startProcess(String command, String dir) throws IOException {
    StringBuffer ret = new StringBuffer();
    String[] comm = new String[3];
    comm[0] = COMMAND_INTERPRETER[0];
    comm[1] = COMMAND_INTERPRETER[1];
    comm[2] = command;
    long start = System.currentTimeMillis();
    try {
      // Start process
      Process ls_proc = Runtime.getRuntime().exec(comm, null, new File(dir));
      // Get input and error streams
      BufferedInputStream ls_in = new BufferedInputStream(ls_proc.getInputStream());
      BufferedInputStream ls_err = new BufferedInputStream(ls_proc.getErrorStream());
      boolean end = false;
      while (!end) {
        int c = 0;
        while ((ls_err.available() > 0) && (++c <= 1000)) {
          ret.append(conv2Html(ls_err.read()));
        }
        c = 0;
        while ((ls_in.available() > 0) && (++c <= 1000)) {
          ret.append(conv2Html(ls_in.read()));
        }
        try {
          ls_proc.exitValue();
          // if the process has not finished, an exception is thrown
          // else
          while (ls_err.available() > 0) ret.append(conv2Html(ls_err.read()));
          while (ls_in.available() > 0) ret.append(conv2Html(ls_in.read()));
          end = true;
        } catch (IllegalThreadStateException ex) {
          // Process is running
        }
        // The process is not allowed to run longer than given time.
        if (System.currentTimeMillis() - start > MAX_PROCESS_RUNNING_TIME) {
          ls_proc.destroy();
          end = true;
          ret.append("!!!! Process has timed out, destroyed !!!!!");
        }
        try {
          Thread.sleep(50);
        } catch (InterruptedException ie) {
        }
      }
    } catch (IOException e) {
      ret.append("Error: " + e);
    }
    return ret.toString();
  }

  /**
   * Converts a dir string to a linked dir string
   *
   * @param dir the directory string (e.g. /usr/local/httpd)
   * @param browserLink web-path to Browser.jsp
   */
  public static String dir2linkdir(String dir, String browserLink, int sortMode) {
    File f = new File(dir);
    StringBuffer buf = new StringBuffer();
    while (f.getParentFile() != null) {
      if (f.canRead()) {
        String encPath = URLEncoder.encode(f.getAbsolutePath());
        buf.insert(
            0,
            "<a href=\""
                + browserLink
                + "?sort="
                + sortMode
                + "&amp;dir="
                + encPath
                + "\">"
                + conv2Html(f.getName())
                + File.separator
                + "</a>");
      } else buf.insert(0, conv2Html(f.getName()) + File.separator);
      f = f.getParentFile();
    }
    if (f.canRead()) {
      String encPath = URLEncoder.encode(f.getAbsolutePath());
      buf.insert(
          0,
          "<a href=\""
              + browserLink
              + "?sort="
              + sortMode
              + "&amp;dir="
              + encPath
              + "\">"
              + conv2Html(f.getAbsolutePath())
              + "</a>");
    } else buf.insert(0, f.getAbsolutePath());
    return buf.toString();
  }

  /** Returns true if the given filename tends towards a packed file */
  public static boolean isPacked(String name, boolean gz) {
    return (name.toLowerCase().endsWith(".zip")
        || name.toLowerCase().endsWith(".jar")
        || (gz && name.toLowerCase().endsWith(".gz"))
        || name.toLowerCase().endsWith(".war"));
  }

  /** If RESTRICT_BROWSING = true this method checks, whether the path is allowed or not */
  public static boolean isAllowed(File path, boolean write) throws IOException {
    if (READ_ONLY && write) return false;
    if (RESTRICT_BROWSING) {
      StringTokenizer stk = new StringTokenizer(RESTRICT_PATH, ";");
      while (stk.hasMoreTokens()) {
        if (path != null && path.getCanonicalPath().startsWith(stk.nextToken()))
          return RESTRICT_WHITELIST;
      }
      return !RESTRICT_WHITELIST;
    } else return true;
  }

  // ---------------------------------------------------------------------------------------------------------------

}
Ejemplo n.º 24
0
  public int doEndTag() throws JspException {
    String pattern = this.pattern;
    ResourceBundle bundle = null;

    // get pattern from bundle
    if (pattern == null) {
      String prefix = null;

      bundle = this.bundle;
      if (bundle == null) {
        BundleTag bundleTag = (BundleTag) findAncestorWithClass(this, BundleTag.class);
        if (bundleTag != null) {
          bundle = bundleTag.getBundle();
          prefix = bundleTag.getPrefix();
        }
      }
      if (bundle == null) {
        bundle = I18nUtil.findBundle(pageContext);
      }

      // get message
      try {
        pattern = bundle.getString(prefix != null ? prefix + this.key : this.key);
      } catch (Exception e) {
        pattern = "???" + this.key + "???";
      }
    }

    // format message
    String message = pattern;
    if ((this.pattern != null || bundle != null) && this.params.size() != 0) {
      // set timezone on formatters
      TimeZone timeZone = null;
      TimeZoneTag timeZoneTag = (TimeZoneTag) findAncestorWithClass(this, TimeZoneTag.class);
      if (timeZoneTag != null) timeZone = timeZoneTag.getTimeZone();
      if (timeZone == null) timeZone = I18nUtil.findTimeZone(pageContext);

      MessageFormat formatter = new MessageFormat(pattern, I18nUtil.findLocale(pageContext));
      for (Format format : formatter.getFormatsByArgumentIndex()) {
        if (format != null && format instanceof DateFormat) {
          ((DateFormat) format).setTimeZone(timeZone);
        }
      }

      // now format!
      message = formatter.format(getParams());
    }

    // output text
    if (this.var == null) {
      try {
        pageContext.getOut().print(message);
      } catch (IOException e) {
        throw new JspException(e);
      }
    }

    // store result
    else {
      pageContext.setAttribute(this.var, message, this.scope);
    }

    // clear old state
    this.pattern = null;
    this.bundle = null;
    this.key = null;
    this.var = null;
    this.scope = PageContext.PAGE_SCOPE;

    // continue with page
    return EVAL_PAGE;
  }
Ejemplo n.º 25
0
  /**
   * The constructor for this class has a bunch of arguments: The frame argument is required for all
   * printing in Java. The jobname appears left justified at the top of each printed page. The font
   * size is specified in points, as on-screen font sizes are. The margins are specified in inches
   * (or fractions of inches).
   */
  public HardcopyWriter(
      Frame frame,
      String jobname,
      int fontsize,
      double leftmargin,
      double rightmargin,
      double topmargin,
      double bottommargin)
      throws HardcopyWriter.PrintCanceledException {
    // Get the PrintJob object with which we'll do all the printing.
    // The call is synchronized on the static printprops object, which
    // means that only one print dialog can be popped up at a time.
    // If the user clicks Cancel in the print dialog, throw an exception.
    Toolkit toolkit = frame.getToolkit(); // get Toolkit from Frame
    synchronized (printprops) {
      job = toolkit.getPrintJob(frame, jobname, printprops);
    }
    if (job == null) throw new PrintCanceledException("User cancelled print request");

    pagesize = job.getPageDimension(); // query the page size
    pagedpi = job.getPageResolution(); // query the page resolution

    // Bug Workaround:
    // On windows, getPageDimension() and getPageResolution don't work, so
    // we've got to fake them.
    if (System.getProperty("os.name").regionMatches(true, 0, "windows", 0, 7)) {
      // Use screen dpi, which is what the PrintJob tries to emulate, anyway
      pagedpi = toolkit.getScreenResolution();
      System.out.println(pagedpi);
      // Assume a 8.5" x 11" page size.  A4 paper users have to change this.
      pagesize = new Dimension((int) (8.5 * pagedpi), 11 * pagedpi);
      System.out.println(pagesize);
      // We also have to adjust the fontsize.  It is specified in points,
      // (1 point = 1/72 of an inch) but Windows measures it in pixels.
      fontsize = fontsize * pagedpi / 72;
      System.out.println(fontsize);
      System.out.flush();
    }

    // Compute coordinates of the upper-left corner of the page.
    // I.e. the coordinates of (leftmargin, topmargin).  Also compute
    // the width and height inside of the margins.
    x0 = (int) (leftmargin * pagedpi);
    y0 = (int) (topmargin * pagedpi);
    width = pagesize.width - (int) ((leftmargin + rightmargin) * pagedpi);
    height = pagesize.height - (int) ((topmargin + bottommargin) * pagedpi);

    // Get body font and font size
    font = new Font("Monospaced", Font.PLAIN, fontsize);
    metrics = toolkit.getFontMetrics(font);
    lineheight = metrics.getHeight();
    lineascent = metrics.getAscent();
    charwidth = metrics.charWidth('0'); // Assumes a monospaced font!

    // Now compute columns and lines will fit inside the margins
    chars_per_line = width / charwidth;
    lines_per_page = height / lineheight;

    // Get header font information
    // And compute baseline of page header: 1/8" above the top margin
    headerfont = new Font("SansSerif", Font.ITALIC, fontsize);
    headermetrics = toolkit.getFontMetrics(headerfont);
    headery = y0 - (int) (0.125 * pagedpi) - headermetrics.getHeight() + headermetrics.getAscent();

    // Compute the date/time string to display in the page header
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT);
    df.setTimeZone(TimeZone.getDefault());
    time = df.format(new Date());

    this.jobname = jobname; // save name
    this.fontsize = fontsize; // save font size
  }
  /**
   * Process the specified HTTP request, and create the corresponding HTTP response (or forward to
   * another web component that will create it). Return an <code>ActionForward</code> instance
   * describing where and how control should be forwarded, or <code>null</code> if the response has
   * already been completed.
   *
   * @param mapping The ActionMapping used to select this instance
   * @param form The optional ActionForm bean for this request (if any)
   * @param request The HTTP request we are processing
   * @param response The HTTP response we are creating
   * @exception Exception if business logic throws an exception
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    // Extract attributes we will need
    MessageResources messages = getResources(request);

    // save errors
    ActionMessages errors = new ActionMessages();

    // START check for login (security)
    if (!SecurityService.getInstance().checkForLogin(request.getSession(false))) {
      return (mapping.findForward("welcome"));
    }
    // END check for login (security)

    // START get id of current project from either request, attribute, or cookie
    // id of project from request
    String projectId = null;
    projectId = request.getParameter("projectViewId");

    // check attribute in request
    if (projectId == null) {
      projectId = (String) request.getAttribute("projectViewId");
    }

    // id of project from cookie
    if (projectId == null) {
      projectId = StandardCode.getInstance().getCookie("projectViewId", request.getCookies());
    }

    // default project to last if not in request or cookie
    if (projectId == null) {
      java.util.List results = ProjectService.getInstance().getProjectList();

      ListIterator iterScroll = null;
      for (iterScroll = results.listIterator(); iterScroll.hasNext(); iterScroll.next()) {}
      iterScroll.previous();
      Project p = (Project) iterScroll.next();
      projectId = String.valueOf(p.getProjectId());
    }

    Integer id = Integer.valueOf(projectId);

    // END get id of current project from either request, attribute, or cookie

    // get project
    Project p = ProjectService.getInstance().getSingleProject(id);

    // get user (project manager)
    User u =
        UserService.getInstance()
            .getSingleUserRealName(
                StandardCode.getInstance().getFirstName(p.getPm()),
                StandardCode.getInstance().getLastName(p.getPm()));

    // START process pdf
    try {
      PdfReader reader = new PdfReader("C://templates/CL01_001.pdf"); // the template

      // save the pdf in memory
      ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();

      // the filled-in pdf
      PdfStamper stamp = new PdfStamper(reader, pdfStream);

      // stamp.setEncryption(true, "pass", "pass", PdfWriter.AllowCopy | PdfWriter.AllowPrinting);
      AcroFields form1 = stamp.getAcroFields();
      Date cDate = new Date();
      Integer month = cDate.getMonth();
      Integer day = cDate.getDate();
      Integer year = cDate.getYear() + 1900;
      String[] monthName = {
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
      };

      // set the field values in the pdf form
      // form1.setField("", projectId)
      form1.setField("currentdate", monthName[month] + " " + day + ", " + year);
      form1.setField(
          "firstname", StandardCode.getInstance().noNull(p.getContact().getFirst_name()));
      form1.setField("pm", p.getPm());
      form1.setField("emailpm", u.getWorkEmail1());
      if (u.getWorkPhoneEx() != null && u.getWorkPhoneEx().length() > 0) { // ext present
        form1.setField(
            "phonepm",
            StandardCode.getInstance().noNull(u.getWorkPhone())
                + " ext "
                + StandardCode.getInstance().noNull(u.getWorkPhoneEx()));
      } else { // no ext present
        form1.setField("phonepm", StandardCode.getInstance().noNull(u.getWorkPhone()));
      }
      form1.setField("faxpm", StandardCode.getInstance().noNull(u.getLocation().getFax_number()));
      form1.setField("postalpm", StandardCode.getInstance().printLocation(u.getLocation()));

      // START add images
      //                if(u.getPicture() != null && u.getPicture().length() > 0) {
      //                    PdfContentByte over;
      //                    Image img = Image.getInstance("C:/Program Files (x86)/Apache Software
      // Foundation/Tomcat 7.0/webapps/logo/images/" + u.getPicture());
      //                    img.setAbsolutePosition(200, 200);
      //                    over = stamp.getOverContent(1);
      //                    over.addImage(img, 54, 0,0, 65, 47, 493);
      //                }
      // END add images
      form1.setField("productname", StandardCode.getInstance().noNull(p.getProduct()));
      form1.setField("project", p.getNumber() + p.getCompany().getCompany_code());
      form1.setField("description", StandardCode.getInstance().noNull(p.getProductDescription()));
      form1.setField("additional", p.getProjectRequirements());

      // get sources and targets
      StringBuffer sources = new StringBuffer("");
      StringBuffer targets = new StringBuffer("");
      if (p.getSourceDocs() != null) {
        for (Iterator iterSource = p.getSourceDocs().iterator(); iterSource.hasNext(); ) {
          SourceDoc sd = (SourceDoc) iterSource.next();
          sources.append(sd.getLanguage() + " ");
          if (sd.getTargetDocs() != null) {
            for (Iterator iterTarget = sd.getTargetDocs().iterator(); iterTarget.hasNext(); ) {
              TargetDoc td = (TargetDoc) iterTarget.next();
              if (!td.getLanguage().equals("All")) targets.append(td.getLanguage() + " ");
            }
          }
        }
      }

      form1.setField("source", sources.toString());
      form1.setField("target", targets.toString());
      form1.setField(
          "start",
          (p.getStartDate() != null)
              ? DateFormat.getDateInstance(DateFormat.SHORT).format(p.getStartDate())
              : "");
      form1.setField(
          "due",
          (p.getDueDate() != null)
              ? DateFormat.getDateInstance(DateFormat.SHORT).format(p.getDueDate())
              : "");

      if (p.getCompany().getCcurrency().equalsIgnoreCase("USD")) {

        form1.setField(
            "cost",
            (p.getProjectAmount() != null)
                ? "$ " + StandardCode.getInstance().formatDouble(p.getProjectAmount())
                : "");
      } else {
        form1.setField(
            "cost",
            (p.getProjectAmount() != null)
                ? "€ "
                    + StandardCode.getInstance()
                        .formatDouble(p.getProjectAmount() / p.getEuroToUsdExchangeRate())
                : "");
      }
      // stamp.setFormFlattening(true);
      stamp.close();

      // write to client (web browser)

      response.setHeader(
          "Content-disposition",
          "attachment; filename="
              + p.getNumber()
              + p.getCompany().getCompany_code()
              + "-Order-Confirmation"
              + ".pdf");

      OutputStream os = response.getOutputStream();
      pdfStream.writeTo(os);
      os.flush();
    } catch (Exception e) {
      System.err.println("PDF Exception:" + e.getMessage());
      throw new RuntimeException(e);
    }
    // END process pdf

    // Forward control to the specified success URI
    return (mapping.findForward("Success"));
  }
Ejemplo n.º 27
0
 static {
   String pattern = "EEE, dd MMM yyyy HH:mm:ss zzz";
   tz = TimeZone.getTimeZone("GMT");
   df = new SimpleDateFormat(pattern, Locale.US);
   df.setTimeZone(tz);
 }
Ejemplo n.º 28
0
/**
 * Usage: java EDU.purdue.cs.bloat.optimize.Main [-options] classes dir
 *
 * <p>where options include: -help print out this message -v -verbose turn on verbose mode -debug
 * display a hideous amount of debug info -classpath <directories separated by colons> list
 * directories in which to look for classes -f optimize files even if up-to-date -closure
 * recursively optimize referenced classes -relax-loading don't report errors if a class is not
 * found -skip <class|package.*> skip the given class or package -only <class|package.*> skip all
 * but the given class or package -preserve-debug try to preserve debug information -[no]anno insert
 * an annotation in the contant pool -[no]stack-alloc try to push locals onto the operand stack
 * -peel-loops <n|all> peel innermost loops to enable code hoisting (n >= 0 is the maximum loop
 * level to peel) -[no]pre perform partial redundency elimination -[no]appre perform partial
 * redundency elimination on access paths -[no]dce perform dead code elimination -diva perform
 * demand-driven induction variable analysis -[no]prop perform copy and constant propagation
 */
public class Main {
  // Flags that can be set/unset from the command line
  static boolean DEBUG = false; // Display debugging information

  static boolean VERBOSE = false; // Display status information as program
  // runs

  public static boolean TRACE = false; // Track our progress

  static boolean FORCE = false; // Optimize file even if they are up-to-date

  static boolean CLOSURE = false; // Opimtize over entire heirarchy (i.e.
  // start

  // at the specified classes and recurse up the
  // class heirarchy)

  static DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG);

  static boolean DIVA = false;

  public static boolean PRE = true;

  public static boolean DCE = true;

  public static boolean PROP = true;

  public static boolean FOLD = true; // Value folding

  public static boolean INFER = true; // Type inference

  public static boolean NUMBER = true; // Value numbering

  public static boolean PERSIST = false; // Persistent check elimination

  public static boolean STACK_ALLOC = false;

  public static boolean COMPACT_ARRAY_INIT = true;

  static boolean ANNO = true; // Note that class file was optimized

  public static boolean VERIFY = true;

  public static boolean OPT_STACK_1 = false; // Perform stack optimizations

  public static boolean OPT_STACK_2 = false;

  static String[] ARGS = null; // Arguments from the command line

  public static List SKIP = new ArrayList(); // Classes that are specifically
  // not optimized

  static List ONLY = new ArrayList(); // Classes that are specifically
  // optimized

  static String METHOD = null; // The name of one method to edit

  static BloatContext context = null;

  static ClassFileLoader loader = null; // Used to load classes from class
  // files

  /**
   * Parses the command line. The user must specify at least one class to optimize and the directory
   * in which to place the optimized class files. The methods of the specified classes are then
   * optimized according to the command line options.
   *
   * @see ClassEditor
   * @see ClassFileLoader
   * @see ClassFile
   * @see MethodEditor
   * @see MethodInfo
   * @see CompactArrayInitializer
   * @see FlowGraph
   */
  public static void main(final String[] args) {
    try {
      Main.loader = new ClassFileLoader();

      List classes = new ArrayList(args.length); // The classes to
      // optimize
      boolean gotdir = false; // Has an output directory been specified?

      Main.ARGS = args;

      for (int i = 0; i < args.length; i++) {
        if (args[i].equals("-v") || args[i].equals("-verbose")) {
          Main.VERBOSE = true;
          Main.loader.setVerbose(true);

        } else if (args[i].equals("-debug")) {
          Main.DEBUG = true;
          Main.loader.setVerbose(true);
          ClassFileLoader.DEBUG = true;
          CompactArrayInitializer.DEBUG = true;
          ClassEditor.DEBUG = true;
          FlowGraph.DEBUG = true;
          DominatorTree.DEBUG = true;
          Tree.DEBUG = true;
          CodeGenerator.DEBUG = true;
          Liveness.DEBUG = true;
          SSA.DEBUG = true;
          SSAGraph.DEBUG = true;
          PersistentCheckElimination.DEBUG = true;
          ValueNumbering.DEBUG = true;
          ValueFolding.DEBUG = true;
          ClassHierarchy.DEBUG = true;
          TypeInference.DEBUG = true;
          SSAPRE.DEBUG = true;
          StackPRE.DEBUG = true;
          ExprPropagation.DEBUG = true;
          DeadCodeElimination.DEBUG = true;
          CodeGenerator.DB_OPT_STACK = true;

        } else if (args[i].equals("-trace")) {
          Main.TRACE = true;

        } else if (args[i].equals("-db")) {

          if (++i >= args.length) {
            System.err.println("** No debugging option specified");
            Main.usage();
          }

          if (args[i].equals("bc")) {
            CodeArray.DEBUG = true;

          } else if (args[i].equals("cfg")) {
            FlowGraph.DEBUG = true;

          } else if (args[i].equals("ssa")) {
            SSA.DEBUG = true;
            SSAGraph.DEBUG = true;

          } else if (args[i].equals("graphs")) {
            FlowGraph.DB_GRAPHS = true;

          } else if (args[i].startsWith("-")) {
            i--;

          } else {
            System.err.println("** Unknown debugging option: " + args[i]);
            Main.usage();
          }

        } else if (args[i].equals("-debugvf")) {
          ValueFolding.DUMP = true;

        } else if (args[i].equals("-debugbc")) {
          BloatContext.DEBUG = true;

        } else if (args[i].equals("-help")) {
          Main.usage();

        } else if (args[i].equals("-noanno")) {
          Main.ANNO = false;

        } else if (args[i].equals("-anno")) {
          Main.ANNO = true;

        } else if (args[i].equals("-print-flow-graph")) {
          FlowGraph.PRINT_GRAPH = true;

        } else if (args[i].equals("-preserve-debug")) {
          MethodEditor.PRESERVE_DEBUG = true;

        } else if (args[i].equals("-nouse-stack-vars")) {
          Tree.USE_STACK = false;

        } else if (args[i].equals("-use-stack-vars")) {
          Tree.USE_STACK = true;

        } else if (args[i].equals("-unique-handlers")) {
          MethodEditor.UNIQUE_HANDLERS = true;

        } else if (args[i].equals("-nocompact-array-init")) {
          Main.COMPACT_ARRAY_INIT = false;

        } else if (args[i].equals("-compact-array-init")) {
          Main.COMPACT_ARRAY_INIT = true;

        } else if (args[i].equals("-nostack-alloc")) {
          Main.STACK_ALLOC = false;

        } else if (args[i].equals("-stack-alloc")) {
          Main.STACK_ALLOC = true;

        } else if (args[i].equals("-no-verify")) {
          Main.VERIFY = false;

        } else if (args[i].equals("-peel-loops")) {
          if (++i >= args.length) {
            Main.usage();
          }

          final String n = args[i];

          if (n.equals("all")) {
            FlowGraph.PEEL_LOOPS_LEVEL = FlowGraph.PEEL_ALL_LOOPS;

          } else {
            try {
              FlowGraph.PEEL_LOOPS_LEVEL = Integer.parseInt(n);

              if (FlowGraph.PEEL_LOOPS_LEVEL < 0) {
                Main.usage();
              }
            } catch (final NumberFormatException ex) {
              Main.usage();
            }
          }

        } else if (args[i].equals("-color")) {
          Liveness.UNIQUE = false;

        } else if (args[i].equals("-nocolor")) {
          Liveness.UNIQUE = true;

        } else if (args[i].equals("-only-method")) {
          if (++i >= args.length) {
            Main.usage();
          }

          Main.METHOD = args[i];

        } else if (args[i].equals("-classpath")) {
          if (++i >= args.length) {
            Main.usage();
          }

          final String classpath = args[i];
          Main.loader.setClassPath(classpath);

        } else if (args[i].equals("-classpath/p")) {
          if (++i >= args.length) {
            Main.usage();
          }

          final String classpath = args[i];
          Main.loader.prependClassPath(classpath);

        } else if (args[i].equals("-skip")) {
          if (++i >= args.length) {
            Main.usage();
          }

          String pkg = args[i];

          // Account for class file name on command line
          if (pkg.endsWith(".class")) {
            pkg = pkg.substring(0, pkg.lastIndexOf('.'));
          }

          Main.SKIP.add(pkg.replace('.', '/'));

        } else if (args[i].equals("-only")) {
          if (++i >= args.length) {
            Main.usage();
          }

          String pkg = args[i];

          // Account for class file name on command line
          if (pkg.endsWith(".class")) {
            pkg = pkg.substring(0, pkg.lastIndexOf('.'));
          }

          Main.ONLY.add(pkg.replace('.', '/'));

        } else if (args[i].equals("-nodce")) {
          Main.DCE = false;

        } else if (args[i].equals("-noprop")) {
          Main.PROP = false;

        } else if (args[i].equals("-noappre")) {
          SSAPRE.NO_ACCESS_PATHS = true;

        } else if (args[i].equals("-nopre")) {
          Main.PRE = false;

        } else if (args[i].equals("-dce")) {
          Main.DCE = true;

        } else if (args[i].equals("-prop")) {
          Main.PROP = true;

        } else if (args[i].equals("-appre")) {
          SSAPRE.NO_ACCESS_PATHS = false;

        } else if (args[i].equals("-pre")) {
          Main.PRE = true;

        } else if (args[i].equals("-closure")) {
          Main.CLOSURE = true;

        } else if (args[i].equals("-opt-stack-1")) {
          Main.OPT_STACK_1 = true;
          CodeGenerator.OPT_STACK = true;

        } else if (args[i].equals("-opt-stack-2")) {
          Main.OPT_STACK_2 = true;
          MethodEditor.OPT_STACK_2 = true;

        } else if (args[i].equals("-diva")) {
          Main.DIVA = true;

        } else if (args[i].equals("-no-thread")) {
          SSAPRE.NO_THREAD = true;

        } else if (args[i].equals("-no-precise")) {
          SSAPRE.NO_PRECISE = true;

        } else if (args[i].equals("-relax-loading")) {
          ClassHierarchy.RELAX = true;

        } else if (args[i].equals("-f") || args[i].equals("-force")) {
          Main.FORCE = true;

        } else if (args[i].startsWith("-")) {
          System.err.println("No such option: " + args[i]);
          Main.usage();

        } else if (i == args.length - 1) {
          // Last argument is the name of the output directory

          final File f = new File(args[i]);

          if (f.exists() && !f.isDirectory()) {
            System.err.println("No such directory: " + f.getPath());
            System.exit(2);
          }

          if (!f.exists()) {
            f.mkdirs();
          }

          if (!f.exists()) {
            System.err.println("Couldn't create directory: " + f.getPath());
            System.exit(2);
          }

          // Tell class loader to put optimized classes in f directory
          Main.loader.setOutputDir(f);
          gotdir = true;
        } else {
          // The argument must be a class name...
          classes.add(args[i]);
        }
      }

      if (!gotdir) {
        System.err.println("No output directory specified");
        Main.usage();
      }

      if (classes.size() == 0) {
        System.err.println("** No classes specified");
        Main.usage();
      }

      // Use the CachingBloatingContext
      Main.context = new CachingBloatContext(Main.loader, classes, Main.CLOSURE);

      boolean errors = false;

      final Iterator iter = classes.iterator();

      // Now that we've parsed the command line, load the classes into the
      // class loader
      while (iter.hasNext()) {
        final String name = (String) iter.next();

        try {
          Main.context.loadClass(name);

        } catch (final ClassNotFoundException ex) {
          System.err.println("Couldn't find class: " + ex.getMessage());

          errors = true;
        }
      }

      if (errors) {
        System.exit(1);
      }

      if (!Main.CLOSURE) {
        final Iterator e = classes.iterator();

        // Edit only the classes that were specified on the command line

        while (e.hasNext()) {
          final String name = (String) e.next();
          Main.editClass(name);
        }
      } else {
        // Edit all the classes in the class file editor and their
        // superclasses

        classes = null;

        if (Main.TRACE) {
          System.out.println("Computing closure " + Main.dateFormat.format(new Date()));
        }

        final Iterator e = Main.context.getHierarchy().classes().iterator();

        while (e.hasNext()) {
          final Type t = (Type) e.next();

          if (t.isObject()) {
            Main.editClass(t.className());
          }
        }
      }
    } catch (final ExceptionInInitializerError ex) {
      ex.printStackTrace();
      System.out.println(ex.getException());
    }
  }

  private static void usage() {
    System.err.println(
        "\nUsage: java EDU.purdue.cs.bloat.optimize.Main"
            + "\n            [-options] classes dir"
            + "\n"
            + "\nwhere options include:"
            + "\n    -help             print out this message"
            + "\n    -v -verbose       turn on verbose mode"
            + "\n    -debug            display a hideous amount of debug info"
            + "\n    -classpath <directories separated by colons>"
            + "\n                      list directories in which to look for classes"
            + "\n    -f                optimize files even if up-to-date"
            + "\n    -closure          recursively optimize referenced classes"
            + "\n    -relax-loading    don't report errors if a class is not found"
            + "\n    -skip <class|package.*>"
            + "\n                      skip the given class or package"
            + "\n    -only <class|package.*>"
            + "\n                      skip all but the given class or package"
            + "\n    -preserve-debug   try to preserve debug information"
            + "\n    -[no]anno         insert an annotation in the contant pool"
            + "\n    -[no]stack-alloc  try to push locals onto the operand stack"
            + "\n    -peel-loops <n|all>"
            + "\n                      peel innermost loops to enable code hoisting"
            + "\n                      (n >= 0 is the maximum loop level to peel)"
            + "\n    -[no]pre          perform partial redundency elimination"
            + "\n    -[no]dce          perform dead code elimination"
            + "\n    -diva             perform demand-driven induction variable analysis"
            + "\n    -[no]prop         perform copy and constant propagation"
            + "");
    System.exit(0);
  }

  /**
   * Performs the actual editing of a class. Does a whole mess of stuff including reading in the
   * classfile, building data structures to represent the class file, converting the CFG for each
   * method in the class into SSA form, perform some anlayses and optimizations on the method, and
   * finally committing it back to the class file. Phew.
   */
  private static void editClass(final String className) {
    ClassFile classFile; // Holds info about a class (implements
    // ClassInfo)

    // Get information about the class className
    try {
      classFile = (ClassFile) Main.context.loadClass(className);
    } catch (final ClassNotFoundException ex) {
      System.err.println("** Couldn't find class: " + ex.getMessage());
      return;
    }

    if (!Main.FORCE) {
      // Check to see if the file is up-to-date (i.e. has been
      // recompiled since it was last optimized). If so, do nothing
      // because the FORCE flag is false.

      final File source = classFile.file();
      final File target = classFile.outputFile();

      if ((source != null)
          && (target != null)
          && source.exists()
          && target.exists()
          && (source.lastModified() < target.lastModified())) {

        if (Main.VERBOSE) {
          System.out.println(classFile.name() + " is up to date");
        }

        return;
      }
    }

    if (Main.DEBUG) {
      // Print the contents of the class file to System.out
      classFile.print(System.out);
    }

    final ClassEditor c = Main.context.editClass(classFile);

    boolean skip = false;

    final String name = c.type().className();
    final String qual = c.type().qualifier() + "/*";

    // Edit only classes explicitly mentioned.
    if (Main.ONLY.size() > 0) {
      skip = true;

      // Only edit classes we explicitly don't name.
      for (int i = 0; i < Main.ONLY.size(); i++) {
        final String pkg = (String) Main.ONLY.get(i);

        if (name.equals(pkg) || qual.equals(pkg)) {
          skip = false;
          break;
        }
      }
    }

    // Don't edit classes we explicitly skip.
    if (!skip) {
      for (int i = 0; i < Main.SKIP.size(); i++) {
        final String pkg = (String) Main.SKIP.get(i);

        if (name.equals(pkg) || qual.equals(pkg)) {
          skip = true;
          break;
        }
      }
    }

    if (skip) {
      if (Main.VERBOSE) {
        System.out.println("Skipping " + c.type().className());
      }

      // We're done with this class file, decrement its reference count
      Main.context.release(classFile);
      return;
    }

    // Touch the output file first. That is, create the file, but make
    // it empty, just to make sure we can create it.

    try {
      final File f = classFile.outputFile();

      if (f.exists()) {
        f.delete();
      }

      final File dir = new File(f.getParent());
      dir.mkdirs();

      if (!dir.exists()) {
        throw new RuntimeException("Couldn't create directory: " + dir);
      }

      final DataOutputStream out = new DataOutputStream(new FileOutputStream(f));
      new PrintStream(out).println();
      out.close();
    } catch (final IOException e) {
      e.printStackTrace();
      System.exit(1);
    }

    if (Main.VERBOSE) {
      System.out.println("Optimizing " + c.type().className());
    }

    // Finally, we can start playing with the methods...
    final MethodInfo[] methods = c.methods();

    final int numMethods = methods.length + 1;
    ;
    int whichMethod = 0;

    for (int j = 0; j < methods.length; j++) {
      final MethodEditor m;

      try {
        m = Main.context.editMethod(methods[j]);
      } catch (final ClassFormatException ex) {
        System.err.println(ex.getMessage());
        continue;
      }

      if (Main.TRACE) {
        whichMethod++;
        System.out.println(
            "Optimizing "
                + name
                + "."
                + m.name()
                + " (method "
                + whichMethod
                + " of "
                + numMethods
                + ")");
      }

      if (Main.METHOD != null) {
        // A method name has been specified on the command line using
        // -only-method.
        boolean pass = true;

        String t = m.name() + m.type();

        if (t.equals(Main.METHOD)) {
          pass = false;
        }

        t = m.name();

        if (t.equals(Main.METHOD)) {
          pass = false;
        }

        if (pass) {
          // This isn't the method we're looking for.
          // Decrement its reference count.
          Main.context.release(methods[j]);
          continue;
        }
      }

      if (Main.DEBUG) {
        m.print(System.out);
      }

      if (m.isNative() || m.isAbstract()) {
        // We can't edit native or abstract methods
        Main.context.release(methods[j]);
        continue;
      }

      Main.bloatMethod(m, Main.context);
    }

    if (Main.ANNO) {
      String s = "Optimized with: EDU.purdue.cs.bloat.optimize.Main";

      for (int i = 0; i < Main.ARGS.length; i++) {
        if ((Main.ARGS[i].indexOf(' ') >= 0)
            || (Main.ARGS[i].indexOf('\t') >= 0)
            || (Main.ARGS[i].indexOf('\r') >= 0)
            || (Main.ARGS[i].indexOf('\n') >= 0)) {
          s += " '" + Main.ARGS[i] + "'";
        } else {
          s += " " + Main.ARGS[i];
        }
      }

      System.out.println(s);
      // c.constants().addConstant(Constant.UTF8, s);
    }

    Main.context.commit(classFile);
    Main.context.release(classFile);

    if (Main.TRACE) {
      System.out.println(Main.context.toString());
    }
  }

  /** Runs BLOAT on a method. */
  public static void bloatMethod(final MethodEditor m, final BloatContext context) {
    try {
      if (Main.COMPACT_ARRAY_INIT) {
        // Compact the initialization of arrays of the basic types by
        // putting the values of the array into a string in the constant
        // pool. The initialization code is replaced with a loop that
        // loads the array from the string in the constant pool.

        if (Main.TRACE) {
          System.out.println("  Compacting Arrays: " + Main.dateFormat.format(new Date()));
        }

        CompactArrayInitializer.transform(m);

        if (Main.DEBUG) {
          System.out.println("---------- After compaction:");
          m.print(System.out);
          System.out.println("---------- end print");
        }
      }

      FlowGraph cfg; // The control flow graph for a method

      if (Main.TRACE) {
        System.out.println("  Constructing CFG: " + Main.dateFormat.format(new Date()));
      }

      try {
        // Construct the control flow graph for method m
        cfg = new FlowGraph(m);
      } catch (final ClassFormatException ex) {
        System.err.println(ex.getMessage());
        context.release(m.methodInfo());
        return;
      }

      // We separate out initialization since before this the FlowGraph
      // more exactly represents the input program.
      cfg.initialize();

      if (Main.TRACE) {
        System.out.println("  Transforming to SSA: " + Main.dateFormat.format(new Date()));
      }

      SSA.transform(cfg);

      if (FlowGraph.DEBUG) {
        System.out.println("---------- After SSA:");
        cfg.print(System.out);
        System.out.println("---------- end print");
      }

      if (Main.DEBUG) {
        cfg.visit(new VerifyCFG(false));
      }

      if (!Tree.USE_STACK) {
        // Do copy propagation and value numbering first to get rid of
        // all the extra copies inserted for dups. If they're left in,
        // it really slows down value numbering.
        if (Main.PROP) {
          if (Main.DEBUG) {
            System.out.println("-----Before Copy Propagation-----");
          }

          if (Main.TRACE) {
            System.out.println("  Copy propagation: " + Main.dateFormat.format(new Date()));
          }

          final ExprPropagation copy = new ExprPropagation(cfg);
          copy.transform();

          if (Main.DEBUG) {
            cfg.visit(new VerifyCFG(false));
          }

          if (Main.DEBUG) {
            System.out.println("------After Copy Propagation-----");
            cfg.print(System.out);
          }
        }
      }

      DeadCodeElimination dce = null;

      if (Main.DCE) {

        if (Main.TRACE) {
          System.out.println("  Dead Code Elimination: " + Main.dateFormat.format(new Date()));
        }

        if (Main.DEBUG) {
          System.out.println("---Before Dead Code Elimination--");
        }

        dce = new DeadCodeElimination(cfg);
        dce.transform();

        if (Main.DEBUG) {
          cfg.visit(new VerifyCFG(false));
        }

        if (Main.DEBUG) {
          System.out.println("---After Dead Code Elimination---");
          cfg.print(System.out);
        }
      }

      if (Main.INFER) {

        if (Main.DEBUG) {
          System.out.println("---------Doing type inference--------");
        }

        if (Main.TRACE) {
          System.out.println("  Type Inferencing: " + Main.dateFormat.format(new Date()));
        }

        TypeInference.transform(cfg, context.getHierarchy());
      }

      if (Main.NUMBER) {

        if (Main.TRACE) {
          System.out.println("  Value Numbering: " + Main.dateFormat.format(new Date()));
        }

        if (Main.DEBUG) {
          System.out.println("--------Doing value numbering--------");
        }

        (new ValueNumbering()).transform(cfg);
      }

      if (Main.FOLD) {
        if (Main.DEBUG) {
          System.out.println("--------Before Value Folding---------");
        }

        if (Main.TRACE) {
          System.out.println("  Value Folding: " + Main.dateFormat.format(new Date()));
        }

        (new ValueFolding()).transform(cfg);

        if (Main.DEBUG) {
          cfg.visit(new VerifyCFG());
        }

        if (Main.DEBUG) {
          System.out.println("---------After Value Folding---------");
          cfg.print(System.out);
        }
      }

      if (Main.PRE) {
        if (Main.DEBUG) {
          System.out.println("-------------Before SSAPRE-----------");
        }

        if (Main.TRACE) {
          System.out.println("  SSAPRE: " + Main.dateFormat.format(new Date()));
        }

        final SSAPRE pre = new SSAPRE(cfg, context);
        pre.transform();

        if (Main.DEBUG) {
          cfg.visit(new VerifyCFG());
        }

        if (Main.DEBUG) {
          System.out.println("-------------After SSAPRE------------");
          cfg.print(System.out);
        }
      }

      if (Main.FOLD) {
        if (Main.DEBUG) {
          System.out.println("--------Before Value Folding---------");
        }

        if (Main.TRACE) {
          System.out.println("  Value Folding: " + Main.dateFormat.format(new Date()));
        }

        (new ValueFolding()).transform(cfg);

        if (Main.DEBUG) {
          cfg.visit(new VerifyCFG());
        }

        if (Main.DEBUG) {
          System.out.println("---------After Value Folding---------");
          cfg.print(System.out);
        }
      }

      if (Main.PROP) {
        if (Main.DEBUG) {
          System.out.println("-------Before Copy Propagation-------");
        }

        if (Main.TRACE) {
          System.out.println("  Copy Propagation " + Main.dateFormat.format(new Date()));
        }

        final ExprPropagation copy = new ExprPropagation(cfg);
        copy.transform();

        if (Main.DEBUG) {
          cfg.visit(new VerifyCFG());
        }

        if (Main.DEBUG) {
          System.out.println("--------After Copy Propagation-------");
          cfg.print(System.out);
        }
      }

      // make sure we've done at least one thing since the last DCE
      if (Main.DCE && (Main.INFER || Main.NUMBER || Main.FOLD || Main.PRE || Main.PROP)) {
        if (Main.DEBUG) {
          System.out.println("-----Before Dead Code Elimination----");
        }

        if (Main.TRACE) {
          System.out.println("  Dead Code Elimination: " + Main.dateFormat.format(new Date()));
        }

        dce = new DeadCodeElimination(cfg);
        dce.transform();

        if (Main.DEBUG) {
          cfg.visit(new VerifyCFG());
        }

        if (Main.DEBUG) {
          System.out.println("-----After Dead Code Elimination-----");
          cfg.print(System.out);
        }
      }

      if (Main.PERSIST) {
        (new PersistentCheckElimination()).transform(cfg);
      }

      if (Main.DIVA) {
        if (Main.DEBUG) {
          System.out.println("-----Before DIVA------");
        }

        if (Main.TRACE) {
          System.out.println("  DIVA: " + Main.dateFormat.format(new Date()));
        }

        (new InductionVarAnalyzer()).transform(cfg);

        if (Main.DEBUG) {
          System.out.println("-----After DIVA-----");
          cfg.print(System.out);
        }
      }

      /*
       * if (STACK_ALLOC) { if (DEBUG) {
       * System.out.println("------------Before StackPRE----------"); }
       *
       * StackPRE pre = new StackPRE(cfg); pre.transform();
       *
       * if (DEBUG) { cfg.visit(new VerifyCFG()); }
       *
       * if (DEBUG) { System.out.println("------------After
       * StackPRE-----------"); cfg.print(System.out); } }
       */

      // Do the new stack optimization
      if (Main.OPT_STACK_2) {

        if (Main.TRACE) {
          System.out.println("  New stack optimization: " + Main.dateFormat.format(new Date()));
        }

        // generate code without doing liveness or register allocation
        final CodeGenerator codegen = new CodeGenerator(m);
        codegen.replacePhis(cfg);
        m.clearCode2();
        cfg.visit(codegen);
        // do stack optimization on the bytecode

        final StackOpt so = new StackOpt();
        so.transform(m);

        // convert it back to a cfg
        cfg = new FlowGraph(m);
        cfg.initialize();

        // convert it back to SSA
        SSA.transform(cfg);

        // do more dead code elimination (eliminate stores)
        dce = new DeadCodeElimination(cfg);
        dce.transform();
      }

      if (Main.TRACE) {
        System.out.println("  Register allocation: " + Main.dateFormat.format(new Date()));
      }

      if (Main.VERIFY) {
        try {
          cfg.visit(new VerifyCFG());
        } catch (final IllegalArgumentException ee) {
          System.out.println(
              " NOTE: CFG did not verify while "
                  + "bloating "
                  + m.name()
                  + " after all optimizations. Exception: "
                  + ee);
        }
      }

      // We're all done performing optimizations. Let's generate some code
      // and go home.

      // Perform liveness analysis of variables in the method.
      // Assign local variables ("registers") to expression values.
      final Liveness liveness = new Liveness(cfg);
      final RegisterAllocator alloc = new RegisterAllocator(cfg, liveness);

      // Gather information which can be used to optimize use of the stack
      if (CodeGenerator.OPT_STACK) {
        if (Main.TRACE) {
          System.out.println("  Old stack optimization: " + Main.dateFormat.format(new Date()));
        }
        StackOptimizer.optimizeCFG(cfg);
      }

      if (Main.TRACE) {
        System.out.println("  Code Generation: " + Main.dateFormat.format(new Date()));
      }

      // Start the code generation process.
      final CodeGenerator codegen = new CodeGenerator(m);
      codegen.replacePhis(cfg);

      if (Main.DEBUG) {
        System.out.println("After fixing Phis------------------------");
        cfg.print(System.out);
        System.out.println("End print--------------------------------");
      }

      codegen.simplifyControlFlow(cfg);
      codegen.allocReturnAddresses(cfg, alloc);

      if (Main.DEBUG) {
        System.out.println("After removing empty blocks--------------");
        cfg.print(System.out);
        System.out.println("End print--------------------------------");
      }

      // Clear the old contents of the bytecode store and generate new
      // code.
      // Code is generated using a visitor pattern on the CFG.
      m.clearCode();
      cfg.visit(codegen);

      Peephole.transform(m);

      // Commit any changes that have been made to the method
      context.commit(m.methodInfo());

    } catch (final Exception ex99) {
      final String msg =
          "** Exception while optimizing "
              + m.name()
              + m.type()
              + " of class "
              + m.declaringClass().name();
      System.err.println(msg);
      System.err.println(ex99.getMessage());
      ex99.printStackTrace(System.err);
      System.exit(1);
    }
  }

  public static void dumpcode(final MethodEditor m) {

    final PrintWriter out = new PrintWriter(System.out, true);
    final StackHeightCounter shc = new StackHeightCounter(m);

    out.println("Code for method " + m.name() + m.type());
    final List instructions = m.code();
    final ListIterator iter = instructions.listIterator();
    while (iter.hasNext()) {
      final Object obj = iter.next();
      if (obj instanceof Label) {
        shc.handle((Label) obj);
      } else if (obj instanceof Instruction) {
        shc.handle((Instruction) obj);
      }

      System.out.println("        " + obj + " (sh: " + shc.height() + ")");
    }
  }
}
  @Override
  public void handle(
      String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    if (!path.equals(request.getRequestURI())) {
      return;
    }

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("text/plain");

    PrintWriter out = null;
    try {
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");

      out = response.getWriter();

      Map<String, Endpoint> endpointMap = tracker.getEndpointMap();
      Map<String, Long> expirationMap = tracker.getExpirationMap();

      out.println("Active sessions:");
      out.println();

      for (Map.Entry<String, Endpoint> ep : endpointMap.entrySet()) {
        String key = ep.getKey();
        out.print(ep.getKey());
        out.print(" => ");
        out.print(ep.getValue());

        Long expiration = expirationMap.get(key);
        if (expiration == null) {
          out.println(" (expiration unknown)");
        } else {
          out.print(" (expires ");
          out.print(df.format(new Date(expiration)));
          out.println(")");
        }
      }

      out.println();
      out.println("Events:");
      out.println();

      for (EndpointEvent event : tracker.getEvents()) {
        out.print(df.format(new Date(event.getTimestamp())));
        out.print(" ");
        out.print(event.getStatus().name());
        out.print(" ");
        out.print(event.getConnectionId());
        out.print(" ");
        out.print(event.getDetails());
        out.println();
      }
    } finally {
      try {
        if (out != null) {
          out.close();
        }
      } catch (Throwable ignored) {
      }
    }
    baseRequest.setHandled(true);
  }
Ejemplo n.º 30
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.");
  }