Example #1
0
 /**
  * Get the current thread's context class loader which is set to the CommonClassLoader by
  * ApplicationServer
  *
  * @return the thread's context classloader if it exists; else the system class loader.
  */
 public static ClassLoader getClassLoader() {
   if (Thread.currentThread().getContextClassLoader() != null) {
     return Thread.currentThread().getContextClassLoader();
   } else {
     return ClassLoader.getSystemClassLoader();
   }
 }
  /** Stops Jetty. */
  private void stopJetty() {
    // Jetty does not really stop the server if port is busy.
    try {
      if (httpSrv != null) {
        // If server was successfully started, deregister ports.
        if (httpSrv.isStarted()) ctx.ports().deregisterPorts(getClass());

        // Record current interrupted status of calling thread.
        boolean interrupted = Thread.interrupted();

        try {
          httpSrv.stop();
        } finally {
          // Reset interrupted flag on calling thread.
          if (interrupted) Thread.currentThread().interrupt();
        }
      }
    } catch (InterruptedException ignored) {
      if (log.isDebugEnabled()) log.debug("Thread has been interrupted.");

      Thread.currentThread().interrupt();
    } catch (Exception e) {
      U.error(log, "Failed to stop Jetty HTTP server.", e);
    }
  }
 public String startIOSWebKit(String udid) throws IOException, InterruptedException {
   input = new FileInputStream("config.properties");
   prop.load(input);
   String serverPath = prop.getProperty("APPIUM_JS_PATH");
   File file = new File(serverPath);
   File curentPath = new File(file.getParent());
   System.out.println(curentPath);
   file = new File(curentPath + "/.." + "/..");
   String ios_web_lit_proxy_runner =
       file.getCanonicalPath() + "/bin/ios-webkit-debug-proxy-launcher.js";
   String webkitRunner =
       ios_web_lit_proxy_runner + " -c " + udid + ":" + deviceMap.get(udid) + " -d";
   System.out.println(webkitRunner);
   p1 = Runtime.getRuntime().exec(webkitRunner);
   System.out.println(
       "WebKit Proxy is started on device "
           + udid
           + " and with port number "
           + deviceMap.get(udid)
           + " and in thread "
           + Thread.currentThread().getId());
   // Add the Process ID to hashMap, which would be needed to kill IOSwebProxywhen required
   appiumServerProcess.put(Thread.currentThread().getId(), getPid(p1));
   System.out.println("Process ID's:" + appiumServerProcess);
   Thread.sleep(1000);
   return deviceMap.get(udid);
 }
 public JilterStatus eom(JilterEOMActions eomActions, Properties properties) {
   logger.debug("jilter eom()");
   try {
     bos.close(); // close stream
   } catch (IOException io) {
     logger.error("jilter failed to close io stream during eom", io);
   }
   byte[] messageBytes = bos.toByteArray();
   bos = new ByteArrayOutputStream();
   ByteArrayInputStream bis = new ByteArrayInputStream(messageBytes);
   try {
     logger.debug("jilter store callback execute");
     Config.getStopBlockFactory()
         .detectBlock("milter server", Thread.currentThread(), this, IDLE_TIMEOUT);
     callback.store(bis, host);
     logger.debug("jilter store callback finished");
   } catch (ArchiveException e) {
     logger.error("failed to store the message via milter", e);
     if (e.getRecoveryDirective() == ArchiveException.RecoveryDirective.REJECT) {
       logger.debug("jilter reject");
       return JilterStatus.SMFIS_REJECT;
     } else if (e.getRecoveryDirective() == ArchiveException.RecoveryDirective.RETRYLATER) {
       logger.debug("jilter temp fail");
       return JilterStatus.SMFIS_TEMPFAIL;
     }
   } catch (Throwable oome) {
     logger.error("failed to store message:" + oome.getMessage(), oome);
     return JilterStatus.SMFIS_REJECT;
   } finally {
     Config.getStopBlockFactory().endDetectBlock(Thread.currentThread());
   }
   return JilterStatus.SMFIS_CONTINUE;
 }
Example #5
0
 private void handleRequest() throws IOException {
   String line = in.readLine();
   if (line == null || line.length() == 0) {
     Log.warn(Thread.currentThread().getName() + ": ignoring empty request.");
     return;
   }
   if (handleCommand(line, out) == false) {
     out.println(
         Thread.currentThread().getName() + ": didn't understand request \"" + line + "\".");
   }
 }
