Example #1
1
  public static void main(String[] args) throws Exception {
    System.setSecurityManager(new SecurityManager());

    // Create an uninitialized class loader
    try {
      new ClassLoader(null) {
        @Override
        protected void finalize() {
          loader = this;
        }
      };
    } catch (SecurityException exc) {
      // Expected
    }
    System.gc();
    System.runFinalization();

    // if 'loader' isn't null, need to ensure that it can't be used as
    // parent
    if (loader != null) {
      try {
        // Create a class loader with 'loader' being the parent
        URLClassLoader child = URLClassLoader.newInstance(new URL[0], loader);
        throw new RuntimeException("Test Failed!");
      } catch (SecurityException se) {
        System.out.println("Test Passed: Exception thrown");
      }
    } else {
      System.out.println("Test Passed: Loader is null");
    }
  }
  /**
   * Creates a new Socket connected to the given IP address. The method uses connection settings
   * supplied in the constructor for connecting the socket.
   *
   * @param address the IP address to connect to
   * @return connected socket
   * @throws java.net.UnknownHostException if the hostname of the address or the proxy cannot be
   *     resolved
   * @throws java.io.IOException if an I/O error occured while connecting to the remote end or to
   *     the proxy
   */
  private Socket createSocket(InetSocketAddress address, int timeout) throws IOException {
    String socksProxyHost = System.getProperty("socksProxyHost");
    System.getProperties().remove("socksProxyHost");
    try {
      ConnectivitySettings cs = lastKnownSettings.get(address);
      if (cs != null) {
        try {
          return createSocket(cs, address, timeout);
        } catch (IOException e) {
          // not good anymore, try all proxies
          lastKnownSettings.remove(address);
        }
      }

      URI uri = addressToURI(address, "socket");
      try {
        return createSocket(uri, address, timeout);
      } catch (IOException e) {
        // we will also try https
      }

      uri = addressToURI(address, "https");
      return createSocket(uri, address, timeout);

    } finally {
      if (socksProxyHost != null) {
        System.setProperty("socksProxyHost", socksProxyHost);
      }
    }
  }
Example #3
0
  /**
   * Konstruktor
   *
   * @param configFile Jmeno konfiguracniho souboru
   */
  public Server(String configFile) {
    setServerConfig(new ServerConfig(configFile));

    setPort(getServerConfig().getPort());
    try {
      setBindAddress(InetAddress.getByName(getServerConfig().getBindAddress()));
    } catch (UnknownHostException e) {
      System.err.println("Bind adresa neni platna!");
      System.exit(-1);
    }

    try {
      setServerSocket(new ServerSocket(getPort(), 0, getBindAddress()));
    } catch (IOException e) {
      System.err.println("Chyba startu ServerSocketu");
      System.exit(-1);
    }

    System.out.println("Server spusten");

    clients = new Hashtable<String, ServerThread>();
    boolean running = true;
    while (running) {
      try {
        accept();
      } catch (IOException e) {
        System.err.println("Chyba acceptu");
        running = false;
      }
    }
  }
 /**
  * invoke as: <CODE>
  * java -cp &lt;classpath&gt; parallel.distributed.PDBTExecSingleCltWrkInitSrv [workers_port(7890)] [client_port(7891)]
  * </CODE>
  *
  * @param args String[]
  */
 public static void main(String[] args) {
   int wport = 7890; // default port
   int cport = 7891;
   if (args.length > 0) {
     try {
       wport = Integer.parseInt(args[0]);
     } catch (Exception e) {
       e.printStackTrace();
       usage();
       System.exit(-1);
     }
     if (args.length > 1) {
       try {
         cport = Integer.parseInt(args[1]);
       } catch (Exception e) {
         e.printStackTrace();
         usage();
         System.exit(-1);
       }
     }
   }
   PDBTExecSingleCltWrkInitSrv server = new PDBTExecSingleCltWrkInitSrv(wport, cport);
   try {
     server.run();
   } catch (Exception e) {
     e.printStackTrace();
     System.err.println("Server exits due to exception.");
   }
 }
