/**
  * Parses a property list from an InputStream. It can either be in XML or binary format.
  *
  * @param is The InputStream delivering the property list data
  * @return The root object of the property list
  * @throws Exception If an error occurred while parsing.
  */
 public static NSObject parse(InputStream is) throws Exception {
   if (is.markSupported()) {
     is.mark(10);
     byte[] magic = new byte[8];
     is.read(magic);
     is.reset();
     String magic_string = new String(magic);
     if (magic_string.startsWith("bplist00")) {
       return BinaryPropertyListParser.parse(is);
     } else if (magic_string.startsWith("<?xml")) {
       return XMLPropertyListParser.parse(is);
     } else {
       throw new UnsupportedOperationException(
           "The given data is neither a binary nor a XML property list. ASCII property lists are not supported.");
     }
   } else {
     if (is.available() > Runtime.getRuntime().freeMemory()) {
       throw new Exception(
           "To little heap space available! Wanted to read "
               + is.available()
               + " bytes, but only "
               + Runtime.getRuntime().freeMemory()
               + " are available.");
     }
     byte[] buf = new byte[is.available()];
     is.read(buf);
     is.close();
     return parse(buf);
   }
 }
  /**
   * this function is called, when a new thread starts if this thread is the thread of getInstance,
   * then this is the shutdown hook and we save all data and disconnect all clients. after this
   * thread ends, the server will completely exit if this is not the thread of getInstance, then
   * this is a countdown thread. we start the countdown, and when we finished it, and it was not
   * aborted, we tell the shutdown-hook why we call exit, and then call exit when the exit status of
   * the server is 1, startServer.sh / startServer.bat will restart the server.
   */
  @Override
  public void run() {
    try {
      NetConnector.getInstance().shutdown();
    } catch (Throwable t) {
      log.error("Can't shutdown NetConnector", t);
    }
    /* Shuting down DB connections */
    try {
      DatabaseFactory.shutdown();
    } catch (Throwable t) {
      log.error("Can't shutdown DatabaseFactory", t);
    }

    // shutdown cron service prior to threadpool shutdown
    CronService.getInstance().shutdown();

    /* Shuting down threadpools */
    try {
      ThreadPoolManager.getInstance().shutdown();
    } catch (Throwable t) {
      log.error("Can't shutdown ThreadPoolManager", t);
    }

    // Do system exit
    if (restartOnly) {
      Runtime.getRuntime().halt(ExitCode.CODE_RESTART);
    } else {
      Runtime.getRuntime().halt(ExitCode.CODE_NORMAL);
    }
  }