Example #6
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.classes);

    setcc();

    Log.e("n", " CC Activity Started");
    try {
      Class<?> strictModeClass =
          Class.forName(
              "android.os.StrictMode", true, Thread.currentThread().getContextClassLoader());

      Class<?> threadPolicyClass =
          Class.forName(
              "android.os.StrictMode$ThreadPolicy",
              true,
              Thread.currentThread().getContextClassLoader());

      Class<?> threadPolicyBuilderClass =
          Class.forName(
              "android.os.StrictMode$ThreadPolicy$Builder",
              true,
              Thread.currentThread().getContextClassLoader());

      Method setThreadPolicyMethod =
          strictModeClass.getMethod("setThreadPolicy", threadPolicyClass);

      Method detectAllMethod = threadPolicyBuilderClass.getMethod("detectAll");
      Method penaltyMethod = threadPolicyBuilderClass.getMethod("penaltyLog");
      Method buildMethod = threadPolicyBuilderClass.getMethod("build");

      Constructor<?> threadPolicyBuilderConstructor = threadPolicyBuilderClass.getConstructor();
      Object threadPolicyBuilderObject = threadPolicyBuilderConstructor.newInstance();

      Object obj = detectAllMethod.invoke(threadPolicyBuilderObject);

      obj = penaltyMethod.invoke(obj);
      Object threadPolicyObject = buildMethod.invoke(obj);
      setThreadPolicyMethod.invoke(strictModeClass, threadPolicyObject);

    } catch (Exception ex) {
      Log.w("n", "Strict not enabled....");
    }

    final Button button = (Button) findViewById(R.id.ccbutton1);
    button.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            setcc();
          }
        });
  }
 public void destroyIOSWebKitProxy() throws IOException, InterruptedException {
   Thread.sleep(3000);
   if (appiumServerProcess.get(Thread.currentThread().getId()) != -1) {
     String process = "pgrep -P " + appiumServerProcess.get(Thread.currentThread().getId());
     Process p2 = Runtime.getRuntime().exec(process);
     BufferedReader r = new BufferedReader(new InputStreamReader(p2.getInputStream()));
     String command = "kill -9 " + r.readLine();
     System.out.println("Kills webkit proxy");
     System.out.println("******************" + command);
     Runtime.getRuntime().exec(command);
   }
 }
Example #8
0
  private final String readMSG(final int len)
      throws IOException, InterruptedException, MessagingNetworkException {
    if (len > 65000)
      ServerConnection.throwProtocolViolated("incoming message is too long: " + len + " bytes");
    byte[] b = new byte[len];
    InputStream is = getInputStream();
    synchronized (is) {
      long abortTime =
          System.currentTimeMillis() + 1000 * MSNMessagingNetwork.REQPARAM_SOCKET_TIMEOUT_SECONDS;
      int ofs = 0;

      while (ofs < len) {
        if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException();
        int read = is.read(b, ofs, len - ofs);
        if (read < 0) read = 0;
        ofs += read;
        if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out");
        /*
        if (len >= buffer.length)
        {
          ...
          return ...;
        }
        int pos = findCRLF();
        if (pos != -1) break;
        fill(is, abortTime);
        */
      }

      String msg = new String(b, 0, len, "UTF-8");
      return msg;
    }
  }
  /**
   * Handles a specific <tt>IOException</tt> which was thrown during the execution of {@link
   * #runInConnectThread(DTLSProtocol, TlsPeer, DatagramTransport)} while trying to establish a DTLS
   * connection
   *
   * @param ioe the <tt>IOException</tt> to handle
   * @param msg the human-readable message to log about the specified <tt>ioe</tt>
   * @param i the number of tries remaining after the current one
   * @return <tt>true</tt> if the specified <tt>ioe</tt> was successfully handled; <tt>false</tt>,
   *     otherwise
   */
  private boolean handleRunInConnectThreadException(IOException ioe, String msg, int i) {
    // SrtpControl.start(MediaType) starts its associated TransformEngine.
    // We will use that mediaType to signal the normal stop then as well
    // i.e. we will ignore exception after the procedure to stop this
    // PacketTransformer has begun.
    if (mediaType == null) return false;

    if (ioe instanceof TlsFatalAlert) {
      TlsFatalAlert tfa = (TlsFatalAlert) ioe;
      short alertDescription = tfa.getAlertDescription();

      if (alertDescription == AlertDescription.unexpected_message) {
        msg += " Received fatal unexpected message.";
        if (i == 0
            || !Thread.currentThread().equals(connectThread)
            || connector == null
            || mediaType == null) {
          msg += " Giving up after " + (CONNECT_TRIES - i) + " retries.";
        } else {
          msg += " Will retry.";
          logger.error(msg, ioe);

          return true;
        }
      } else {
        msg += " Received fatal alert " + alertDescription + ".";
      }
    }

    logger.error(msg, ioe);
    return false;
  }
