Exemplo n.º 1
1
  void dateTest() throws RuntimeException {
    Locale locTH = new Locale("th", "TH", "TH");
    TimeZone tz = TimeZone.getTimeZone("PST");

    Calendar calGregorian = Calendar.getInstance(tz, Locale.US);
    calGregorian.clear();
    calGregorian.set(2002, 4, 1, 8, 30);
    final Date date = calGregorian.getTime();
    Calendar cal = Calendar.getInstance(tz, locTH);
    cal.clear();
    cal.setTime(date);

    final String strExpected =
        "\u0E27\u0E31\u0E19\u0E1E\u0E38\u0E18\u0E17\u0E35\u0E48\u0020\u0E51\u0020\u0E1E\u0E24\u0E29\u0E20\u0E32\u0E04\u0E21\u0020\u0E1E\u002E\u0E28\u002E\u0020\u0E52\u0E55\u0E54\u0E55\u002C\u0020\u0E58\u0020\u0E19\u0E32\u0E2C\u0E34\u0E01\u0E32\u0020\u0E53\u0E50\u0020\u0E19\u0E32\u0E17\u0E35\u0020\u0E50\u0E50\u0020\u0E27\u0E34\u0E19\u0E32\u0E17\u0E35";
    Date value = cal.getTime();

    // th_TH_TH test
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, locTH);
    df.setTimeZone(tz);
    String str = df.format(value);

    if (!strExpected.equals(str)) {
      throw new RuntimeException();
    }
  }
Exemplo n.º 2
0
  public void testCDate() throws ParseException {
    Date date = new Date();
    assertEquals(date, Vba.cDate(date));
    assertNull(Vba.cDate(null));
    // CInt rounds to the nearest even number
    try {
      assertEquals(DateFormat.getDateInstance().parse("Jan 12, 1952"), Vba.cDate("Jan 12, 1952"));
      assertEquals(
          DateFormat.getDateInstance().parse("October 19, 1962"), Vba.cDate("October 19, 1962"));
      assertEquals(DateFormat.getTimeInstance().parse("4:35:47 PM"), Vba.cDate("4:35:47 PM"));
      assertEquals(
          DateFormat.getDateTimeInstance().parse("October 19, 1962 4:35:47 PM"),
          Vba.cDate("October 19, 1962 4:35:47 PM"));
    } catch (ParseException e) {
      e.printStackTrace();
      fail();
    }

    try {
      Vba.cDate("Jan, 1952");
      fail();
    } catch (InvalidArgumentException e) {
      assertTrue(e.getMessage().indexOf("Jan, 1952") >= 0);
    }
  }
Exemplo n.º 3
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));
  }
Exemplo n.º 4
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);
    }
  }
Exemplo n.º 5
0
  /** {@inheritDoc} */
  protected String paramString() {
    String curDate;
    if ((selectedComponents & DISPLAY_DATE) == DISPLAY_DATE) {
      curDate = DateFormat.getDateInstance(DateFormat.FULL, locale).format(getDate());
    } else if ((selectedComponents & DISPLAY_TIME) == DISPLAY_TIME) {
      curDate = DateFormat.getTimeInstance(DateFormat.FULL, locale).format(getDate());
    } else {
      curDate =
          DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, locale)
              .format(getDate());
    }

    return super.paramString() + ",selectedDate=" + curDate;
  }
Exemplo n.º 6
0
  /**
   * Constructor for ATimeStampFmt.
   *
   * @param styleDate one of SHORT, MEDIUM, LONG, FULL or the IFmt-styles
   * @param styleTime one of SHORT, MEDIUM, LONG, FULL or the IFmt-styles
   * @param l the locale
   */
  public ATimeStampFmt(int styleDate, int styleTime, Locale l) {
    if ((styleDate & MANDATORY) != 0 || (styleTime & MANDATORY) != 0) setMandatory(true);

    int javaDateStyle = DateFormat.MEDIUM;
    int javaTimeStyle = DateFormat.MEDIUM;

    if ((styleDate & SHORT) != 0) javaDateStyle = DateFormat.SHORT;
    else if ((styleDate & LONG) != 0) javaDateStyle = DateFormat.LONG;
    else if ((styleDate & FULL) != 0) javaDateStyle = DateFormat.FULL;

    if ((styleTime & SHORT) != 0) javaTimeStyle = DateFormat.SHORT;
    else if ((styleTime & LONG) != 0) javaTimeStyle = DateFormat.LONG;
    else if ((styleTime & FULL) != 0) javaTimeStyle = DateFormat.FULL;

    dateFormat_ = DateFormat.getDateTimeInstance(javaDateStyle, javaTimeStyle, l);
    dateFormat_.setLenient(false);
  }
