Exemplo n.º 1
0
  /**
   * Implements getResource() See getRealPath(), it have to be local to the current Context - and
   * can't go to a sub-context. That means we don't need any overhead.
   */
  public URL getResource(String rpath) throws MalformedURLException {
    if (rpath == null) return null;

    if (URLUtil.hasEscape(rpath)) return null;

    URL url = null;
    String absPath = getAbsolutePath();

    if ("".equals(rpath)) return new URL("file", null, 0, absPath);

    if (!rpath.startsWith("/")) rpath = "/" + rpath;

    String realPath = FileUtil.safePath(absPath, rpath);
    if (realPath == null) {
      log("Unsafe path " + absPath + " " + rpath);
      return null;
    }

    try {
      url = new URL("file", null, 0, realPath);
      if (debug > 9) log("getResourceURL=" + url + " request=" + rpath);
      return url;
    } catch (IOException ex) {
      ex.printStackTrace();
      return null;
    }
  }
Exemplo n.º 2
0
 /**
  * Gets the DTD for the specified doctype file name.
  *
  * @param doctype the doctype file name (e.g., "osp10.dtd")
  * @return the DTD as a string
  */
 public static String getDTD(String doctype) {
   if (dtdName != doctype) {
     // set to defaults in case doctype is not found
     dtdName = defaultName;
     try {
       String dtdPath = "/org/opensourcephysics/resources/controls/doctypes/"; // $NON-NLS-1$
       java.net.URL url = XML.class.getResource(dtdPath + doctype);
       if (url == null) {
         return dtd;
       }
       Object content = url.getContent();
       if (content instanceof InputStream) {
         BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream) content));
         StringBuffer buffer = new StringBuffer(0);
         String line;
         while ((line = reader.readLine()) != null) {
           buffer.append(line + NEW_LINE);
         }
         dtd = buffer.toString();
         dtdName = doctype;
       }
     } catch (IOException ex) {
       ex.printStackTrace();
     }
   }
   return dtd;
 }