Example #5
0
  @Before
  public void dbInit() throws Exception {
    String configFileName = System.getProperty("user.home");
    if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) {
      configFileName += "/.pokerth/config.xml";
    } else {
      configFileName += "/AppData/Roaming/pokerth/config.xml";
    }
    File file = new File(configFileName);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);
    doc.getDocumentElement().normalize();
    Element configNode = (Element) doc.getElementsByTagName("Configuration").item(0);

    Element dbAddressNode = (Element) configNode.getElementsByTagName("DBServerAddress").item(0);
    String dbAddress = dbAddressNode.getAttribute("value");

    Element dbUserNode = (Element) configNode.getElementsByTagName("DBServerUser").item(0);
    String dbUser = dbUserNode.getAttribute("value");

    Element dbPasswordNode = (Element) configNode.getElementsByTagName("DBServerPassword").item(0);
    String dbPassword = dbPasswordNode.getAttribute("value");

    Element dbNameNode = (Element) configNode.getElementsByTagName("DBServerDatabaseName").item(0);
    String dbName = dbNameNode.getAttribute("value");

    final String dbUrl = "jdbc:mysql://" + dbAddress + ":3306/" + dbName;
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    dbConn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
  }
Example #6
0
 /**
  * 验证项目是否ok
  *
  * @param contextPath 项目路径
  */
 public static boolean isdomainok(String contextPath, String securityKey, String domiankey) {
   try {
     if (contextPath.indexOf("127.0.") > -1 || contextPath.indexOf("192.168.") > -1) {
       return true;
     }
     String dedomaininfo = PurseSecurityUtils.decryption(domiankey, securityKey);
     Gson gson = new Gson();
     JsonParser jsonParser = new JsonParser();
     JsonObject jsonObject = jsonParser.parse(dedomaininfo).getAsJsonObject();
     Map<String, String> map =
         gson.fromJson(jsonObject, new TypeToken<Map<String, String>>() {}.getType());
     String domain = map.get("domain");
     if (contextPath.indexOf(domain) < 0) {
       System.exit(2);
       return false;
     }
     String dt = map.get("dt");
     if (com.yizhilu.os.core.util.StringUtils.isNotEmpty(dt)) {
       Date t = DateUtils.toDate(dt, "yyyy-MM-dd");
       if (t.compareTo(new Date()) < 0) {
         System.exit(3);
         return false;
       }
     }
     return true;
   } catch (Exception e) {
     return false;
   }
 }
    protected void addTimeStamp(ClassNode node) {
      if (node.getDeclaredField(Verifier.__TIMESTAMP)
          == null) { // in case if verifier visited the call already
        FieldNode timeTagField =
            new FieldNode(
                Verifier.__TIMESTAMP,
                ACC_PUBLIC | ACC_STATIC | ACC_SYNTHETIC,
                ClassHelper.long_TYPE,
                // "",
                node,
                new ConstantExpression(System.currentTimeMillis()));
        // alternatively, FieldNode timeTagField = SourceUnit.createFieldNode("public static final
        // long __timeStamp = " + System.currentTimeMillis() + "L");
        timeTagField.setSynthetic(true);
        node.addField(timeTagField);

        timeTagField =
            new FieldNode(
                Verifier.__TIMESTAMP__ + String.valueOf(System.currentTimeMillis()),
                ACC_PUBLIC | ACC_STATIC | ACC_SYNTHETIC,
                ClassHelper.long_TYPE,
                // "",
                node,
                new ConstantExpression((long) 0));
        // alternatively, FieldNode timeTagField = SourceUnit.createFieldNode("public static final
        // long __timeStamp = " + System.currentTimeMillis() + "L");
        timeTagField.setSynthetic(true);
        node.addField(timeTagField);
      }
    }