Example #10
0
  public static void main(String[] args) {
    //        BuddyTree buddy;
    Properties prop;
    msn = new MSNMessenger("*****@*****.**", "marinescommand");

    msn.setInitialStatus(UserStatus.ONLINE);
    msn.addMsnListener(new MSNAdapter(msn));
    msn.login();

    System.out.println("Waiting for the response....");

    MsnTreeTest test = new MsnTreeTest();
    try {
      Thread.currentThread().sleep(6000);
    } catch (InterruptedException ex) {
    }
    if (msn.isLoggedIn()) {
      BuddyList bl = msn.getBuddyGroup().getForwardList();
      for (int i = 0; i < bl.size(); i++) {
        if (!bl.get(i).getStatus().equalsIgnoreCase(UserStatus.OFFLINE)) {
          System.out.println(bl.get(i).getLoginName());
        } else {
          System.out.println("User offline: " + bl.get(i).getLoginName());
        }
      }
    } else {
      System.out.println("terminator");
    }
  }
Example #11
0
  // Look through the http-import directory and process all
  // the files there, oldest first. Note that these are actual
  // files, not queue elements.
  private void processHttpImportFiles() {
    File importDirFile = new File(TrialConfig.basepath + TrialConfig.httpImportDir);
    if (!importDirFile.exists()) return;
    File[] files = importDirFile.listFiles();
    for (int k = 0; k < files.length; k++) {
      File next = files[k];
      if (next.canRead() && next.canWrite()) {
        FileObject fileObject = FileObject.getObject(next);
        if (preprocess(fileObject)) {
          process(fileObject);
          if (!queueForDatabase(fileObject))
            Log.message(Quarantine.file(next, processorServiceName));
          else Log.message(processorServiceName + ": Processing complete: " + next.getName());
        }

        // If the file still exists, then there must be a bug
        // somewhere; log it and quarantine the file so we don't
        // fall into an infinite loop.
        if (next.exists()) {
          logger.warn(
              "File still in queue after processing:\n" + next + "The file will be quarantined.");
          Log.message(Quarantine.file(next, processorServiceName));
        }
        Thread.currentThread().yield();
      }
    }
  }
  /** JNDI object factory so the proxy can be used as a resource. */
  public Object getObjectInstance(
      Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
    Reference ref = (Reference) obj;

    String api = null;
    String url = null;
    String user = null;
    String password = null;

    for (int i = 0; i < ref.size(); i++) {
      RefAddr addr = ref.get(i);

      String type = addr.getType();
      String value = (String) addr.getContent();

      if (type.equals("type")) api = value;
      else if (type.equals("url")) url = value;
      else if (type.equals("user")) setUser(value);
      else if (type.equals("password")) setPassword(value);
    }

    if (url == null) throw new NamingException("`url' must be configured for HessianProxyFactory.");
    // XXX: could use meta protocol to grab this
    if (api == null)
      throw new NamingException("`type' must be configured for HessianProxyFactory.");

    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Class apiClass = Class.forName(api, false, loader);

    return create(apiClass, url);
  }
  public BookCatalogImpl() {

    try {

      final String filePath = path + "catalog.json";
      // read the json file
      ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
      InputStream inputStream = classLoader.getResourceAsStream(filePath);

      BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
      bookStrBuilder = new StringBuilder();

      String inputStr;
      while ((inputStr = streamReader.readLine()) != null) bookStrBuilder.append(inputStr);

      final ObjectMapper mapper = new ObjectMapper();

      catalog = mapper.readValue(bookStrBuilder.toString(), new TypeReference<List<Book>>() {});

      hBookDetails = new Hashtable();

      for (Book book : catalog) {

        hBookDetails.put(book.getId(), book);
      }

    } catch (FileNotFoundException ex) {
      ex.printStackTrace();
    } catch (IOException ex) {
      ex.printStackTrace();
    } catch (NullPointerException ex) {
      ex.printStackTrace();
    }
  }
