Esempio n. 1
0
  private boolean checkAvaliableMemory(int neededMemory, TestResult testResult) {
    if ((ourMode & CHECK_MEMORY) == 0) return true;

    boolean possibleOutOfMemoryError = possibleOutOfMemory(neededMemory);
    if (possibleOutOfMemoryError) {
      tryGc(5);
      possibleOutOfMemoryError = possibleOutOfMemory(neededMemory);
      if (possibleOutOfMemoryError) {
        log("OutOfMemoryError: dumping memory");
        Runtime runtime = Runtime.getRuntime();
        long total = runtime.totalMemory();
        long free = runtime.freeMemory();
        String errorMessage =
            "Too much memory used. Total: "
                + total
                + " free: "
                + free
                + " used: "
                + (total - free)
                + "\n";
        addErrorMessage(testResult, errorMessage);
      }
    }
    return !possibleOutOfMemoryError;
  }
Esempio n. 2
0
  /** Metoda uruchamiana przez watek, odpowiedzialna za przerysowywanie ekranu */
  public void run() {
    int loopCount = 0;

    displayLogo();

    Runtime.getRuntime().gc();
    // setFullScreenMode(false);

    while (true) {
      updateState(); // sprawdzenie stanu przyciskow
      updateScreen(); // wyswietlenie nowej zawartosci ekranu

      loopCount++;

      if (loopCount > 200) {
        Runtime.getRuntime().gc();
        loopCount = 0;
      }

      try {
        Thread.sleep(50);
      } catch (InterruptedException e) {
        soundPlayer.play(SoundPlayer.ERROR_SOUND);
        System.out.println("Praca watku przerysowujacego zawartosc ekranu zostala przerwana!");
      }
    }
  }
Esempio n. 3
0
  /** @return a human friendly string for the VM used memory */
  private String formatUsedMemory() {
    final Runtime runtime = Runtime.getRuntime();
    final long usedBytes = runtime.totalMemory() - runtime.freeMemory();
    String formattedUsedMemory = formatMemory(usedBytes);

    return formattedUsedMemory;
  }
    public void generateDiagram(String outputDirectory, File dotFile) {
      try {
        Runtime run = Runtime.getRuntime();
        Process pr =
            run.exec(
                "dot "
                    + dotFile.getAbsolutePath()
                    + " -Tpng -o"
                    + outputDirectory
                    + FILE_SEPARATOR
                    + "graph.png");
        pr.waitFor();
        // BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));

        // should the output be really printed?
        //            String line;
        //            while ( ( line = buf.readLine() ) != null )
        //            {
        //                System.out.println(line) ;
        //            }
        // FIXME how to handle exceptions in listener?
      } catch (IOException e) {
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      } catch (InterruptedException e) {
        e
            .printStackTrace(); // To change body of catch statement use File | Settings | File
                                // Templates.
      }
    }
Esempio n. 5
0
  /**
   * Opens the URL in external browser.
   *
   * @param url
   * @throws IOException
   */
  public static void openURL(String url) throws IOException {
    String osName = System.getProperty("os.name");

    try {
      if (osName.startsWith("Mac OS")) {
        Class<?> fileMgr = Class.forName("com.apple.eio.FileManager");
        Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] {String.class});

        openURL.invoke(null, new Object[] {url});
      } else if (osName.startsWith("Windows")) {
        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
      } else { // assume Unix or Linux
        String[] browsers = {
          "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape", "dillo"
        };
        String browser = null;

        for (int count = 0; count < browsers.length && browser == null; count++) {
          String[] whichCmd = new String[] {"which", browsers[count]};

          if (Runtime.getRuntime().exec(whichCmd).waitFor() == 0) {
            browser = browsers[count];
          }
        }

        if (browser == null) {
          throw new IOException("Could not find any web browser");
        } else {
          Runtime.getRuntime().exec(new String[] {browser, url});
        }
      }
    } catch (Exception e) {
      throw new IOException("Error launching browser at URL " + url + "\n" + e.getMessage());
    }
  }