Example #8
0
  public static void main(String[] args) throws IOException, ClassNotFoundException {
    ServerSocket serverSocket = null;
    boolean listening = true;
    Class.forName("org.sqlite.JDBC");

    try {
      if (args.length == 1) {
        serverSocket = new ServerSocket(Integer.parseInt(args[0]));
        System.out.println(
            "Server up and running with:\nhostname: " + getLocalIpAddress() + "\nport: " + args[0]);
        System.out.println("Waiting to accept client...");
        System.out.println("Remember to setup client hostname");
      } else {
        System.err.println("ERROR: Invalid arguments!");
        System.exit(-1);
      }
    } catch (IOException e) {
      System.err.println("ERROR: Could not listen on port!");
      System.exit(-1);
    }

    while (listening) {
      new ServerHandlerThread(serverSocket.accept()).start();
    }

    serverSocket.close();
  }
Example #9
0
 public static void main(String[] args) {
   String str;
   Socket sock = null;
   ObjectOutputStream writer = null;
   Scanner kb = new Scanner(System.in);
   try {
     sock = new Socket("127.0.0.1", 4445);
   } catch (IOException e) {
     System.out.println("Could not connect.");
     System.exit(-1);
   }
   try {
     writer = new ObjectOutputStream(sock.getOutputStream());
   } catch (IOException e) {
     System.out.println("Could not create write object.");
     System.exit(-1);
   }
   str = kb.nextLine();
   try {
     writer.writeObject(str);
     writer.flush();
   } catch (IOException e) {
     System.out.println("Could not write to buffer");
     System.exit(-1);
   }
   try {
     sock.close();
   } catch (IOException e) {
     System.out.println("Could not close connection.");
     System.exit(-1);
   }
   System.out.println("Wrote and exited successfully");
 }
Example #10
0
  public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();
    String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
    if (otherArgs.length != 2) {
      System.err.println("Usage: test.icde12.HadoopJoin <in> <out>");
      System.exit(2);
    }
    Job job = new Job(conf, "hadoop join");
    job.setJarByClass(HadoopJoin.class);
    job.setMapperClass(TokenizerMapper.class);
    job.setCombinerClass(IntSumReducer.class);
    job.setReducerClass(IntSumReducer.class);

    job.setPartitionerClass(ICDEPartitioner.class);

    //    WritableComparator.define(Text.class,new ICDEComparator());

    job.setSortComparatorClass(ICDEComparator.class);

    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(Text.class);
    job.setNumReduceTasks(8);
    FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
    FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
    System.exit(job.waitForCompletion(true) ? 0 : 1);
  }
Example #11
0
  public Sender(int sk1_dst_port, int sk4_dst_port, String inPath, String outName) {
    DatagramSocket sk1, sk4;
    System.out.println(
        "sk1_dst_port=" + sk1_dst_port + ", " + "sk4_dst_port=" + sk4_dst_port + ".");

    try {
      // create sockets
      sk1 = new DatagramSocket();
      sk4 = new DatagramSocket(sk4_dst_port);

      File file = new File(inPath);
      if (!(file.exists() && file.isFile())) {
        System.err.println("File does not exist.");
        System.exit(-1);
      }

      // create threads to process data
      InThread th_in = new InThread(sk4);
      OutThread th_out = new OutThread(sk1, sk1_dst_port, sk4_dst_port, inPath, outName);
      th_in.start();
      th_out.start();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(-1);
    }
  }