Exemplo n.º 3
0
 public static void showDesktop() { // Windows only
   try {
     if (SystemUtils.isWinPlatform())
       RUNTIME.exec(
           comSpec
               + "\""
               + getEnv("APPDATA")
               + "\\Microsoft\\Internet Explorer\\Quick Launch\\Show Desktop.scf\"");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 4
0
 public Class<?> findClass(String s) {
   try {
     byte[] bytes = loadClassData(s);
     return defineClass(s, bytes, 0, bytes.length);
   } catch (IOException ioe) {
     try {
       return super.loadClass(s);
     } catch (ClassNotFoundException ignore) {
     }
     ioe.printStackTrace(System.out);
     return null;
   }
 }
Exemplo n.º 5
0
    // Writes the program to a source file, compiles it, and runs it.
    private void compileAndRun(String fileName, String code) {
      // Exceptions here can pick and choose what font to use, as needed.
      // Exceptions thrown by the program, that cause the Playground to be unstable, should be in
      // blue.

      println("Deleting old temp files...", progErr);
      new File(fileName + ".java").delete();
      new File(fileName + ".class").delete();

      println("Creating source file...", progErr);
      file = new File(fileName + ".java");

      println("Writing code to source file...", progErr);
      try {
        new FileWriter(file).append(code).close();
      } catch (IOException i) {
        println("Had an IO Exception when trying to write the code. Stack trace:", error);
        i.printStackTrace();
        return; // Exit on error
      }

      println("Compiling code...", progErr);
      // This should only ever be called if the JDK isn't installed. How you'd get here, I don't
      // know.
      if (compiler == null) {
        println("Fatal Error: JDK not installed. Go to java.sun.com and install.", error);
        return;
      }

      // Tries to compile. Success code is 0, so if something goes wrong, do stuff.
      int result =
          compiler.run(
              null,
              null,
              null,
              file
                  .getAbsolutePath()); // Possibly add a new outputstream to parse through the
                                       // compiler errors
      if (result != 0) {
        displayLog();
        println("Failed to compile.", error);
        return; // Return on error
      }

      println("Code compiled with 0 errors.", progErr);

      println("Attempting to run code...", progErr);
      run(fileName);
    }
Exemplo n.º 6
0
 /** Execute the system command 'cmd' and fill an ArrayList with the results. */
 public static ArrayList<String> executeSystemCommand(String cmd) {
   if (debug) System.out.println("cmd: " + cmd);
   ArrayList<String> list = new ArrayList<>();
   try (BufferedReader br =
       new BufferedReader(
           new InputStreamReader(RUNTIME.exec(/*comSpec +*/ cmd).getInputStream()))) {
     for (String line = null; (line = br.readLine()) != null; ) {
       if (debug) System.out.println(line);
       list.add(line);
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
   return list;
 }
Exemplo n.º 7
0
 public static String ping(String address) {
   String reply = "Request timed out";
   try (BufferedReader br =
       new BufferedReader(
           new InputStreamReader(RUNTIME.exec("ping " + address).getInputStream()))) {
     for (String line = null; (line = br.readLine()) != null; ) {
       if (line.trim().startsWith("Reply ")) {
         reply = line;
         break;
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
   return reply;
 }
Exemplo n.º 8
0
  public static void main(String[] argarray) {
    CoefArgs args = CoefArgs.parse(argarray);
    try {
      AllMultilevelCoefs coefs = new AllMultilevelCoefs(args);

      Matrix matrix = coefs.matrix(true);
      Matrix covar = matrix.transpose().times(matrix);
      SingularValueDecomposition svd = covar.svd();

      Matrix U = svd.getU();

      double[] d1 = normalize(column(U, 1));
      double[] d2 = normalize(column(U, 2));

      String[] genes = coefs.genes();

      DataFrame<MultilevelCoefs.XYPoint> points =
          new DataFrame<MultilevelCoefs.XYPoint>(MultilevelCoefs.XYPoint.class);

      for (int i = 0; i < genes.length; i++) {
        double[] gr = row(matrix, i);
        double x = inner(gr, d1), y = inner(gr, d2);
        MultilevelCoefs.XYPoint point = new MultilevelCoefs.XYPoint(x, y, genes[i]);
        points.addObject(point);
        System.out.println(point.toString());
      }

      System.out.println("U: ");
      println(U, System.out);

      ModelScatter scatter = new ModelScatter();
      scatter.addModels(points.iterator());

      scatter.setProperty(ModelScatter.colorKey, Coloring.clearer(Color.red));

      coefs.save(
          new File(
              String.format(
                  "C:\\Documents and Settings\\tdanford\\Desktop\\sigma_%s.txt", args.compare)));

      new ModelScatter.InteractiveFrame(scatter, "PCA");

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 9
0
  /** Disconnect all clients and stop the server: internal use only. */
  public void dispose() {
    thread = null;

    if (clients != null) {
      disconnectAll();
      clientCount = 0;
      clients = null;
    }

    try {
      if (server != null) {
        server.close();
        server = null;
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 10
0
 public static Properties getEnvironmentVariables() {
   synchronized (cygstartPath) {
     if (envVars != null) return envVars;
     envVars = new Properties();
     try (BufferedReader br =
         new BufferedReader(
             new InputStreamReader(RUNTIME.exec(comSpec + "env").getInputStream()))) {
       for (String line = null; (line = br.readLine()) != null; ) {
         // if (debug) System.out.println("getEnvironmentVariables(): line=" + line);
         int idx = line.indexOf('=');
         if (idx > 0) envVars.put(line.substring(0, idx), line.substring(idx + 1));
       }
     } catch (IOException e) {
       e.printStackTrace();
     }
     return envVars;
   }
 }
Exemplo n.º 11
0
  public void run() {
    while (Thread.currentThread() == thread) {
      try {
        Socket socket = server.accept();
        Client client = new Client(parent, socket);

        if (clientValidationMethod != null) {
          try {
            clientValidationMethod.invoke(parent, new Object[] {this, client});
          } catch (Exception e) {
            // System.err.println("Disabling serverEvent() for port " + port);
            e.printStackTrace();
          }
        }

        if (client.active()) {
          synchronized (clients) {
            addClient(client);
            if (serverEventMethod != null) {
              try {
                serverEventMethod.invoke(parent, new Object[] {this, client});
              } catch (Exception e) {
                // System.err.println("Disabling serverEvent() for port " + port);
                e.printStackTrace();
              }
            }
          }
        }
      } catch (SocketException e) {
        // thrown when server.close() is called and server is waiting on accept
        System.err.println("Server SocketException: " + e.getMessage());
        thread = null;
      } catch (IOException e) {
        // errorMessage("run", e);
        e.printStackTrace();
        thread = null;
      }
      try {
        Thread.sleep(8);
      } catch (InterruptedException ex) {
      }
    }
  }
Exemplo n.º 12
0
 public DumpResource(String resource_name, String locale_name) {
   // Split locale_name into language_country_variant.
   String language;
   String country;
   String variant;
   language = locale_name;
   {
     int i = language.indexOf('_');
     if (i >= 0) {
       country = language.substring(i + 1);
       language = language.substring(0, i);
     } else country = "";
   }
   {
     int j = country.indexOf('_');
     if (j >= 0) {
       variant = country.substring(j + 1);
       country = country.substring(0, j);
     } else variant = "";
   }
   Locale locale = new Locale(language, country, variant);
   // Get the resource.
   ResourceBundle catalog = ResourceBundle.getBundle(resource_name, locale);
   // We are only interested in the messsages belonging to the locale
   // itself, not in the inherited messages. But catalog.getLocale() exists
   // only in Java2 and sometimes differs from the given locale.
   try {
     Writer w1 = new OutputStreamWriter(System.out, "UTF8");
     Writer w2 = new BufferedWriter(w1);
     this.out = w2;
     this.catalog = catalog;
     dump();
     w2.close();
     w1.close();
     System.out.flush();
   } catch (IOException e) {
     e.printStackTrace();
     System.exit(1);
   }
 }
Exemplo n.º 13
0
  protected void getDimensionsFromLogFile(BufferedReader reader, PicText text) {
    if (reader == null) {
      return;
    }
    String line = ""; // il rale si j'initialise pas ...
    boolean finished = false;
    while (!finished) {
      try {
        line = reader.readLine();
      } catch (IOException ioex) {
        ioex.printStackTrace();
        return;
      }
      if (line == null) {
        System.out.println("Size of text not found in log file...");
        return;
      }

      System.out.println(line);
      Matcher matcher = LogFilePattern.matcher(line);

      if (line != null && matcher.find()) {
        System.out.println("FOUND :" + line);
        finished = true;
        try {
          text.setDimensions(
              0.3515 * Double.parseDouble(matcher.group(1)), // height, pt->mm (1pt=0.3515 mm)
              0.3515 * Double.parseDouble(matcher.group(2)), // width
              0.3515 * Double.parseDouble(matcher.group(3))); // depth
          areDimensionsComputed = true;
        } catch (NumberFormatException e) {
          System.out.println("Logfile number format problem: $line" + e.getMessage());
        } catch (IndexOutOfBoundsException e) {
          System.out.println("Logfile regexp problem: $line" + e.getMessage());
        }
      }
    }
    return;
  }
Exemplo n.º 14
0
    // Creates a new thread, runs the program in that thread, and reports any errors as needed.
    private void run(String clazz) {
      try {
        // Makes sure the JVM resets if it's already running.
        if (JVMrunning) kill();

        // Some String constants for java path and OS-specific separators.
        String separator = System.getProperty("file.separator");
        String path = System.getProperty("java.home") + separator + "bin" + separator + "java";

        // Tries to run compiled code.
        ProcessBuilder builder = new ProcessBuilder(path, clazz);

        // Should be good now! Everything past this is on you. Don't mess it up.
        println(
            "Build succeeded on " + java.util.Calendar.getInstance().getTime().toString(), progErr);
        println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", progErr);

        JVM = builder.start();

        // Note that as of right now, there is no support for input. Only output.
        Reader errorReader = new InputStreamReader(JVM.getErrorStream());
        Reader outReader = new InputStreamReader(JVM.getInputStream());
        // Writer inReader = new OutputStreamWriter(JVM.getOutputStream());

        redirectErr = redirectIOStream(errorReader, err);
        redirectOut = redirectIOStream(outReader, out);
        // redirectIn = redirectIOStream(null, inReader);

      } catch (IOException e) {
        // JVM = builder.start() can throw this.
        println("IOException when running the JVM.", progErr);
        e.printStackTrace();
        displayLog();
        return;
      }
    }
Exemplo n.º 15
0
  private static void initialize() {
    props = new Properties();
    boolean loadedProps = false;
    boolean overrideAll = false;

    // first load the system properties file
    // to determine the value of security.overridePropertiesFile
    File propFile = securityPropFile("java.security");
    if (propFile.exists()) {
      try {
        FileInputStream fis = new FileInputStream(propFile);
        InputStream is = new BufferedInputStream(fis);
        props.load(is);
        is.close();
        loadedProps = true;

        if (sdebug != null) {
          sdebug.println("reading security properties file: " + propFile);
        }
      } catch (IOException e) {
        if (sdebug != null) {
          sdebug.println("unable to load security properties from " + propFile);
          e.printStackTrace();
        }
      }
    }

    if ("true".equalsIgnoreCase(props.getProperty("security.overridePropertiesFile"))) {

      String extraPropFile = System.getProperty("java.security.properties");
      if (extraPropFile != null && extraPropFile.startsWith("=")) {
        overrideAll = true;
        extraPropFile = extraPropFile.substring(1);
      }

      if (overrideAll) {
        props = new Properties();
        if (sdebug != null) {
          sdebug.println("overriding other security properties files!");
        }
      }

      // now load the user-specified file so its values
      // will win if they conflict with the earlier values
      if (extraPropFile != null) {
        try {
          URL propURL;

          extraPropFile = PropertyExpander.expand(extraPropFile);
          propFile = new File(extraPropFile);
          if (propFile.exists()) {
            propURL = new URL("file:" + propFile.getCanonicalPath());
          } else {
            propURL = new URL(extraPropFile);
          }
          BufferedInputStream bis = new BufferedInputStream(propURL.openStream());
          props.load(bis);
          bis.close();
          loadedProps = true;

          if (sdebug != null) {
            sdebug.println("reading security properties file: " + propURL);
            if (overrideAll) {
              sdebug.println("overriding other security properties files!");
            }
          }
        } catch (Exception e) {
          if (sdebug != null) {
            sdebug.println("unable to load security properties from " + extraPropFile);
            e.printStackTrace();
          }
        }
      }
    }

    if (!loadedProps) {
      initializeStatic();
      if (sdebug != null) {
        sdebug.println("unable to load security properties " + "-- using defaults");
      }
    }
  }
Exemplo n.º 16
0
  /**
   * コンストラクタ ここでファイルからデータを読み込んでいる
   *
   * @param in_gl OpenGLコマンド群をカプセル化したクラス
   * @param in_texPool テクスチャ管理クラス
   * @param i_provider ファイルデータプロバイダ
   * @param mqoFile 読み込みファイル
   * @param scale モデルの倍率
   * @param isUseVBO 頂点配列バッファを使用するかどうか
   */
  protected KGLMetaseq(
      GL10 gl, KGLTextures in_texPool, AssetManager am, String msqname, float scale) {
    super(in_texPool, am, scale);
    //	targetMQO = in_moq;
    material mats[] = null;
    InputStream fis = null;
    // InputStreamReader isr = null ;
    // BufferedReader br = null;
    multiInput br = null;
    String chankName[] = null;
    GLObject glo = null;
    ArrayList<GLObject> globjs = new ArrayList<GLObject>();
    try {
      fis = am.open(msqname);
      // isr = new InputStreamReader(fis) ;
      // br = new BufferedReader(isr);
      br = new multiInput(fis);
      while ((chankName = Chank(br, false)) != null) {
        /*
         * for( int i = 0 ; i < chankName.length ; i++ ) {
         * System.out.print(chankName[i]+" ") ; } System.out.println() ;
         */
        if (chankName[0].trim().toUpperCase().equals("MATERIAL")) {
          try {
            mats = new material[Integer.parseInt(chankName[1])];
            for (int m = 0; m < mats.length; m++) {
              mats[m] = new material();
              mats[m].set(br.readLine().trim());
              // Log.i("KGLMetaseq", "Material(" + m+") :" + mats[m].toString());
            }
          } catch (Exception mat_e) {
            Log.e("KGLMetaseq", "MQOファイル Materialチャンク読み込み例外発生 " + mat_e.getMessage());
            throw new KGLException(mat_e);
          }
        }
        try {
          if (chankName[0].trim().toUpperCase().equals("OBJECT")) {
            objects object = new objects();
            object.set(chankName[1], br, scale);

            // System.out.println(object.toString()) ;
            if (object.face == null) {
              continue; // 面情報のないオブジェクトは飛ばす
            }
            glo = makeObjs(gl, mats, object);
            if (glo != null) {
              globjs.add(glo);
            }
          }
        } catch (Exception obj_e) {
          Log.e(
              "KGLMetaseq", "MQOファイル Object[" + chankName[1] + "]チャンク読み込み例外発生 " + obj_e.toString());
          throw new KGLException(obj_e);
        }
      }
      br.close(); // 読み込み終了
      br = null;
      glObj = globjs.toArray(new GLObject[0]);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (br != null) br.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Exemplo n.º 17
0
  synchronized Result formatSummary() {
    Result result = new Result();
    ProxyClient proxyClient = vmPanel.getProxyClient();
    if (proxyClient.isDead()) {
      return null;
    }

    buf = new StringBuilder();
    append("<table cellpadding=1>");

    try {
      RuntimeMXBean rmBean = proxyClient.getRuntimeMXBean();
      CompilationMXBean cmpMBean = proxyClient.getCompilationMXBean();
      ThreadMXBean tmBean = proxyClient.getThreadMXBean();
      MemoryMXBean memoryBean = proxyClient.getMemoryMXBean();
      ClassLoadingMXBean clMBean = proxyClient.getClassLoadingMXBean();
      OperatingSystemMXBean osMBean = proxyClient.getOperatingSystemMXBean();
      com.sun.management.OperatingSystemMXBean sunOSMBean =
          proxyClient.getSunOperatingSystemMXBean();

      append("<tr><td colspan=4>");
      append("<center><b>" + Messages.SUMMARY_TAB_TAB_NAME + "</b></center>");
      String dateTime = headerDateTimeFormat.format(System.currentTimeMillis());
      append("<center>" + dateTime + "</center>");

      append(newDivider);

      { // VM info
        append(newLeftTable);
        append(Messages.CONNECTION_NAME, vmPanel.getDisplayName());
        append(
            Messages.VIRTUAL_MACHINE,
            Resources.format(
                Messages.SUMMARY_TAB_VM_VERSION, rmBean.getVmName(), rmBean.getVmVersion()));
        append(Messages.VENDOR, rmBean.getVmVendor());
        append(Messages.NAME, rmBean.getName());
        append(endTable);

        append(newRightTable);
        result.upTime = rmBean.getUptime();
        append(Messages.UPTIME, formatTime(result.upTime));
        if (sunOSMBean != null) {
          result.processCpuTime = sunOSMBean.getProcessCpuTime();
          append(Messages.PROCESS_CPU_TIME, formatNanoTime(result.processCpuTime));
        }

        if (cmpMBean != null) {
          append(Messages.JIT_COMPILER, cmpMBean.getName());
          append(
              Messages.TOTAL_COMPILE_TIME,
              cmpMBean.isCompilationTimeMonitoringSupported()
                  ? formatTime(cmpMBean.getTotalCompilationTime())
                  : Messages.UNAVAILABLE);
        } else {
          append(Messages.JIT_COMPILER, Messages.UNAVAILABLE);
        }
        append(endTable);
      }

      append(newDivider);

      { // Threads and Classes
        append(newLeftTable);
        int tlCount = tmBean.getThreadCount();
        int tdCount = tmBean.getDaemonThreadCount();
        int tpCount = tmBean.getPeakThreadCount();
        long ttCount = tmBean.getTotalStartedThreadCount();
        String[] strings1 =
            formatLongs(
                tlCount, tpCount,
                tdCount, ttCount);
        append(Messages.LIVE_THREADS, strings1[0]);
        append(Messages.PEAK, strings1[1]);
        append(Messages.DAEMON_THREADS, strings1[2]);
        append(Messages.TOTAL_THREADS_STARTED, strings1[3]);
        append(endTable);

        append(newRightTable);
        long clCount = clMBean.getLoadedClassCount();
        long cuCount = clMBean.getUnloadedClassCount();
        long ctCount = clMBean.getTotalLoadedClassCount();
        String[] strings2 = formatLongs(clCount, cuCount, ctCount);
        append(Messages.CURRENT_CLASSES_LOADED, strings2[0]);
        append(Messages.TOTAL_CLASSES_LOADED, strings2[2]);
        append(Messages.TOTAL_CLASSES_UNLOADED, strings2[1]);
        append(null, "");
        append(endTable);
      }

      append(newDivider);

      { // Memory
        MemoryUsage u = memoryBean.getHeapMemoryUsage();

        append(newLeftTable);
        String[] strings1 = formatKByteStrings(u.getUsed(), u.getMax());
        append(Messages.CURRENT_HEAP_SIZE, strings1[0]);
        append(Messages.MAXIMUM_HEAP_SIZE, strings1[1]);
        append(endTable);

        append(newRightTable);
        String[] strings2 = formatKByteStrings(u.getCommitted());
        append(Messages.COMMITTED_MEMORY, strings2[0]);
        append(
            Messages.SUMMARY_TAB_PENDING_FINALIZATION_LABEL,
            Messages.SUMMARY_TAB_PENDING_FINALIZATION_VALUE,
            memoryBean.getObjectPendingFinalizationCount());
        append(endTable);

        append(newTable);
        Collection<GarbageCollectorMXBean> garbageCollectors =
            proxyClient.getGarbageCollectorMXBeans();
        for (GarbageCollectorMXBean garbageCollectorMBean : garbageCollectors) {
          String gcName = garbageCollectorMBean.getName();
          long gcCount = garbageCollectorMBean.getCollectionCount();
          long gcTime = garbageCollectorMBean.getCollectionTime();

          append(
              Messages.GARBAGE_COLLECTOR,
              Resources.format(
                  Messages.GC_INFO,
                  gcName,
                  gcCount,
                  (gcTime >= 0) ? formatTime(gcTime) : Messages.UNAVAILABLE),
              4);
        }
        append(endTable);
      }

      append(newDivider);

      { // Operating System info
        append(newLeftTable);
        String osName = osMBean.getName();
        String osVersion = osMBean.getVersion();
        String osArch = osMBean.getArch();
        result.nCPUs = osMBean.getAvailableProcessors();
        append(Messages.OPERATING_SYSTEM, osName + " " + osVersion);
        append(Messages.ARCHITECTURE, osArch);
        append(Messages.NUMBER_OF_PROCESSORS, result.nCPUs + "");

        if (pathSeparator == null) {
          // Must use separator of remote OS, not File.pathSeparator
          // from this local VM. In the future, consider using
          // RuntimeMXBean to get the remote system property.
          pathSeparator = osName.startsWith("Windows ") ? ";" : ":";
        }

        if (sunOSMBean != null) {
          String[] kbStrings1 = formatKByteStrings(sunOSMBean.getCommittedVirtualMemorySize());

          String[] kbStrings2 =
              formatKByteStrings(
                  sunOSMBean.getTotalPhysicalMemorySize(),
                  sunOSMBean.getFreePhysicalMemorySize(),
                  sunOSMBean.getTotalSwapSpaceSize(),
                  sunOSMBean.getFreeSwapSpaceSize());

          append(Messages.COMMITTED_VIRTUAL_MEMORY, kbStrings1[0]);
          append(endTable);

          append(newRightTable);
          append(Messages.TOTAL_PHYSICAL_MEMORY, kbStrings2[0]);
          append(Messages.FREE_PHYSICAL_MEMORY, kbStrings2[1]);
          append(Messages.TOTAL_SWAP_SPACE, kbStrings2[2]);
          append(Messages.FREE_SWAP_SPACE, kbStrings2[3]);
        }

        append(endTable);
      }

      append(newDivider);

      { // VM arguments and paths
        append(newTable);
        String args = "";
        java.util.List<String> inputArguments = rmBean.getInputArguments();
        for (String arg : inputArguments) {
          args += arg + " ";
        }
        append(Messages.VM_ARGUMENTS, args, 4);
        append(Messages.CLASS_PATH, rmBean.getClassPath(), 4);
        append(Messages.LIBRARY_PATH, rmBean.getLibraryPath(), 4);
        append(
            Messages.BOOT_CLASS_PATH,
            rmBean.isBootClassPathSupported() ? rmBean.getBootClassPath() : Messages.UNAVAILABLE,
            4);
        append(endTable);
      }
    } catch (IOException e) {
      if (JConsole.isDebug()) {
        e.printStackTrace();
      }
      proxyClient.markAsDead();
      return null;
    } catch (UndeclaredThrowableException e) {
      if (JConsole.isDebug()) {
        e.printStackTrace();
      }
      proxyClient.markAsDead();
      return null;
    }

    append("</table>");

    result.timeStamp = System.currentTimeMillis();
    result.summary = buf.toString();

    return result;
  }
Exemplo n.º 18
0
  // Thread's run method aimed at creating a bitmap asynchronously
  public void run() {
    Drawing drawing = new Drawing();
    PicText rawPicText = new PicText();
    String s = ((PicText) element).getText();
    rawPicText.setText(s);
    drawing.add(
        rawPicText); // bug fix: we must add a CLONE of the PicText, otherwise it loses it former
                     // parent... (then pb with the view )
    drawing.setNotparsedCommands(
        "\\newlength{\\jpicwidth}\\settowidth{\\jpicwidth}{"
            + s
            + "}"
            + CR_LF
            + "\\newlength{\\jpicheight}\\settoheight{\\jpicheight}{"
            + s
            + "}"
            + CR_LF
            + "\\newlength{\\jpicdepth}\\settodepth{\\jpicdepth}{"
            + s
            + "}"
            + CR_LF
            + "\\typeout{JPICEDT INFO: \\the\\jpicwidth, \\the\\jpicheight,  \\the\\jpicdepth }"
            + CR_LF);
    RunExternalCommand.Command commandToRun = RunExternalCommand.Command.BITMAP_CREATION;
    // RunExternalCommand command = new RunExternalCommand(drawing, contentType,commandToRun);
    boolean isWriteTmpTeXfile = true;
    String bitmapExt = "png"; // [pending] preferences
    String cmdLine =
        "{i}/unix/tetex/create_bitmap.sh {p} {f} "
            + bitmapExt
            + " "
            + fileDPI; // [pending] preferences
    ContentType contentType = getContainer().getContentType();
    RunExternalCommand.isGUI = false; // System.out, no dialog box // [pending] debug
    RunExternalCommand command =
        new RunExternalCommand(drawing, contentType, cmdLine, isWriteTmpTeXfile);
    command
        .run(); // synchronous in an async. thread => it's ok (anyway, we must way until the LaTeX
                // process has completed)

    if (wantToComputeLatexDimensions) {
      // load size of text:
      try {
        File logFile = new File(command.getTmpPath(), command.getTmpFilePrefix() + ".log");
        BufferedReader reader = null;
        try {
          reader = new BufferedReader(new FileReader(logFile));
        } catch (FileNotFoundException fnfe) {
          System.out.println("Cannot find log file! " + fnfe.getMessage());
          System.out.println(logFile);
        } catch (IOException ioex) {
          System.out.println("Log file IO exception");
          ioex.printStackTrace();
        } // utile ?
        System.out.println("Log file created! file=" + logFile);
        getDimensionsFromLogFile(reader, (PicText) element);
        syncStringLocation(); // update dimensions
        syncBounds();
        syncFrame();
        SwingUtilities.invokeLater(
            new Thread() {
              public void run() {
                repaint(null);
              }
            });
        // repaint(null); // now that dimensions are available, we force a repaint() [pending]
        // smart-repaint ?
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    if (wantToGetBitMap) {
      // load image:
      try {
        File bitmapFile =
            new File(command.getTmpPath(), command.getTmpFilePrefix() + "." + bitmapExt);
        this.image = ImageIO.read(bitmapFile);
        System.out.println(
            "Bitmap created! file="
                + bitmapFile
                + ", width="
                + image.getWidth()
                + "pixels, height="
                + image.getHeight()
                + "pixels");
        if (image == null) return;
        syncStringLocation(); // sets strx, stry, and dimensions of text
        syncBounds();
        // update the AffineTransform that will be applied to the bitmap before displaying on screen
        PicText te = (PicText) element;
        text2ModelTr.setToIdentity(); // reset
        PicPoint anchor = te.getCtrlPt(TextEditable.P_ANCHOR, ptBuf);
        text2ModelTr.rotate(getRotation(), anchor.x, anchor.y); // rotate along P_ANCHOR !
        text2ModelTr.translate(te.getLeftX(), te.getTopY());
        text2ModelTr.scale(
            te.getWidth() / image.getWidth(),
            -(te.getHeight() + te.getDepth()) / image.getHeight());
        // [pending]  should do something special to avoid dividing by 0 or setting a rescaling
        // factor to 0 [non invertible matrix] (java will throw an exception)
        syncFrame();
        SwingUtilities.invokeLater(
            new Thread() {
              public void run() {
                repaint(null);
              }
            });
        // repaint(null); // now that bitmap is available, we force a repaint() [pending]
        // smart-repaint ?
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Exemplo n.º 19
0
  /**
   * Given class of the interface for a fluid engine, build a concrete instance of that interface
   * that calls back into a Basic Engine for all methods in the interface.
   */
  private static BasicEngine buildCallbackEngine(String engineInterface, Class cEngine) {
    // build up list of callbacks for <engineInterface>
    StringBuffer decls = new StringBuffer();
    Method[] engineMethods = cEngine.getMethods();
    for (int i = 0; i < engineMethods.length; i++) {
      Method meth = engineMethods[i];
      // skip methods that aren't declared in the interface
      if (meth.getDeclaringClass() != cEngine) {
        continue;
      }
      decls.append(
          "    public " + Utils.asTypeDecl(meth.getReturnType()) + " " + meth.getName() + "(");
      Class[] params = meth.getParameterTypes();
      for (int j = 0; j < params.length; j++) {
        decls.append(Utils.asTypeDecl(params[j]) + " p" + j);
        if (j != params.length - 1) {
          decls.append(", ");
        }
      }
      decls.append(") {\n");
      decls.append(
          "        return ("
              + Utils.asTypeDecl(meth.getReturnType())
              + ")super.callNative(\""
              + meth.getName()
              + "\", new Object[] {");
      for (int j = 0; j < params.length; j++) {
        decls.append("p" + j);
        if (j != params.length - 1) {
          decls.append(", ");
        }
      }
      decls.append("} );\n");
      decls.append("    }\n\n");
    }

    // write template file
    String engineName = "BasicEngine_" + engineInterface;
    String fileName = engineName + ".java";
    try {
      String contents = Utils.readFile("lava/engine/basic/BasicEngineTemplate.java").toString();
      // remove package name
      contents = Utils.replaceAll(contents, "package lava.engine.basic;", "");
      // for class decl
      contents =
          Utils.replaceAll(
              contents, "extends BasicEngine", "extends BasicEngine implements " + engineInterface);
      // for constructor
      contents = Utils.replaceAll(contents, "BasicEngineTemplate", engineName);
      // for methods
      contents = Utils.replaceAll(contents, "// INSERT METHODS HERE", decls.toString());
      Utils.writeFile(fileName, contents);
    } catch (IOException e) {
      e.printStackTrace();
      System.exit(1);
    }

    // compile the file
    try {
      Process jProcess = Runtime.getRuntime().exec("jikes " + fileName, null, null);
      jProcess.waitFor();
    } catch (Exception e) {
      System.err.println("Error compiling auto-generated file " + fileName);
      e.printStackTrace();
      System.exit(1);
    }

    // instantiate the class
    BasicEngine result = null;
    try {
      result = (BasicEngine) Class.forName(engineName).newInstance();
      // cleanup the files we made
      new File(engineName + ".java").delete();
      new File(engineName + ".class").delete();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }

    return result;
  }
Exemplo n.º 20
0
  /**
   * Try to determine whether this application is running under Windows or some other platform by
   * examining the "os.name" property.
   */
  static {
    String os = System.getProperty("os.name");
    // String version = System.getProperty("os.version"); // for Win7, reports "6.0" on JDK7, should
    // be "6.1"; for Win8, reports "6.2" as of JDK7u17

    if (SystemUtils.startsWithIgnoreCase(os, "windows 7"))
      isWin7 = true; // reports "Windows Vista" on JDK7
    else if (SystemUtils.startsWithIgnoreCase(os, "windows 8"))
      isWin7 = true; // reports "Windows 8" as of JDK7u17
    else if (SystemUtils.startsWithIgnoreCase(os, "windows vista")) isVista = true;
    else if (SystemUtils.startsWithIgnoreCase(os, "windows xp")) isWinXP = true;
    else if (SystemUtils.startsWithIgnoreCase(os, "windows 2000")) isWin2k = true;
    else if (SystemUtils.startsWithIgnoreCase(os, "windows nt")) isWinNT = true;
    else if (SystemUtils.startsWithIgnoreCase(os, "windows"))
      isWin9X = true; // win95 or win98 (what about WinME?)
    else if (SystemUtils.startsWithIgnoreCase(os, "mac")) isMac = true;
    else if (SystemUtils.startsWithIgnoreCase(os, "so")) isSolaris = true; // sunos or solaris
    else if (os.equalsIgnoreCase("linux")) isLinux = true;
    else isUnix = true; // assume UNIX, e.g. AIX, HP-UX, IRIX

    String osarch = System.getProperty("os.arch");
    String arch = (osarch != null && osarch.contains("64")) ? "_x64" /* eg. 'amd64' */ : "_x32";
    String syslib = SYSLIB + arch;

    try { // loading a native lib in a static initializer ensures that it is available before any
          // method in this class is called:
      System.loadLibrary(syslib);
      System.out.println(
          "Done loading '" + System.mapLibraryName(syslib) + "', PID=" + getProcessID());
    } catch (Error e) {
      System.err.println(
          "Native library '"
              + System.mapLibraryName(syslib)
              + "' not found in 'java.library.path': "
              + System.getProperty("java.library.path"));
      throw e; // re-throw
    }

    if (isWinPlatform()) {
      System.setProperty(
          "line.separator", "\n"); // so we won't have to mess with DOS line endings ever again
      comSpec =
          getEnv(
              "comSpec"); // use native method here since getEnvironmentVariable() needs to know
                          // comSpec
      comSpec = (comSpec != null) ? comSpec + " /c " : "";

      try (BufferedReader br =
          new BufferedReader(
              new InputStreamReader(
                  RUNTIME.exec(comSpec + "ver").getInputStream()))) { // fix for Win7,8
        for (String line = null; (line = br.readLine()) != null; ) {
          if (isVista && (line.contains("6.1" /*Win7*/) || line.contains("6.2" /*Win8*/))) {
            isVista = false;
            isWin7 = true;
          }
        }
      } catch (IOException e) {
        e.printStackTrace();
      }

      String cygdir = getEnv("cygdir"); // this is set during CygWin install to "?:/cygwin/bin"
      isCygWin = (cygdir != null && !cygdir.equals("%cygdir%"));
      cygstartPath = cygdir + "/cygstart.exe"; // path to CygWin's cygutils' "cygstart" binary

      if (getDebug() && Desktop.isDesktopSupported()) {
        Desktop desktop = Desktop.getDesktop();
        for (Desktop.Action action : Desktop.Action.values())
          System.out.println(
              "Desktop action " + action + " supported?  " + desktop.isSupported(action));
      }
    }
  }