Beispiel #3
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!");
      }
    }
  }
 /** 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");
 }
  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();
  }
Beispiel #6
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();
  }
Beispiel #7
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);
    }
  }
 public void addMemoryStatsToSnooper() {
   addData("memory_total", Long.valueOf(Runtime.getRuntime().totalMemory()));
   addData("memory_max", Long.valueOf(Runtime.getRuntime().maxMemory()));
   addData("memory_free", Long.valueOf(Runtime.getRuntime().freeMemory()));
   addData("cpu_cores", Integer.valueOf(Runtime.getRuntime().availableProcessors()));
   playerStatsCollector.addServerStatsToSnooper(this);
 }
  @Override
  public void run() {
    if (!isRunning) {
      isRunning = true;
      long s = System.currentTimeMillis();
      System.out.println(
          new Date()
              + "--start--将版权音乐导出,搜索结果,保存结果到memcached中,供搜索使用start,总内存:"
              + Runtime.getRuntime().totalMemory()
              + ",剩余内存:"
              + Runtime.getRuntime().freeMemory());

      try {
        new VideoMusicRecommend().cacheMusic();
      } catch (Exception e) {
        System.out.println("加载音乐错误:" + e.getMessage());
      }

      System.out.println(
          new Date()
              + "--end--将版权音乐导出,搜索结果,保存结果到memcached中,供搜索使用end,总内存:"
              + Runtime.getRuntime().totalMemory()
              + ",剩余内存:"
              + Runtime.getRuntime().freeMemory()
              + ",占用时间:"
              + (System.currentTimeMillis() - s));
      isRunning = false;
    } else {
      log.warn("上一次任务执行还未结束..."); // 上一次任务执行还未结束
    }
  }
  /**
   * Inspect the log directory to recover any log file without
   * an active region server.
   */
  void splitLogAfterStartup() {
    boolean retrySplitting = !conf.getBoolean("hbase.hlog.split.skip.errors",
        HLog.SPLIT_SKIP_ERRORS_DEFAULT);
    Path logsDirPath = new Path(this.rootdir, HConstants.HREGION_LOGDIR_NAME);
    do {
      if (master.isStopped()) {
        LOG.warn("Master stopped while splitting logs");
        break;
      }
      List<ServerName> serverNames = new ArrayList<ServerName>();
      try {
        if (!this.fs.exists(logsDirPath)) return;
        FileStatus[] logFolders = FSUtils.listStatus(this.fs, logsDirPath, null);
        // Get online servers after getting log folders to avoid log folder deletion of newly
        // checked in region servers . see HBASE-5916
        Set<ServerName> onlineServers = ((HMaster) master).getServerManager().getOnlineServers()
            .keySet();

        if (logFolders == null || logFolders.length == 0) {
          LOG.debug("No log files to split, proceeding...");
          return;
        }
        for (FileStatus status : logFolders) {
          String sn = status.getPath().getName();
          // truncate splitting suffix if present (for ServerName parsing)
          if (sn.endsWith(HLog.SPLITTING_EXT)) {
            sn = sn.substring(0, sn.length() - HLog.SPLITTING_EXT.length());
          }
          ServerName serverName = ServerName.parseServerName(sn);
          if (!onlineServers.contains(serverName)) {
            LOG.info("Log folder " + status.getPath() + " doesn't belong "
                + "to a known region server, splitting");
            serverNames.add(serverName);
          } else {
            LOG.info("Log folder " + status.getPath()
                + " belongs to an existing region server");
          }
        }
        splitLog(serverNames);
        retrySplitting = false;
      } catch (IOException ioe) {
        LOG.warn("Failed splitting of " + serverNames, ioe);
        if (!checkFileSystem()) {
          LOG.warn("Bad Filesystem, exiting");
          Runtime.getRuntime().halt(1);
        }
        try {
          if (retrySplitting) {
            Thread.sleep(conf.getInt(
              "hbase.hlog.split.failure.retry.interval", 30 * 1000));
          }
        } catch (InterruptedException e) {
          LOG.warn("Interrupted, aborting since cannot return w/o splitting");
          Thread.currentThread().interrupt();
          retrySplitting = false;
          Runtime.getRuntime().halt(1);
        }
      }
    } while (retrySplitting);
  }
  public static boolean tryOpenURL(URL theLink) {
    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[] {theLink});
        return true;
      } else if (osName.startsWith("Windows")) {
        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + theLink);
        return true;
      } else {
        // assume Unix or Linux
        String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"};
        String browser = null;
        for (int count = 0; count < browsers.length && browser == null; count++)
          if (Runtime.getRuntime().exec(new String[] {"which", browsers[count]}).waitFor() == 0)
            browser = browsers[count];
        if (browser == null) return false;
        else {
          Runtime.getRuntime().exec(new String[] {browser, theLink.toString()});
          return true;
        }
      }
    } catch (Exception e) {
      e.toString();
    }

    return false;
  }
 public void openURL(String url) {
   try {
     if (DetectOS.getOS().startsWith("windows")) {
       Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
     } else if (DetectOS.getOS().equals("mac")) {
       Runtime.getRuntime().exec("open " + url);
     } else {
       String[] browsers = {
         "firefox", "iceweasel", "opera", "konqueror", "epiphany", "mozilla", "netscape", "safari"
       };
       boolean browserStarted = false;
       for (int index = 0; index < browsers.length; index++) {
         try {
           Runtime.getRuntime().exec(new String[] {browsers[index], url});
           browserStarted = true;
           break;
         } catch (Exception e) {
           // try next browser
         }
       }
       if (!browserStarted) {
         JOptionPane.showMessageDialog(
             null, "No browser found on your path, please open it yourself.");
       }
     }
   } catch (Exception e) {
     JOptionPane.showMessageDialog(null, "Error in opening browser:\n" + e.getLocalizedMessage());
   }
 }