Example #12
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);
    }
  }
  // public static LinkedList<Message> queue = new LinkedList<Message>();
  public static void main(String[] args) throws IOException {
    int port = 4444;
    ServerSocket serverSocket = null;
    try {
      String _port = System.getProperty("port");
      if (_port != null) port = Integer.parseInt(_port);
      serverSocket = new ServerSocket(port);
      MBusQueueFactory.createQueues();
    } catch (IOException e) {
      System.err.println("Could not listen on port: " + port + ".");
      System.exit(1);
    }
    System.out.println("Server is running at port : " + port + ".");

    Socket clientSocket = null;
    while (true) {
      try {
        System.out.println("Waiting for client.....");
        clientSocket = serverSocket.accept();
      } catch (IOException e) {
        System.err.println("Accept failed.");
        e.printStackTrace();
      }
      System.out.println(clientSocket.getInetAddress().toString() + " Connected");
      Thread mt = new MessageBusWorker(clientSocket);
      mt.start();
    }
  }
Example #14
0
 static void help() {
   System.out.println("");
   System.out.println("Usage: java RawLogger [options] ");
   System.out.println("  [options] are:");
   System.out.println("  -h, --help                  Display this message.");
   System.out.println("  --logging                   Enable Logging.");
   System.out.println("                              Required options (source). ");
   System.out.println("                              And (url, user, pass, tablename). ");
   System.out.println("  --display                   Display Packets.");
   System.out.println("                              Required options (source). ");
   System.out.println("  --createtable               Create a table.");
   System.out.println(
       "                              Required options (url, user, pass, tablename).");
   System.out.println("  --droptable                 Drop a table.");
   System.out.println(
       "                              Required options (url, user, pass, tablename).");
   System.out.println("  --cleartable                Clear a table.");
   System.out.println(
       "                              Required options (url, user, pass, tablename).");
   System.out.println("  --duration                  Summary of Experiement Duration.");
   System.out.println(
       "                              Required options (url, user, pass, tablename).");
   System.out.println("  --reset                     Reseting EPRB and the attached mote ");
   System.out.println("                              Required options (source). ");
   System.out.println("  --tablename=<name>          Specify sql tablename ");
   System.out.println("  --url=<ip/dbname>           JDBC URL. eg: localhost/rsc.");
   System.out.println("  --user=<user>               User of the database.");
   System.out.println("  --pass=<password>           Password of the database.");
   System.out.println("  --source=<type>             Standard TinyOS Source");
   System.out.println("                              serial@COM1:platform");
   System.out.println("                              network@HOSTNAME:PORTNUMBER");
   System.out.println("                              sf@HOSTNAME:PORTNUMBER");
   System.out.println("");
   System.exit(-1);
 }
Example #15
0
  public static void duration() {
    connectDb();
    String sql = "select min(time), max(time), count(*) from " + tablename + ";";
    try {
      ResultSet rs = query.executeQuery(sql);
      rs.next();
      int numCols = rs.getMetaData().getColumnCount();
      String minTime = rs.getString(1);
      String maxTime = rs.getString(2);
      String numPackets = rs.getString(3);
      System.out.println(
          "Experiment "
              + tablename
              + "\n\tfrom: "
              + minTime
              + "\n\tto: "
              + maxTime
              + "\n\tpackets: "
              + numPackets);

    } catch (SQLException e) {
      System.out.println("SQL Exception: " + e);
      System.exit(1);
    }
  }
Example #16
0
 public static void main(String[] args) throws Exception {
   BioServer s = new BioServer(9999);
   s.start();
   System.console().readLine("BioServer running on port 9999. Press enter to exit.");
   System.exit(0);
   s.stop();
 }