Esempio n. 6
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = request.getHeader("foo");

    String bar = new Test().doSomething(param);

    String a1 = "";
    String a2 = "";
    String osName = System.getProperty("os.name");
    if (osName.indexOf("Windows") != -1) {
      a1 = "cmd.exe";
      a2 = "/c";
    } else {
      a1 = "sh";
      a2 = "-c";
    }
    String[] args = {a1, a2, "echo", bar};

    String[] argsEnv = {"foo=bar"};

    Runtime r = Runtime.getRuntime();

    try {
      Process p = r.exec(args, argsEnv, new java.io.File(System.getProperty("user.dir")));
      org.owasp.benchmark.helpers.Utils.printOSCommandResults(p);
    } catch (IOException e) {
      System.out.println("Problem executing cmdi - TestCase");
      throw new ServletException(e);
    }
  } // end doPost
Esempio n. 7
0
  public static String getSDCardPath() {
    String cmd = "cat /proc/mounts";
    Runtime run = Runtime.getRuntime(); // 返回与当前 Java 应用程序相关的运行时对象
    try {
      Process p = run.exec(cmd); // 启动另一个进程来执行命令
      BufferedInputStream in = new BufferedInputStream(p.getInputStream());
      BufferedReader inBr = new BufferedReader(new InputStreamReader(in));

      String lineStr;
      while ((lineStr = inBr.readLine()) != null) {
        // 获得命令执行后在控制台的输出信息
        //	            	Log.i("CommonUtil:getSDCardPath", lineStr);
        if (lineStr.contains("sdcard") && lineStr.contains(".android_secure")) {
          String[] strArray = lineStr.split(" ");
          if (strArray != null && strArray.length >= 5) {
            String result = strArray[1].replace("/.android_secure", "");
            return result;
          }
        }
        // 检查命令是否执行失败。
        if (p.waitFor() != 0 && p.exitValue() == 1) {
          // p.exitValue()==0表示正常结束,1:非正常结束
          Log.e("CommonUtil:getSDCardPath", "命令执行失败!");
        }
      }
      inBr.close();
      in.close();
    } catch (Exception e) {
      //	            Log.e("CommonUtil:getSDCardPath", e.toString());

      return Environment.getExternalStorageDirectory().getPath();
    }

    return Environment.getExternalStorageDirectory().getPath();
  }
    public ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        ModelAndView mav = new ModelAndView("systeminfo");
        mav.addObject("sysprops", new TreeMap<String, String>((Map) System.getProperties()));
        mav.addObject("sysenv", new TreeMap<String, String>((Map) System.getenv()));
        mav.addObject("systime", new Date());

        //Calculate app uptime duration
        Date appStartTime = (Date) getServletContext().getAttribute("appStartTime");
        long durationMillis = new Date().getTime() - appStartTime.getTime();
        String duration = DurationFormatUtils.formatDurationWords(durationMillis, true, false);
        mav.addObject("appUptime", duration);

        //Calculate system resources.
        Runtime runtime = Runtime.getRuntime();
        long totalMem = runtime.totalMemory() / MB;
        long freeMem = runtime.freeMemory() / MB;
        long avaCPU = runtime.availableProcessors();
        mav.addObject("sysres", "CPU: " + avaCPU + ", MemoryUsed: " + (totalMem - freeMem) + "M/" + totalMem + "M");
        
        if(applicationProperties== null){
            applicationProperties = new Properties();
        }
        mav.addObject("applicationProps", applicationProperties);
        
        return mav;
    }
Esempio n. 9
0
  /*
   * (non-Javadoc)
   *
   * @see com.orientechnologies.common.test.SpeedTest#startTimer(java.lang.String)
   */
  public void startTimer(final String iName) {
    Runtime.getRuntime().runFinalization();
    Runtime.getRuntime().gc();

    try {
      Thread.sleep(TIME_WAIT);
    } catch (InterruptedException e) {
    }

    final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    final MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
    final MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();

    currentTestName = iName;

    currentTestHeapCommittedMemory = heapMemoryUsage.getCommitted();
    currentTestHeapUsedMemory = heapMemoryUsage.getUsed();
    currentTestHeapMaxMemory = heapMemoryUsage.getMax();

    currentTestNonHeapCommittedMemory = nonHeapMemoryUsage.getCommitted();
    currentTestNonHeapUsedMemory = nonHeapMemoryUsage.getUsed();
    currentTestNonHeapMaxMemory = nonHeapMemoryUsage.getMax();

    System.out.println("-> Started the test of '" + currentTestName + "' (" + cycles + " cycles)");

    currentTestTimer = System.currentTimeMillis();
  }