Example #14
0
 private void closeClientSocket() {
   try {
     client.close();
   } catch (IOException ex) {
     Log.warn(Thread.currentThread().getName() + ": failed to close client socket.", ex);
   }
 }
 public void stop() {
   try {
     Socket socket1;
     InputStream inputstream;
     OutputStream outputstream;
     synchronized (this) {
       if (!isRun) return;
       timeUpdate();
       isRun = false;
       socket1 = socket;
       inputstream = In;
       outputstream = Out;
       socket = null;
       In = null;
       Out = null;
       Thread thread1 = Thread.currentThread();
       if (thread != null && thread1 != thread) {
         thread.interrupt();
         thread = null;
       }
     }
     try {
       if (socket1 != null) socket1.close();
       if (inputstream != null) inputstream.close();
       if (outputstream != null) outputstream.close();
     } catch (IOException _ex) {
     }
   } catch (Throwable throwable) {
     throwable.printStackTrace();
   }
 }
Example #16
0
 public void run() {
     try {
         while (true) {
             
             System.out.println("Starting Kepplerian maintenance process");
             
             int files = 1;
             Enumeration enum = link.elements();
             while (enum.hasMoreElements()) {
                 String url = (String) enum.nextElement();
                 System.out.println("Downloading from [ " + url + " ]   [" + downloadKeps(url, "keps" + files + ".txt") + " ]");
                 files++;
             }
             
             System.out.println("Done");
             System.out.println("");
             System.out.println("Starting satellites creation process");
             Vector fileList = new Vector();
             for (int f = 1; f < files; f++) {
                 String file = "keps" + f + ".txt";
                 fileList.addElement(file);
             }
             
             
             buildSatsFromKeps(fileList);
             
             
             System.out.println("[The Keplerian updater is now going to sleep for  " + freq + " days]");
             Thread.currentThread();
             Thread.sleep(Integer.parseInt(freq) * 24 * 60 * 60 * 1000);
         }
     } catch (Exception e) {
 /**
  * Builds a new AgentMBeanServerConnectionFactory and returns the underlying
  * MBeanServerConnection
  *
  * @return a new MBeanServerConnection
  */
 public MBeanServerConnection build() {
   final String key = buildKey();
   MBeanServerConnection conn = INSTANCES.get(key);
   if (conn == null) {
     synchronized (INSTANCES) {
       conn = INSTANCES.get(key);
       if (conn == null) {
         conn =
             (MBeanServerConnection)
                 Proxy.newProxyInstance(
                     Thread.currentThread().getContextClassLoader(),
                     new Class[] {MBeanServerConnection.class},
                     new AgentMBeanServerConnectionFactory(this));
         INSTANCES.put(key, conn);
         channel
             .getCloseFuture()
             .addListener(
                 new ChannelFutureListener() {
                   @Override
                   public void operationComplete(ChannelFuture future) throws Exception {
                     INSTANCES.remove(key);
                   }
                 });
       }
     }
   }
   return conn;
 }
Example #18
0
  // XXX dir.canWrite() has issues on Windows, so verify it directly:
  // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6203387
  public static boolean isDirectoryWritable(File dir) {
    boolean isWritable = false;

    if (dir != null) {
      // new File("").isDirectory() is false, even though getAbsolutePath() returns the right path.
      // this resolves it
      dir = dir.getAbsoluteFile();

      if (dir.isDirectory()) {
        File file =
            new File(
                dir,
                String.format(
                    "pms_directory_write_test_%d_%d.tmp",
                    System.currentTimeMillis(), Thread.currentThread().getId()));

        try {
          if (file.createNewFile()) {
            if (isFileWritable(file)) {
              isWritable = true;
            }

            if (!file.delete()) {
              LOGGER.warn("Can't delete temporary test file: {}", file.getAbsolutePath());
            }
          }
        } catch (IOException | SecurityException ioe) {
        }
      }
    }

    return isWritable;
  }
  /**
   * Closes given {@link #transportManagers} of this <tt>Conference</tt> and removes corresponding
   * channel bundle.
   */
  void closeTransportManager(TransportManager transportManager) {
    synchronized (transportManagers) {
      for (Iterator<IceUdpTransportManager> i = transportManagers.values().iterator();
          i.hasNext(); ) {
        if (i.next() == transportManager) {
          i.remove();
          // Presumably, we have a single association for
          // transportManager.
          break;
        }
      }

      // Close manager
      try {
        transportManager.close();
      } catch (Throwable t) {
        logger.warn(
            "Failed to close an IceUdpTransportManager of" + " conference " + getID() + "!", t);
        // The whole point of explicitly closing the
        // transportManagers of this Conference is to prevent memory
        // leaks. Hence, it does not make sense to possibly leave
        // TransportManagers open because a TransportManager has
        // failed to close.
        if (t instanceof InterruptedException) Thread.currentThread().interrupt();
        else if (t instanceof ThreadDeath) throw (ThreadDeath) t;
      }
    }
  }
Example #20
0
  public static void main(String args[]) {
    if (args.length != 1) {
      System.err.println("Usage: NBIOClient <hostname>\n");
      System.exit(-1);
    }

    try {
      System.err.println("NBIOClient starting...");
      NonblockingSocket s = new NonblockingSocket(args[0], 4046);

      NonblockingOutputStream os = (NonblockingOutputStream) s.getOutputStream();
      String str = "Hello there server!";
      byte barr[] = str.getBytes();

      while (true) {
        int c = os.nbWrite(barr);
        System.err.println("WROTE " + c + " bytes");
        try {
          Thread.currentThread().sleep(1000);
        } catch (InterruptedException ie) {
        }
      }

    } catch (Exception e) {
      System.err.println("NBIOClient: Caught exception: " + e);
      e.printStackTrace();
      System.exit(-1);
    }
  }
 @Override
 public void run() {
   int count;
   try {
     while (!Thread.currentThread().isInterrupted() && !isComplete) {
       URL url = new URL(urlStr);
       URLConnection conection = url.openConnection();
       conection.connect();
       int lenghtOfFile = conection.getContentLength();
       InputStream input = new BufferedInputStream(url.openStream(), 8192);
       File file =
           createNameFile(
               Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                   + "/"
                   + this.tile,
               type);
       OutputStream output = new FileOutputStream(file);
       byte data[] = new byte[1024];
       long start = System.currentTimeMillis();
       long total = 0;
       while ((count = input.read(data)) != -1) {
         total += count;
         output.write(data, 0, count);
         updateProgress((int) ((total * 100) / lenghtOfFile));
       }
       output.flush();
       output.close();
       input.close();
       isComplete = true;
     }
   } catch (Exception e) {
     isComplete = false;
   }
 }
Example #22
0
    public void run() {
      if (Thread.currentThread() == this) {
        //                    Environment.setThreadEnvironment(launcherEnvironment);
        Job.setUserInterface(userInterface);
      }
      try {
        PrintWriter pw = null;
        if (redirect != null) pw = new PrintWriter(redirect);

        // read from stream
        InputStreamReader input = new InputStreamReader(in);
        BufferedReader reader = new BufferedReader(input);
        int read = 0;
        while ((read = reader.read(buf)) >= 0) {
          if (pw != null) {
            pw.write(buf, 0, read);
            pw.flush();
          }
        }

        reader.close();
        input.close();

      } catch (java.io.IOException e) {
        ActivityLogger.logException(e);
      }
    }
  public void testGetAttributesForThisTestClass() throws IOException {
    if (Os.isFamily(Os.FAMILY_WINDOWS)) {
      System.out.println("WARNING: Unsupported OS, skipping test");
      return;
    }

    URL resource =
        Thread.currentThread()
            .getContextClassLoader()
            .getResource(getClass().getName().replace('.', '/') + ".class");

    if (resource == null) {
      throw new IllegalStateException(
          "SOMETHING IS VERY WRONG. CANNOT FIND THIS TEST CLASS IN THE CLASSLOADER.");
    }

    File f = new File(resource.getPath().replaceAll("%20", " "));

    Map attrs =
        PlexusIoResourceAttributeUtils.getFileAttributesByPath(
            f, new ConsoleLogger(Logger.LEVEL_INFO, "test"), Logger.LEVEL_DEBUG);

    PlexusIoResourceAttributes fileAttrs =
        (PlexusIoResourceAttributes) attrs.get(f.getAbsolutePath());

    System.out.println("Got attributes for: " + f.getAbsolutePath() + fileAttrs);

    assertNotNull(fileAttrs);
    assertTrue(fileAttrs.isOwnerReadable());
    assertEquals(System.getProperty("user.name"), fileAttrs.getUserName());
  }
  // Private method to infer the caller's class and method names
  private void inferCaller() {
    needToInferCaller = false;
    // Android-changed: Use VMStack.getThreadStackTrace.
    StackTraceElement[] stack = VMStack.getThreadStackTrace(Thread.currentThread());
    int depth = stack.length;

    boolean lookingForLogger = true;
    for (int ix = 0; ix < depth; ix++) {
      // Calling getStackTraceElement directly prevents the VM
      // from paying the cost of building the entire stack frame.
      //
      // Android-changed: Use value from getThreadStackTrace.
      StackTraceElement frame = stack[ix];
      String cname = frame.getClassName();
      boolean isLoggerImpl = isLoggerImplFrame(cname);
      if (lookingForLogger) {
        // Skip all frames until we have found the first logger frame.
        if (isLoggerImpl) {
          lookingForLogger = false;
        }
      } else {
        if (!isLoggerImpl) {
          // skip reflection call
          if (!cname.startsWith("java.lang.reflect.") && !cname.startsWith("sun.reflect.")) {
            // We've found the relevant frame.
            setSourceClassName(cname);
            setSourceMethodName(frame.getMethodName());
            return;
          }
        }
      }
    }
    // We haven't found a suitable frame, so just punt.  This is
    // OK as we are only committed to making a "best effort" here.
  }
Example #25
0
  public void run() {

    // setup advertisement message
    advMsg.set_sourceAddr(TOS_UART_ADDR);

    if (reboot) {
      advMsg.set_summary_vNum(0x0);
      advMsg.set_runningVNum(0xffff);
    } else {
      advMsg.set_summary_vNum(0xffff);
      advMsg.set_runningVNum(0x0);
    }
    advMsg.set_summary_numPgsComplete((byte) numPgs);

    while (true) {
      try {
        // send an advertisement message every second
        if (printAllMsgs) System.out.print(advMsg);
        send(advMsg);
        Thread.currentThread().sleep(1000);
        if (reboot) {
          System.exit(0);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Example #26
0
	public static void main(String[] args) throws Exception{
		//free和use和total均为KB 
		long free=0; 
		long use=0; 
		long total=0;  
		int kb=1024;

		Runtime rt=Runtime.getRuntime();
		total=rt.totalMemory();
		free=rt.freeMemory();
		use=total-free;
		
		System.out.println("系统内存已用的空间为:"+use/kb+" MB");
		System.out.println("系统内存的空闲空间为:"+free/kb+" MB");
		System.out.println("系统总内存空间为:"+total/kb+" MB");   

		OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
		
		long physicalFree=osmxb.getFreePhysicalMemorySize()/kb;
		long physicalTotal=osmxb.getTotalPhysicalMemorySize()/kb;
		long physicalUse=physicalTotal-physicalFree;
		String os=System.getProperty("os.name");
		System.out.println("操作系统的版本:"+os);
		System.out.println("系统物理内存已用的空间为:"+physicalFree+" MB");
		System.out.println("系统物理内存的空闲空间为:"+physicalUse+" MB");
		System.out.println("总物理内存:"+physicalTotal+" MB");

		// 获得线程总数 
        	ThreadGroup parentThread;
        	for (parentThread = Thread.currentThread().getThreadGroup(); parentThread.getParent() != null; parentThread = parentThread.getParent())
			;
		int totalThread = parentThread.activeCount();

		System.out.println("获得线程总数:"+totalThread);
	}
Example #27
0
 public void run() {
   if (Thread.currentThread() != this.mt)
     throw (new RuntimeException("MainFrame is being run from an invalid context"));
   Thread ui = new HackThread(p, "Haven UI thread");
   ui.start();
   try {
     try {
       Session sess = null;
       while (true) {
         UI.Runner fun;
         if (sess == null) {
           Bootstrap bill = new Bootstrap(Config.defserv, Config.mainport);
           if ((Config.authuser != null) && (Config.authck != null)) {
             bill.setinitcookie(Config.authuser, Config.authck);
             Config.authck = null;
           }
           fun = bill;
           setTitle(String.format("Amish Paradise %s", version));
         } else {
           fun = new RemoteUI(sess);
           setTitle(String.format("Amish Paradise %s \u2013 %s", version, sess.username));
         }
         sess = fun.run(p.newui(sess));
       }
     } catch (InterruptedException e) {
     }
     savewndstate();
   } finally {
     ui.interrupt();
     dispose();
   }
 }
Example #28
0
 /** Simple pause method used for debugging. */
 static void pause(int length) {
   try {
     Thread.currentThread().sleep(length);
   } catch (InterruptedException ex) {
     System.err.println(ex);
   }
 }
  /**
   * Constructor. The first time an RJavaClassLoader is created, it is cached as the primary loader.
   *
   * @param path path of the rJava package
   * @param libpath lib sub directory of the rJava package
   */
  public RJavaClassLoader(String path, String libpath) {
    super(new URL[] {});
    // respect rJava.debug level
    String rjd = System.getProperty("rJava.debug");
    if (rjd != null && rjd.length() > 0 && !rjd.equals("0")) verbose = true;
    if (verbose) System.out.println("RJavaClassLoader(\"" + path + "\",\"" + libpath + "\")");
    if (primaryLoader == null) {
      primaryLoader = this;
      if (verbose) System.out.println(" - primary loader");
    } else {
      if (verbose)
        System.out.println(" - NOT primrary (this=" + this + ", primary=" + primaryLoader + ")");
    }
    libMap = new HashMap /*<String,UnixFile>*/();

    classPath = new Vector /*<UnixFile>*/();
    classPath.add(new UnixDirectory(path + "/java"));

    rJavaPath = path;
    rJavaLibPath = libpath;

    /* load the rJava library */
    UnixFile so = new UnixFile(rJavaLibPath + "/rJava.so");
    if (!so.exists()) so = new UnixFile(rJavaLibPath + "/rJava.dll");
    if (so.exists()) libMap.put("rJava", so);

    /* load the jri library */
    UnixFile jri = new UnixFile(path + "/jri/libjri.so");
    String rarch = System.getProperty("r.arch");
    if (rarch != null && rarch.length() > 0) {
      UnixFile af = new UnixFile(path + "/jri" + rarch + "/libjri.so");
      if (af.exists()) jri = af;
      else {
        af = new UnixFile(path + "/jri" + rarch + "/jri.dll");
        if (af.exists()) jri = af;
      }
    }
    if (!jri.exists()) jri = new UnixFile(path + "/jri/libjri.jnilib");
    if (!jri.exists()) jri = new UnixFile(path + "/jri/jri.dll");
    if (jri.exists()) {
      libMap.put("jri", jri);
      if (verbose) System.out.println(" - registered JRI: " + jri);
    }

    /* if we are the primary loader, make us the context loader so
    projects that rely on the context loader pick us */
    if (primaryLoader == this) Thread.currentThread().setContextClassLoader(this);

    if (verbose) {
      System.out.println("RJavaClassLoader initialized.\n\nRegistered libraries:");
      for (Iterator entries = libMap.keySet().iterator(); entries.hasNext(); ) {
        Object key = entries.next();
        System.out.println("  " + key + ": '" + libMap.get(key) + "'");
      }
      System.out.println("\nRegistered class paths:");
      for (Enumeration e = classPath.elements(); e.hasMoreElements(); )
        System.out.println("  '" + e.nextElement() + "'");
      System.out.println("\n-- end of class loader report --");
    }
  }
Example #30
0
 public static void main(String[] args) throws IOException, InterruptedException {
   boolean stop = false;
   ServerSocket server = new ServerSocket(8080, 1, InetAddress.getByName("127.0.0.1"));
   while (!stop) {
     Socket socket = server.accept();
     OutputStream os = socket.getOutputStream();
     PrintWriter out = new PrintWriter(os);
     InputStream is = socket.getInputStream();
     BufferedReader reader = new BufferedReader(new InputStreamReader(is));
     out.print("<h1>Hello World</h1>");
     out.flush();
     boolean loop = true;
     StringBuffer sb = new StringBuffer();
     while (loop) {
       if (reader.ready()) {
         int i = 0;
         while ((i = reader.read()) != -1) {
           sb.append((char) i);
         }
         loop = false;
       }
       Thread.currentThread().sleep(500);
     }
     System.out.println(sb);
     out.close();
     is.close();
     socket.close();
   }
   server.close();
 }