Example #17
0
  public PingResult ping(ScanningSubject subject, int count) throws IOException {
    PingResult result = new PingResult(subject.getAddress());

    DatagramSocket socket = sockets.bind(new DatagramSocket());
    socket.setSoTimeout(timeout);
    socket.connect(subject.getAddress(), PROBE_UDP_PORT);

    for (int i = 0; i < count && !Thread.currentThread().isInterrupted(); i++) {
      long startTime = System.currentTimeMillis();
      byte[] payload = new byte[8];
      ByteBuffer.wrap(payload).putLong(startTime);
      DatagramPacket packet = new DatagramPacket(payload, payload.length);
      try {
        socket.send(packet);
        socket.receive(packet);
      } catch (PortUnreachableException e) {
        result.addReply(System.currentTimeMillis() - startTime);
      } catch (SocketTimeoutException ignore) {
      } catch (NoRouteToHostException e) {
        // this means that the host is down
        break;
      } catch (SocketException e) {
        if (e.getMessage().contains(/*No*/ "route to host")) {
          // sometimes 'No route to host' also gets here...
          break;
        }
      } catch (IOException e) {
        LOG.log(FINER, subject.toString(), e);
      }
    }
    return result;
  }
  private void initAuthUserInfo(HttpURLConnection conn, String userInfo) {
    String user;
    String password;
    if (userInfo != null) { // get the user and password
      // System.out.println("UserInfo= " + userInfo );
      int delimiter = userInfo.indexOf(':');
      if (delimiter == -1) {
        user = ParseUtil.decode(userInfo);
        password = null;
      } else {
        user = ParseUtil.decode(userInfo.substring(0, delimiter++));
        password = ParseUtil.decode(userInfo.substring(delimiter));
      }

      String plain = user + ":";
      byte[] nameBytes = plain.getBytes();
      byte[] passwdBytes = password.getBytes();

      // concatenate user name and password bytes and encode them
      byte[] concat = new byte[nameBytes.length + passwdBytes.length];

      System.arraycopy(nameBytes, 0, concat, 0, nameBytes.length);
      System.arraycopy(passwdBytes, 0, concat, nameBytes.length, passwdBytes.length);
      String auth = "Basic " + new String(Base64.encode(concat));
      conn.setRequestProperty("Authorization", auth);
      if (dL > 0) d("Adding auth " + auth);
    }
  }
Example #19
0
 void updateMenus() {
   if (IJ.debugMode) {
     long start = System.currentTimeMillis();
     Menus.updateImageJMenus();
     IJ.log("Refresh Menus: " + (System.currentTimeMillis() - start) + " ms");
   } else Menus.updateImageJMenus();
 }
Example #20
0
 public static boolean getFormFields(
     ResponseWrapper rw, List<NameValuePairString> hiddenFormFields, String formSelector) {
   // --- analisi della pagina contente la form, specifica al sito
   Document doc = rw.getJSoupDocument();
   Elements els = doc.select(formSelector); // per debug, dovrebbe essere uo
   if (els == null || els.size() <= 0) {
     log.error("unable to find form at selector: " + formSelector);
     System.exit(1);
     return false;
   }
   Element loginForm = els.get(0);
   if (loginForm == null) {
     log.error("failed to get form to analyze at: " + rw.dump());
     System.exit(1);
   }
   // log.info("login form OUTER HTML\n" + loginForm.outerHtml());
   Elements inputFields = loginForm.select("input");
   // display all
   for (Element e : inputFields) {
     String type = e.attr("type");
     if (type.equals("submit")) {
       continue;
     }
     String attrName = e.attr("name");
     hiddenFormFields.add(new NameValuePairString(attrName, e.val()));
     log.debug("captured form input: " + attrName + " = " + e.val());
   }
   return false;
 }