Esempio n. 10
0
 public static void EjecutarNativo(String cmd) {
   Runtime aplicacion = Runtime.getRuntime();
   try {
     aplicacion.exec(cmd);
   } catch (Exception e) {
   }
 }
  public void addUser(
      long companyId,
      long userId,
      String password,
      String firstName,
      String middleName,
      String lastName,
      String emailAddress) {

    try {
      CyrusServiceUtil.addUser(userId, emailAddress, password);

      // Expect

      String addUserCmd = PropsUtil.get(PropsKeys.MAIL_HOOK_CYRUS_ADD_USER);

      addUserCmd = StringUtil.replace(addUserCmd, "%1%", String.valueOf(userId));

      Runtime rt = Runtime.getRuntime();

      Process p = rt.exec(addUserCmd);

      ProcessUtil.close(p);
    } catch (Exception e) {
      _log.error(e, e);
    }
  }
Esempio n. 12
0
  public static void main(String args[]) {

    try {
      Runtime rt = Runtime.getRuntime();
      // Process pr = rt.exec("cmd /c dir");
      Process pr = rt.exec("python ciao.py");

      BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

      String line = null;

      while ((line = input.readLine()) != null) {
        System.out.println(line);
      }

      int exitVal = pr.waitFor();
      if (exitVal == 0) {
        System.out.println("Exited without errors ");
      } else {
        System.out.println("Exited with error code " + exitVal);
      }

    } catch (Exception e) {
      System.out.println(e.toString());
      e.printStackTrace();
    }
  }
Esempio n. 13
0
 /**
  * Opens the specified web page in the user's default browser
  *
  * @param url A web address (URL) of a web page (ex: "http://www.google.com/")
  */
 public static void openURL(String url) {
   try { // attempt to use Desktop library from JDK 1.6+ (even if on 1.5)
     Class<?> d = Class.forName("java.awt.Desktop");
     d.getDeclaredMethod("browse", new Class[] {java.net.URI.class})
         .invoke(
             d.getDeclaredMethod("getDesktop").invoke(null),
             new Object[] {java.net.URI.create(url)});
     // above code mimics:
     //   java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
   } catch (Exception ignore) { // library not available or failed
     String osName = System.getProperty("os.name");
     try {
       if (osName.startsWith("Mac OS")) {
         Class.forName("com.apple.eio.FileManager")
             .getDeclaredMethod("openURL", new Class[] {String.class})
             .invoke(null, new Object[] {url});
       } else if (osName.startsWith("Windows"))
         Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
       else { // assume Unix or Linux
         boolean found = false;
         for (String browser : browsers)
           if (!found) {
             found = Runtime.getRuntime().exec(new String[] {"which", browser}).waitFor() == 0;
             if (found) Runtime.getRuntime().exec(new String[] {browser, url});
           }
         if (!found) throw new Exception(Arrays.toString(browsers));
       }
     } catch (Exception e) {
       JOptionPane.showMessageDialog(null, errMsg + "\n" + e.toString());
     }
   }
 }