Beispiel #13
0
 private static boolean execute(String cmd, String dir) {
   if (PRINT_ERRORS) {
     System.out.println("EXECUTING " + cmd + " IN " + dir);
   }
   try {
     Process p = null;
     if (dir == null) {
       p = Runtime.getRuntime().exec(cmd);
     } else {
       p = Runtime.getRuntime().exec(cmd, null, new File(dir));
     }
     if (PRINT_ERRORS) {
       InputStream stderr = p.getErrorStream();
       InputStreamReader isr = new InputStreamReader(stderr);
       BufferedReader br = new BufferedReader(isr);
       String line = null;
       while ((line = br.readLine()) != null) {
         Output.writeln(line);
       }
     }
     p.waitFor();
     return true;
   } catch (IOException e) {
     e.printStackTrace();
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
   return false;
 }
 private void storeMemory() {
   if (store.isMonitoring("memoryUsed")) {
     System.gc();
     long memoryUsed = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
     store.setLongMax("memoryUsed", memoryUsed);
   }
 }
 /** Print a Gibbs sample debug message */
 protected void GibbsSampleDebugMessage(int t) {
   if (t == 0 && gibbs_sample_num % 100 == 0) {
     String message =
         "Sampling M_"
             + (t + 1)
             + "/"
             + num_trees
             + " iter "
             + gibbs_sample_num
             + "/"
             + num_gibbs_total_iterations;
     if (num_cores > 1) {
       message += "  thread: " + (threadNum + 1);
     }
     if (ON_WINDOWS) {
       long mem_used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
       long max_mem = Runtime.getRuntime().maxMemory();
       message +=
           "  mem: "
               + TreeIllustration.one_digit_format.format(mem_used / 1000000.0)
               + "/"
               + TreeIllustration.one_digit_format.format(max_mem / 1000000.0)
               + "MB";
     }
     System.out.println(message);
   }
 }
Beispiel #16
0
  /**
   * Implements the other cross-platform headache of opening a folder in the machine's native file
   * browser.
   */
  public static void openFolder(File file) {
    try {
      String folder = file.getAbsolutePath();

      if (Base.isWindows()) {
        // doesn't work
        // Runtime.getRuntime().exec("cmd /c \"" + folder + "\"");

        // works fine on winxp, prolly win2k as well
        Runtime.getRuntime().exec("explorer \"" + folder + "\"");

        // not tested
        // Runtime.getRuntime().exec("start explorer \"" + folder +
        // "\"");

      } else if (Base.isMacOS()) {
        openURL(folder); // handles char replacement, etc

      } else if (Base.isLinux()) {
        String launcher = preferences.get("launcher.linux", null);
        if (launcher != null) {
          Runtime.getRuntime().exec(new String[] {launcher, folder});
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /**
   * @param server The server this connector will be added to. Must not be null.
   * @param executor An executor for this connector or null to use the servers executor
   * @param scheduler A scheduler for this connector or null to either a {@link Scheduler} set as a
   *     server bean or if none set, then a new {@link TimerScheduler} instance.
   * @param pool A buffer pool for this connector or null to either a {@link ByteBufferPool} set as
   *     a server bean or none set, the new {@link ArrayByteBufferPool} instance.
   * @param acceptors the number of acceptor threads to use, or 0 for a default value.
   * @param factories The Connection Factories to use.
   */
  public AbstractConnector(
      Server server,
      Executor executor,
      Scheduler scheduler,
      ByteBufferPool pool,
      int acceptors,
      ConnectionFactory... factories) {
    _server = server;
    _executor = executor != null ? executor : _server.getThreadPool();
    if (scheduler == null) scheduler = _server.getBean(Scheduler.class);
    _scheduler = scheduler != null ? scheduler : new TimerScheduler();
    if (pool == null) pool = _server.getBean(ByteBufferPool.class);
    _byteBufferPool = pool != null ? pool : new ArrayByteBufferPool();

    addBean(_server, false);
    addBean(_executor);
    if (executor == null) unmanage(_executor); // inherited from server
    addBean(_scheduler);
    addBean(_byteBufferPool);

    for (ConnectionFactory factory : factories) addConnectionFactory(factory);

    if (acceptors <= 0) acceptors = Math.max(1, (Runtime.getRuntime().availableProcessors()) / 2);
    if (acceptors > 2 * Runtime.getRuntime().availableProcessors())
      LOG.warn("Acceptors should be <= 2*availableProcessors: " + this);
    _acceptors = new Thread[acceptors];
  }
Beispiel #18
0
  /**
   * @param args
   * @throws IOException
   */
  public static void main(String[] args) throws IOException {

    File file = new File("server/server.log");

    if (!file.exists()) {
      System.out.println("ERROR: Could not find server/server.log!!!");
      System.exit(1);
    }

    long lastModified = file.lastModified();
    long currentTime = System.currentTimeMillis();

    System.out.println("Last modified: " + Long.toString(lastModified));
    System.out.println("Current time: " + Long.toString(currentTime));

    // 900000 ms = 15 minutes
    if (currentTime - lastModified > 300000) {
      // It's been 15 minutes, something went wrong.
      Runtime.getRuntime().exec("killall java");
      Runtime.getRuntime().exec("server/start");
      System.out.println("I had to kill the process...");
      System.exit(1);
    } else {
      // Nothing wrong.
      System.out.println("Server appears to be up.");
      System.exit(0);
    }
  }
  public static void openURL(String url) {

    try {
      // Since Java6 this is a much easier method to open the browser
      if (Desktop.isDesktopSupported()) {
        Desktop desktop = Desktop.getDesktop();
        desktop.browse(new URI(url));
      }

      // Only if desktop is not supported we try the old main specific code
      else {
        if (SystemInfo.OS == Os.MAC) {
          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 (SystemInfo.OS == Os.WINDOWS)
          Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
        else { // assume Unix or Linux
          String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"};
          String browser = null;
          for (int count = 0; (count < browsers.length) && (browser == null); count++)
            if (Runtime.getRuntime().exec(new String[] {"which", browsers[count]}).waitFor() == 0)
              browser = browsers[count];
          if (browser == null) throw new Exception("Could not find web browser");
          else Runtime.getRuntime().exec(new String[] {browser, url});
        }
      }
    } catch (Exception e) {
      log.error("Error at opening the URL.", e);
    }
  }
Beispiel #20
0
  public static String getArchName() throws Exception {
    if (archName == null) {
      archName = "lin";

      // bits
      Process process = Runtime.getRuntime().exec("uname -m");
      process.waitFor();
      if (process.exitValue() != 0) throw new Exception("Error arch");
      BufferedReader inStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
      String arch = inStream.readLine();
      if (arch.equals("i686")) archName += "32";
      else archName += "64";
      process.destroy();

      // SSE
      process = Runtime.getRuntime().exec("cat /proc/cpuinfo");
      process.waitFor();
      if (process.exitValue() != 0) throw new Exception("Error /proc/cpuinfo");
      inStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
      String line, cpuinfo = "";
      while ((line = inStream.readLine()) != null) cpuinfo += line;

      String bestSSE = "sse";
      String[] sses = {"sse2", "sse3", "ssse3", "sse4", "avx"};
      for (int i = 0; i < sses.length; i++) {
        if (cpuinfo.indexOf(sses[i]) >= 0) bestSSE = sses[i];
      }
      archName += bestSSE;
      process.destroy();
    }
    return archName;
  }
 /**
  * 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());
     }
   }
 }
  public void update() {
    super.update();

    boolean enableDebug = Config.getInstance().isDebug();
    debugLine1.setVisible(enableDebug);
    debugLine2.setVisible(enableDebug);
    debugLine3.setVisible(enableDebug);
    debugLine4.setVisible(enableDebug);

    if (enableDebug) {
      CameraTargetSystem cameraTarget = CoreRegistry.get(CameraTargetSystem.class);
      double memoryUsage =
          ((double) Runtime.getRuntime().totalMemory() - (double) Runtime.getRuntime().freeMemory())
              / 1048576.0;
      Timer timer = CoreRegistry.get(Timer.class);
      debugLine1.setText(
          String.format(
              "fps: %.2f, mem usage: %.2f MB, total mem: %.2f, max mem: %.2f",
              timer.getFps(),
              memoryUsage,
              Runtime.getRuntime().totalMemory() / 1048576.0,
              Runtime.getRuntime().maxMemory() / 1048576.0));
      debugLine2.setText(String.format("%s", cameraTarget.toString()));
      debugLine3.setText(String.format("%s", CoreRegistry.get(WorldRenderer.class)));
      debugLine4.setText(
          String.format(
              "total vus: %s | active threads: %s",
              ChunkTessellator.getVertexArrayUpdateCount(),
              CoreRegistry.get(GameEngine.class).getActiveTaskCount()));
    }
  }
Beispiel #23
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());
 }
Beispiel #24
0
  public void testCopyFromNonReadableDirectory() throws Exception {
    // We can use source.setReadable(false) when we decide to use java 1.6
    if (!Platform.OS_WIN32.equals(Platform.getOS())) {
      URL resourceURL = Platform.getBundle(BUNDLE_ID).getEntry(RESOURCE_DIR);
      File resourceFolder = ResourceUtil.resourcePathToFile(resourceURL);

      File source = new File(resourceFolder, TEST_DIR);
      File dest = new File(tempDir, "tempdir");

      try {
        Runtime.getRuntime()
            .exec(new String[] {"chmod", "333", source.getAbsolutePath()})
            .waitFor(); //$NON-NLS-1$
        IOUtil.copyDirectory(source, dest);
        assertDirectory(source, dest);
        fail("Expected directories to not match");
      } catch (AssertionError ae) {
        // expected
      } finally {
        FileUtil.deleteRecursively(dest);
        Runtime.getRuntime()
            .exec(new String[] {"chmod", "755", source.getAbsolutePath()})
            .waitFor(); //$NON-NLS-1$
      }
    }
  }
Beispiel #25
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);
}
  public static boolean startAudioConfigTool() throws IOException {
    String os = System.getProperty("os.name", "<unk>");

    if (os.startsWith("Mac OS X")) {
      Runtime.getRuntime().exec("open /System/Library/PreferencePanes/Sound.prefPane/");
      return true;
    }

    if (os.startsWith("Windows XP")) {
      Runtime.getRuntime().exec("control mmsys.cpl,,2");
      return true;
    }

    if (os.startsWith("SunOS")) {
      String command = Utils.getProperty("com.sun.mc.softphone.media.AUDIO_CONTROL");
      if (command == null) {
        command = "/usr/dt/bin/sdtaudiocontrol";
      }
      Runtime.getRuntime().exec(command);
      return true;
    }

    if (os.startsWith("Linux")) {
      Runtime.getRuntime().exec("/usr/bin/gnome-volume-control");
      return true;
    }

    return false;
  }
Beispiel #27
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());
    }
  }
Beispiel #28
0
 public static final void printSystemInfo() {
   log.info(
       "JVM: "
           + System.getProperty("java.version")
           + "; "
           + System.getProperty("java.vm.vendor")
           + "; "
           + System.getProperty("java.vm.info")
           + "; "
           + System.getProperty("sun.arch.data.model")
           + "-bit");
   log.info(
       "OS: "
           + System.getProperty("os.name")
           + "; "
           + System.getProperty("os.version")
           + "; "
           + System.getProperty("os.arch"));
   log.info("CPU cores: " + Runtime.getRuntime().availableProcessors());
   log.info(
       "max. Memory: "
           + Runtime.getRuntime().maxMemory() / 1024.0 / 1024.0
           + "MB ("
           + Runtime.getRuntime().maxMemory()
           + "B)");
 }
Beispiel #29
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();
  }
Beispiel #30
0
  public static boolean openFolderAvailable() {
    if (Base.isWindows() || Base.isMacOS()) return true;

    if (Base.isLinux()) {
      // Assume that this is set to something valid
      if (preferences.get("launcher.linux", null) != null) {
        return true;
      }

      // Attempt to use gnome-open
      try {
        Process p = Runtime.getRuntime().exec(new String[] {"gnome-open"});
        p.waitFor();
        // Not installed will throw an IOException (JDK 1.4.2, Ubuntu
        // 7.04)
        preferences.put("launcher.linux", "gnome-open");
        return true;
      } catch (Exception e) {
      }

      // Attempt with kde-open
      try {
        Process p = Runtime.getRuntime().exec(new String[] {"kde-open"});
        p.waitFor();
        preferences.put("launcher.linux", "kde-open");
        return true;
      } catch (Exception e) {
      }
    }
    return false;
  }