Example #21
0
  /** 基类实现消息监听接口,加上打印metaq监控日志的方法 */
  @Override
  public ConsumeConcurrentlyStatus consumeMessage(
      List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
    long startTime = System.currentTimeMillis();
    logger.info("receive_message:{}", msgs.toString());
    if (msgs == null || msgs.size() < 1) {
      logger.error("receive empty msg!");
      return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

    List<Serializable> msgList = new ArrayList<>();
    for (MessageExt message : msgs) {
      msgList.add(decodeMsg(message));
    }

    final int reconsumeTimes = msgs.get(0).getReconsumeTimes();
    MsgObj msgObj = new MsgObj();
    msgObj.setReconsumeTimes(reconsumeTimes);
    msgObj.setMsgList(msgList);
    msgObj.setContext(context);
    context.setDelayLevelWhenNextConsume(getDelayLevelWhenNextConsume(reconsumeTimes));

    ConsumeConcurrentlyStatus status = doConsumeMessage(msgObj);
    logger.info(
        "ConsumeConcurrentlyStatus:{}|cost:{}", status, System.currentTimeMillis() - startTime);
    return status;
  }
Example #22
0
  public void run() {

    try {
      DataOutputStream out = new DataOutputStream(client.getOutputStream());
      FileInputStream file_in = new FileInputStream(file);
      DataInputStream in = new DataInputStream(file_in);

      byte buffer[] = new byte[512];

      while (in.read(buffer) != -1) {
        System.out.print("\nSending buffer to: " + client_id);
        out.write(buffer, 0, buffer.length);
      }
    } catch (Exception exception) {
      System.out.println("\nException" + exception);
      System.exit(0);
    } finally {
      try {
        client.close();
      } catch (Exception exception) {
        System.out.println("\nException" + exception);
        System.exit(0);
      }
    }
  }
  private Core() {
    boolean f = false;
    try {
      for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
        NetworkInterface intf = (NetworkInterface) en.nextElement();
        for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
          InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
          if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
            String ipAddress = inetAddress.getHostAddress().toString();
            this.ip = inetAddress;
            f = true;
            break;
          }
        }
        if (f) break;
      }
    } catch (SocketException ex) {
      ex.printStackTrace();
      System.exit(1);
    }
    this.teams = new HashMap<String, Team>();
    this.judges = new HashMap<String, Judge>();
    this.problems = new HashMap<String, ProblemInfo>();
    this.scheduler = new Scheduler();
    this.timer = new ContestTimer(300 * 60);

    try {
      readConfigure();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      System.exit(1);
    }
    this.scoreBoardHttpServer = new ScoreBoardHttpServer(this.scoreBoardPort);
  }
  public static void main(String[] args) throws Exception {

    if (args.length > 0) {
      URL context = null;
      String input, result;

      if (args.length > 1) {
        context = new URL(args[0]);
        input = args[1];
      } else {
        input = args[0];
      }

      try {
        result = new URL(context, input).toString();
      } catch (MalformedURLException e) {
        result = e.toString();
      }

      System.out.println("  CONTEXT: " + context);
      System.out.println("    INPUT: " + input);
      System.out.println("   RESULT: " + result);
      System.exit(0);
    }

    boolean failed = false;
    for (int i = 0; i < cases.length; i++) {
      TestCase t = cases[i];
      URL context = null;
      String result;

      // Create context URL
      try {
        context = (t.context == null) ? null : new URL(t.context);
      } catch (MalformedURLException e) {
        System.out.println("Oops: " + t.context + ": " + e);
        System.exit(1);
      }

      // Create new URL in context
      try {
        result = new URL(context, t.input).toString();
      } catch (MalformedURLException e) {
        result = e.toString();
      }

      // Check result
      if (!result.equals(t.result)) {
        System.out.println("Test failure (case " + i + ")");
        System.out.println("  CONTEXT: " + t.context);
        System.out.println("    INPUT: " + t.input);
        System.out.println("   WANTED: " + t.result);
        System.out.println("  BUT GOT: " + result);
        failed = true;
      }
    }
    if (!failed) {
      System.out.println("Success.");
    }
  }
    // Creates a new thread, runs the program in that thread, and reports any errors as needed.
    private void run(String clazz) {
      try {
        // Makes sure the JVM resets if it's already running.
        if (JVMrunning) kill();

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

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

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

        JVM = builder.start();

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

        redirectErr = redirectIOStream(errorReader, err);
        redirectOut = redirectIOStream(outReader, out);
        // redirectIn = redirectIOStream(null, inReader);
      } catch (Exception e) {
        // This catches any other errors we might get.
        println("Some error thrown", progErr);
        logError(e.toString());
        displayLog();
        return;
      }
    }
 /**
  * This method runs the Runnable and measures how long it takes.
  *
  * @param r is the Runnable for the task that we want to measure
  * @return the time it took to execute this task
  */
 public static long time(Runnable r) {
   long time = -System.currentTimeMillis();
   r.run();
   time += System.currentTimeMillis();
   System.out.println("Took " + time + "ms");
   return time;
 }
 /**
  * creates a server socket listening on the port specified in the parameter of the constructor,
  * and waits for a single incoming client connection which it handles by invoking the <CODE>
  * addNewClientConnection(s)</CODE> method of the enclosing server, and then the thread exits.
  */
 public void run() {
   try {
     ServerSocket ss = new ServerSocket(_port);
     System.out.println("Srv: Now Accepting Single Client Connection");
     // while (true) {
     try {
       Socket s = ss.accept();
       System.out.println("Srv: Client Added to the Network");
       addNewClientConnection(s);
       System.out.println("Srv: finished adding client connection");
     } catch (Exception e) {
       // e.printStackTrace();
       System.err.println("Client Connection failed, exiting...");
       System.exit(-1);
     }
     // }
   } catch (IOException e) {
     // e.printStackTrace();
     utils.Messenger.getInstance()
         .msg(
             "PDBTExecSingleCltWrkInitSrv.C2Thread.run(): "
                 + "Failed to create Server Socket, Server exiting.",
             0);
     System.exit(-1);
   }
 }
  public static void main(String[] args) {
    String host = args[0];
    int port = Integer.parseInt(args[1]);
    long id = Long.parseLong(args[2]);
    String character = args[3];
    long actorId = Long.parseLong(args[4]);

    // Install an RMISecurityManager, if there is not a
    // SecurityManager already installed
    if (System.getSecurityManager() == null) {
      System.setSecurityManager(new RMISecurityManager());
    }

    String name = "rmi://" + host + ":" + port + "/MovieDatabase";

    try {
      MovieDatabase db = (MovieDatabase) Naming.lookup(name);
      db.noteCharacter(id, character, actorId);

      Movie movie = db.getMovie(id);
      out.println(movie.getTitle());
      for (Map.Entry entry : movie.getCharacters().entrySet()) {
        out.println("  " + entry.getKey() + "\t" + entry.getValue());
      }

    } catch (RemoteException | NotBoundException | MalformedURLException ex) {
      ex.printStackTrace(System.err);
    }
  }
  public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = null;

    try {
      serverSocket = new ServerSocket(10008);
      System.out.println("Enroll: 130050131071");
      System.out.println("Connection Socket Created");
      try {
        while (true) {
          System.out.println("Waiting for Connection");
          new EchoServer2(serverSocket.accept());
        }
      } catch (IOException e) {
        System.err.println("Accept failed.");
        System.exit(1);
      }
    } catch (IOException e) {
      System.err.println("Could not listen on port: 10008.");
      System.exit(1);
    } finally {
      try {
        serverSocket.close();
      } catch (IOException e) {
        System.err.println("Could not close port: 10008.");
        System.exit(1);
      }
    }
  }
Example #30
0
  @Override
  public void run() {
    long lastTimestamp = System.currentTimeMillis();
    long lastMessageCounter = 0L;

    while (true) {
      final long newTimestamp = System.currentTimeMillis();
      final long duration = newTimestamp - lastTimestamp;

      final long newMessageCounter = messageCounter;
      final long numberOfMessages = newMessageCounter - lastMessageCounter;

      System.out.format(
          "Sent %d messages in %dms\n", Long.valueOf(numberOfMessages), Long.valueOf(duration));

      lastTimestamp = newTimestamp;
      lastMessageCounter = newMessageCounter;

      try {
        Thread.sleep(1000);
      } catch (final InterruptedException ex) {
        break;
      }
    }
  }