Esempio n. 14
0
  /**
   * Start saving the logcat logs to a file in the external storage. The app needs to obtain the
   * read/write permission to the external storage before calling this method. If not, this method
   * will do nothing.
   */
  public static void startSavingLogs(Context context, String appName) {
    if (isSavingLogs) {
      return;
    }

    // Stop if we don't have enough storage access permission.
    if (!Utils.hasExternalStoragePermission(context)) {
      return;
    }

    File dir = Utils.getLogDirectory();

    Log.i(TAG, "Logcat logs are saved at: " + dir.getAbsolutePath());

    String startTime = Utils.getTimeString();
    String deviceId = DeviceInfoFactory.getDeviceId(context);

    deleteOldLogs(dir, appName, deviceId);

    File logcatFile =
        new File(dir, String.format("%s-%s.log", getLogPrefix(appName, deviceId), startTime));

    try {
      // Clear the previous logs
      Runtime.getRuntime().exec("logcat -c");
      Runtime.getRuntime()
          .exec(String.format("logcat -v time -f %s", logcatFile.getCanonicalPath()));
      isSavingLogs = true;
    } catch (IOException e) {
      Log.e(TAG, "Could not start writing the logcat file.", e);
    }
  }
 private String getSDKProperties(String javaPath, String path) throws IOException {
   Runtime runtime = Runtime.getRuntime();
   try {
     String[] command = new String[5];
     command[0] = javaPath;
     command[1] = "-classpath"; // NOI18N
     command[2] =
         InstalledFileLocator.getDefault()
             .locate(
                 "modules/ext/org-netbeans-modules-visage-platform-probe.jar",
                 "org.netbeans.modules.visage.platform",
                 false)
             .getAbsolutePath(); // NOI18N
     command[3] = "org.netbeans.modules.visage.platform.wizard.SDKProbe"; // NOI18N
     command[4] = path;
     final Process process = runtime.exec(command);
     // PENDING -- this may be better done by using ExecEngine, since
     // it produces a cancellable task.
     process.waitFor();
     int exitValue = process.exitValue();
     if (exitValue != 0) throw new IOException();
     return command[2];
   } catch (InterruptedException ex) {
     IOException e = new IOException();
     ErrorManager.getDefault().annotate(e, ex);
     throw e;
   }
 }
Esempio n. 16
0
  public static void main(String[] args) {
    int i = 0, j;
    String arg;
    char flag;
    boolean vflag = false;
    String outputfile = "";
    int d = -1, t = -1, b = -1, l = -1, r = -1;

    while (i < args.length) {

      if (args[i].startsWith("-")) {
        arg = args[i++];
        for (j = 1; j < arg.length(); j++) {
          flag = arg.charAt(j);
          switch (flag) {
            case 'd':
              d = Integer.valueOf(args[i++]);
              break;
            case 't':
              t = Integer.valueOf(args[i++]);
              break;
            case 'b':
              b = Integer.valueOf(args[i++]);
              break;
            case 'l':
              l = Integer.valueOf(args[i++]);
              break;
            case 'r':
              r = Integer.valueOf(args[i++]);
              break;
            default:
              System.err.println("ParseCmdLine: illegal option " + flag);
              break;
          }
        }
      }
    }
    if (d < 0 || t < 0 || l < 0 || r < 0) {
      System.out.println("Invalid number of arguements.");
      System.out.println("Proper usage: java Tpdahp.Demo -d # -l # -r # -t # -b #");
    } else {

      long start = System.currentTimeMillis();

      // Instanciate and calls the Simulator
      DiffusionSimulator simulator = new DiffusionSimulator(d, t, b, l, r);
      simulator.simulate();

      long end = System.currentTimeMillis();
      simulator.printResults();

      Runtime runtime = Runtime.getRuntime();
      long memory = runtime.totalMemory() - runtime.freeMemory();
      System.out.println(String.format("\n\nPerformance Summary: "));
      System.out.println(String.format(" - Time Taken: %dms", end - start));
      System.out.println(String.format(" - Memory Used: %d bytes", memory));
      System.out.println(
          String.format(" - Number of iteration: %d", simulator.getNumberOfIterations()));
    }
  }