Exemplo n.º 7
0
 public void testFormatDateTime() {
   try {
     Date date = DateFormat.getDateTimeInstance().parse("October 19, 1962 4:35:47 PM");
     assertEquals("Oct 19, 1962 4:35:47 PM", Vba.formatDateTime(date));
     assertEquals("Oct 19, 1962 4:35:47 PM", Vba.formatDateTime(date, 0));
     assertEquals("October 19, 1962", Vba.formatDateTime(date, 1));
     assertEquals("10/19/62", Vba.formatDateTime(date, 2));
     String datestr = Vba.formatDateTime(date, 3);
     assertNotNull(datestr);
     // skip the timezone so this test runs everywhere
     // in EST, this string is "4:35:47 PM EST"
     assertTrue(datestr.startsWith("4:35:47 PM"));
     assertEquals("4:35 PM", Vba.formatDateTime(date, 4));
   } catch (ParseException e) {
     e.printStackTrace();
     fail();
   }
 }
Exemplo n.º 8
0
  public static void main(String[] args) throws Exception {
    /*
    	DateFormat的构造器是protected的 但它提供了一些静态方法来获取DateFormat实例。
    	df = new DateFormat();
    	getDateInstance - 格式化后的字符串只有日期。
    	getTimeInstance - 格式化的字符串只有时间
    	getDateTimeInstance - 格式化的的字符串有日期、时间

    */
    Date d = new Date();
    System.out.println(d);
    // 为了程序更加友好的界面,要求把Date转换成一个符合Locale的字符串。

    DateFormat df =
        DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.getDefault());
    System.out.println(df.format(d));

    String dateStr = "2007年aa月20日 星期二 上午11时54分15秒 CST";
    System.out.println(df.parse(dateStr));
  }
Exemplo n.º 9
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;
  }

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

}
Exemplo n.º 10
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() + ")");
    }
  }
}
Exemplo n.º 11
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
  }
Exemplo n.º 12
0
/**
 * This class is used in the model of the ACLTree. The MessageNode contains an ACLMessage, a
 * direction and a date/timestamp
 *
 * @author Chris van Aart - Acklin B.V., the Netherlands
 * @created April 26, 2002
 */
public class ACLMessageNode extends DefaultMutableTreeNode {

  /**
   * Constructor for the MessageNode object
   *
   * @param str Description of Parameter
   */
  ACLMessageNode(String str) {
    super(str);
  }

  /**
   * Gets the Message attribute of the MessageNode object
   *
   * @return The Message value
   */
  public ACLMessage getMessage() {
    return theMessage;
  }

  /**
   * Gets the Performative attribute of the MessageNode object
   *
   * @return The Performative value
   */
  public String getPerformative() {
    return theMessage.getPerformative(theMessage.getPerformative());
  }

  /**
   * Gets the SendTo attribute of the MessageNode object
   *
   * @return The SendTo value
   */
  public String getSendTo() {
    if (theMessage.getAllReceiver().hasNext()) {
      AID sender = (AID) theMessage.getAllReceiver().next();
      return sender.getName();
    }
    return "<unknown>";
  }

  /**
   * Gets the Ontology attribute of the MessageNode object
   *
   * @return The Ontology value
   */
  public String getOntology() {
    String ontology = theMessage.getOntology();
    if (ontology != null) {
      return ontology;
    }
    return "<unknown>";
  }

  /**
   * Gets the Direction attribute of the MessageNode object
   *
   * @return The Direction value
   */
  public String getDirection() {
    return direction;
  }

  public String getTime() {
    return time;
  }

  public Date getTheDate() {
    return theDate;
  }

  /**
   * Sets the Message attribute of the MessageNode object
   *
   * @param msg The new Message value
   */
  public void setMessage(ACLMessage msg) {
    theMessage = (ACLMessage) msg.clone();
  }

  /**
   * Sets the Direction attribute of the MessageNode object
   *
   * @param theDirection The new Direction value
   */
  public void setDirection(String theDirection) {
    direction = theDirection;
  }

  public void setTime(String theTime) {
    time = theTime;
    try {
      this.theDate = dateFormat.parse(time);
    } catch (Exception ex) {
      jade.util.Logger.getMyLogger(this.getClass().getName())
          .log(jade.util.Logger.WARNING, ex.getMessage());
    }
  }

  public void setTheDate(Date theTheDate) {
    theDate = theTheDate;
  }

  public String receivedFrom() {
    if (theMessage.getSender() != null) {
      AID sender = theMessage.getSender();
      return sender.getName();
    }
    return "<unknown>";
  }

  private static DateFormat dateFormat =
      DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM);
  private Date theDate = new Date();
  private ACLMessage theMessage;
  private String direction;
  private String time;
}
Exemplo n.º 13
0
 public static DateFormat getShortDateFormat(Locale locale) {
   if (locale.getCountry().equals("ZA")) return new SimpleDateFormat("dd/MM/yyyy h:mm a");
   else return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);
 }