Esempio n. 17
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = "";
    java.util.Enumeration<String> headers = request.getHeaders("foo");
    if (headers.hasMoreElements()) {
      param = headers.nextElement(); // just grab first element
    }

    String bar = doSomething(param);

    String cmd = org.owasp.benchmark.helpers.Utils.getOSCommandString("echo") + bar;

    String[] argsEnv = {"Foo=bar"};
    Runtime r = Runtime.getRuntime();

    try {
      Process p = r.exec(cmd, argsEnv);
      org.owasp.benchmark.helpers.Utils.printOSCommandResults(p);
    } catch (IOException e) {
      System.out.println("Problem executing cmdi - TestCase");
      throw new ServletException(e);
    }
  } // end doPost
  /**
   * 返回服务系统信息
   *
   * @throws Exception
   */
  public static ServerStatus getServerStatus() throws Exception {
    ServerStatus status = new ServerStatus();
    status.setServerTime(DateFormatUtils.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss"));
    status.setServerName(System.getenv().get("COMPUTERNAME"));

    Runtime rt = Runtime.getRuntime();
    // status.setIp(InetAddress.getLocalHost().getHostAddress());
    status.setJvmTotalMem(rt.totalMemory() / (1024 * 1024));
    status.setJvmFreeMem(rt.freeMemory() / (1024 * 1024));
    status.setJvmMaxMem(rt.maxMemory() / (1024 * 1024));
    Properties props = System.getProperties();
    status.setServerOs(
        props.getProperty("os.name")
            + " "
            + props.getProperty("os.arch")
            + " "
            + props.getProperty("os.version"));
    status.setJavaHome(props.getProperty("java.home"));
    status.setJavaVersion(props.getProperty("java.version"));
    status.setJavaTmpPath(props.getProperty("java.io.tmpdir"));

    Sigar sigar = new Sigar();
    getServerCpuInfo(sigar, status);
    getServerDiskInfo(sigar, status);
    getServerMemoryInfo(sigar, status);

    return status;
  }
Esempio n. 19
0
/**
 * The Class <code>ALNSGlobalParameters</code> defines global parameters used in the {@link
 * AdaptiveLargeNeighborhoodSearch}
 *
 * <p>Creation date: May 13, 2011 - 10:36:16 AM.
 *
 * @author Victor Pillac, <a href="http://uniandes.edu.co">Universidad de Los Andes</a>-<a
 *     href="http://copa.uniandes.edu.co">Copa</a> <a href="http://www.emn.fr">Ecole des Mines de
 *     Nantes</a>-<a href="http://www.irccyn.ec-nantes.fr/irccyn/d/en/equipes/Slp">SLP</a>
 * @version 1.0
 */
public class ALNSGlobalParameters extends GlobalParameters {

  /**
   * The range for the value for the size of {@link
   * IDestroy#destroy(vroom.common.utilities.optimization.ISolution,
   * vroom.common.utilities.optimization.IParameters, int) destroy} (by convention in [0,1]).
   */
  @RequiredParameter
  public static final ParameterKey<double[]> DESTROY_SIZE_RANGE =
      new ParameterKey<double[]>("DESTROY_SIZE_RANGE", double[].class, new double[] {0.1, 0.5});

  /** The type of {@linkplain IPALNSSolutionPool solution pool} */
  @SuppressWarnings("rawtypes")
  public static final ClassParameterKey<IPALNSSolutionPool> PALNS_POOL =
      new ClassParameterKey<IPALNSSolutionPool>(
          "PALNS_POOL", IPALNSSolutionPool.class, SimpleSolutionPool.class);

  /** The number of iterations to be performed in parallel */
  public static final ParameterKey<Integer> PALNS_POOL_SIZE =
      new ParameterKey<Integer>(
          "PALNS_POOL_SIZE", Integer.class, Runtime.getRuntime().availableProcessors());

  /** The number of Threads to use for parallelization */
  public static final ParameterKey<Integer> PALNS_THREAD_COUNT =
      new ParameterKey<Integer>(
          "PALNS_THREAD_COUNT", Integer.class, Runtime.getRuntime().availableProcessors());

  /** The number of iterations to be performed in parallel */
  public static final ParameterKey<Integer> PALNS_IT_P =
      new ParameterKey<Integer>("PALNS_IT_P", Integer.class, 100);

  @SuppressWarnings("rawtypes")
  public static final ClassParameterKey<IDistance> DIVERSITY_METRIC =
      new ClassParameterKey<IDistance>("DIVERSITY_METRIC", IDistance.class);
}
Esempio n. 20
0
  public boolean execute(GPLoadMeta meta, boolean wait) throws KettleException {
    Runtime rt = Runtime.getRuntime();

    try {
      gploadProcess = rt.exec(createCommandLine(meta, true));
      // any error message?
      StreamLogger errorLogger = new StreamLogger(gploadProcess.getErrorStream(), "ERROR");

      // any output?
      StreamLogger outputLogger = new StreamLogger(gploadProcess.getInputStream(), "OUTPUT");

      // kick them off
      errorLogger.start();
      outputLogger.start();

      if (wait) {
        // any error???
        int exitVal = gploadProcess.waitFor();
        logBasic(
            BaseMessages.getString(
                PKG, "GPLoad.Log.ExitValuePsqlPath", "" + exitVal)); // $NON-NLS-1$
      }
    } catch (Exception ex) {
      // Don't throw the message upwards, the message contains the password.
      throw new KettleException("Error while executing \'" + createCommandLine(meta, false) + "\'");
    }

    return true;
  }
Esempio n. 21
0
  public static void main(String args[]) {
    Runtime r = Runtime.getRuntime();
    long mem1, mem2;
    Integer someints[] = new Integer[1000];

    System.out.println("Total memory is: " + r.totalMemory());
    mem1 = r.freeMemory();
    System.out.println("Initial free memory: " + mem1);
    r.gc();
    mem1 = r.freeMemory();
    System.out.println("Free memory after garbage collection: " + mem1);

    for (int i = 0; i < 1000; i++) someints[i] = new Integer(i); // allocate integers

    mem2 = r.freeMemory();
    System.out.println("Free memory after allocation: " + mem2);
    System.out.println("Memory used by allocation: " + (mem1 - mem2));

    // discard Integers
    for (int i = 0; i < 1000; i++) someints[i] = null;

    mem2 = r.freeMemory();
    System.out.println("Free memory after discarding Integers: " + mem2);

    r.gc(); // request garbage collection

    mem2 = r.freeMemory();
    System.out.println("Free memory after collecting discarded Integers: " + mem2);
  }
  public void speak(String txt) {
    try {
      Runtime rtime = Runtime.getRuntime();

      // start unix shell
      Process child = rtime.exec("/bin/sh");
      // or "/bin/sh set -t" to auto-exit after 1 command

      BufferedWriter outCommand =
          new BufferedWriter(new OutputStreamWriter(child.getOutputStream()));

      // run a command
      outCommand.write("echo '" + txt + "' | festival --tts\n");
      outCommand.flush();

      // exit the unix shell
      outCommand.write("exit" + "\n");
      outCommand.flush();

      int wait = child.waitFor();
      System.out.println("exit code: " + wait);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 23
0
 /** Cleans garbage (Tilecleanup) */
 public synchronized void garbageCollect() {
   long startTime = getTime();
   int curMemory =
       (int) (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1000;
   for (int i = 0; i < Instance.getWorld().tiles.length; i++) {
     for (int in = 0; in < Instance.getWorld().tiles[i].length; in++) {
       ActiveTile tile = Instance.getWorld().tiles[i][in];
       if (tile != null) {
         if (!tile.hasGameObject() && !tile.hasItems() && !tile.hasNpcs() && !tile.hasPlayers()) {
           Instance.getWorld().tiles[i][in] = null;
         }
       }
     }
   }
   Runtime.getRuntime().gc();
   int newMemory =
       (int) (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1000;
   Logger.println("GARBAGE COLLECT | Executing Memory Cleanup");
   Logger.println(
       "GARBAGE COLLECT | Memory before: "
           + curMemory
           + "kb"
           + " Memory after: "
           + newMemory
           + " (Freed: "
           + (curMemory - newMemory)
           + "kb)");
   Logger.println("GARBAGE COLLECT | Cleanup took " + (updateTime() - startTime) + "ms");
 }
Esempio n. 24
0
 // Constructor
 public FittingCapacities(
     int[] dimensions,
     MatrixND<Double> weightsFS,
     MatrixND<Double> quantitiesOS,
     MatrixND<Double> proportionsFO,
     MatrixND<Double> maxCapacityF) {
   this.dimensions = dimensions;
   os = new TotalFittingControl1D(quantitiesOS);
   MatrixND<Double> quantitiesFS = new Matrix2DImpl(new int[] {dimensions[0], dimensions[2]});
   for (int s = 0; s < dimensions[2]; s++) {
     double totalStopQuantity = 0;
     for (int o = 0; o < dimensions[1]; o++)
       totalStopQuantity += quantitiesOS.getElement(new int[] {o, s});
     for (int f = 0; f < dimensions[0]; f++)
       quantitiesFS.setElement(
           new int[] {f, s}, weightsFS.getElement(new int[] {f, s}) * totalStopQuantity);
   }
   fs = new TotalFittingControl1D(quantitiesFS);
   fo = new ProportionFittingControlND(proportionsFO, new int[] {2});
   f = new MaxFittingControlND(maxCapacityF);
   System.out.println(
       "Heap memory: "
           + Runtime.getRuntime().freeMemory()
           + " of "
           + Runtime.getRuntime().maxMemory());
 }
Esempio n. 25
0
  @Override
  public void mousePressed(final MouseEvent e) {
    Performance.gc(3);
    repaint();

    final Runtime rt = Runtime.getRuntime();
    final long max = rt.maxMemory();
    final long total = rt.totalMemory();
    final long used = total - rt.freeMemory();

    final String inf =
        TOTAL_MEM_C
            + Performance.format(max, true)
            + NL
            + RESERVED_MEM_C
            + Performance.format(total, true)
            + NL
            + MEMUSED_C
            + Performance.format(used, true)
            + NL
            + NL
            + H_USED_MEM;

    BaseXDialog.info(gui, inf);
  }
Esempio n. 26
0
  public void setCaptImage(Uri ur, int src) {
    BitMapManipulation bm = new BitMapManipulation();
    // String path;
    switch (imgIdG) {
      case 0:
        captView[0].findViewById(R.id.captBtn1).setVisibility(View.GONE);
        captImg[0].setVisibility(View.VISIBLE);
        captImg[0].setLongClickable(true);
        captImg[0].setOnTouchListener(this);

        if (captImg[0] != null) {
          captImg[0].destroyDrawingCache();
        }
        System.gc();
        Runtime.getRuntime().gc();
        bmp[0] = bm.createBMP(src, ur.toString(), captImg[0].getWidth(), captImg[0].getHeight());
        resetView(captImg[0]);
        captImg[0].setImageBitmap(bmp[0]);
        captImg[0].invalidate();

        Toast.makeText(this, "id: " + imgIdG, Toast.LENGTH_SHORT).show();
        break;
      case 1:
        if (MAX_COL == 1) {
          captView[1].findViewById(R.id.captBtn1).setVisibility(View.GONE);
          captImg[1].setVisibility(View.VISIBLE);
          captImg[1].setOnTouchListener(this);
          bmp[1] = bm.createBMP(src, ur.toString(), captImg[0].getWidth(), captImg[0].getHeight());
          resetView(captImg[1]);
          captImg[1].setImageBitmap(bmp[1]);
        } else {
          captView[0].findViewById(R.id.captBtn2).setVisibility(View.GONE);
          captImg[1].setVisibility(View.VISIBLE);
          captImg[1].setOnTouchListener(this);
          bmp[1] = bm.createBMP(src, ur.toString(), captImg[0].getWidth(), captImg[0].getHeight());
          resetView(captImg[1]);
          captImg[1].setImageBitmap(bmp[1]);
        }
        Toast.makeText(this, "id: " + imgIdG, Toast.LENGTH_SHORT).show();
        break;
      case 2:
        captView[1].findViewById(R.id.captBtn1).setVisibility(View.GONE);
        captImg[2].setVisibility(View.VISIBLE);
        captImg[2].setOnTouchListener(this);
        bmp[2] = bm.createBMP(src, ur.toString(), captImg[2].getWidth(), captImg[2].getHeight());
        resetView(captImg[2]);
        captImg[2].setImageBitmap(bmp[2]);
        break;
      case 3:
        captView[1].findViewById(R.id.captBtn2).setVisibility(View.GONE);
        captImg[3].setVisibility(View.VISIBLE);
        captImg[3].setOnTouchListener(this);
        bmp[3] = bm.createBMP(src, ur.toString(), captImg[0].getWidth(), captImg[0].getHeight());
        resetView(captImg[3]);
        captImg[3].setImageBitmap(bmp[3]);
        break;
    }
    System.gc();
    Runtime.getRuntime().gc();
  }
Esempio n. 27
0
  public static String getStat() {
    StringBuilder stat = new StringBuilder();
    stat.append("Available processors (cores): ")
        .append(Runtime.getRuntime().availableProcessors());

    /* Total amount of free memory available to the JVM */
    stat.append("\nFree memory (bytes): ").append(Runtime.getRuntime().freeMemory());

    /* This will return Long.MAX_VALUE if there is no preset limit */
    long maxMemory = Runtime.getRuntime().maxMemory();
    /* Maximum amount of memory the JVM will attempt to use */
    stat.append("\nMaximum memory (bytes): ")
        .append(maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory);

    /* Total memory currently in use by the JVM */
    stat.append("\nTotal memory (bytes): ").append(Runtime.getRuntime().totalMemory());

    /* Get a list of all filesystem roots on this system */
    File[] roots = File.listRoots();

    /* For each filesystem root, print some info */
    for (File root : roots) {
      stat.append("\nFile system root: ").append(root.getAbsolutePath());
      stat.append("\nTotal space (bytes): ").append(root.getTotalSpace());
      stat.append("\nFree space (bytes): ").append(root.getFreeSpace());
      stat.append("\nUsable space (bytes): ").append(root.getUsableSpace());
    }

    return stat.toString();
  }
  private void logStats(MavenSession session) {
    logger.info(chars('-', LINE_LENGTH));

    Date finish = new Date();

    long time = finish.getTime() - session.getRequest().getStartTime().getTime();

    String wallClock = session.getRequest().isThreadConfigurationPresent() ? " (Wall Clock)" : "";

    logger.info("Total time: " + getFormattedTime(time) + wallClock);

    logger.info("Finished at: " + finish);

    System.gc();

    Runtime r = Runtime.getRuntime();

    long MB = 1024 * 1024;

    logger.info(
        "Final Memory: "
            + (r.totalMemory() - r.freeMemory()) / MB
            + "M/"
            + r.totalMemory() / MB
            + "M");
  }
Esempio n. 29
0
  /** this void method runs the command created in the constructor. */
  public void runTesseract() {
    LOGGER.info(
        "Trying to run command: "
            + command[0]
            + " "
            + command[1]
            + " "
            + command[2]
            + " "
            + command[3]
            + " "
            + command[4]);
    System.out.println("Trying to run command: " + Arrays.toString(command));
    try {
      Runtime rt = Runtime.getRuntime();
      Process pr = rt.exec(command);
      BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
      String line;
      while ((line = input.readLine()) != null) {
        System.out.println(line);
      }

      int exitVal = pr.waitFor();
      System.out.println("Exited with error code " + exitVal);
    } catch (Exception e) {
      System.out.println(e.toString());
      e.printStackTrace();
    }
  }
Esempio n. 30
0
 public void getJvmInfo() {
   Map<String, String> result = new HashMap<String, String>();
   // 内存
   Runtime runtime = Runtime.getRuntime();
   double max = runtime.maxMemory() * 1.0 / 1024.0 / 1024.0;
   result.put("maxMemory", max + "");
   double total = runtime.totalMemory() * 1.0 / 1024.0 / 1024.0;
   result.put("totalMemory", total + "");
   double freeMemory = runtime.freeMemory() * 1.0 / 1024.0 / 1024.0;
   result.put("freeMemory", freeMemory + "");
   // 线程
   ThreadGroup group = Thread.currentThread().getThreadGroup();
   ThreadGroup topGroup = group;
   // 遍历线程组树,获取根线程组
   while (group != null) {
     topGroup = group;
     group = group.getParent();
   }
   // 激活的线程数加倍
   int estimatedSize = topGroup.activeCount() * 2;
   Thread[] slackList = new Thread[estimatedSize];
   // 获取根线程组的所有线程
   int actualSize = topGroup.enumerate(slackList);
   // copy into a list that is the exact size
   Thread[] list = new Thread[actualSize];
   System.arraycopy(slackList, 0, list, 0, actualSize);
   for (int i = 0; i < list.length; i++) {
     // System.out.println(list[i].getName());
   }
   result.put("thread", list.length + "");
   String resultStr = JsonUtil.map2Json(result);
   this.print(resultStr);
 }