/**
   * Creates a new Server object.
   *
   * @param sqlDriver JDBC driver
   * @param dbURL JDBC connection url
   * @param dbLogin database login
   * @param dbPasswd database password
   */
  private Server(ServerConfig config) {
    Server.instance = this;
    this.connections = new ArrayList();
    this.services = new ArrayList();
    this.port = config.getPort();
    this.socket = null;
    this.dbLayer = null;

    try {
      dbLayer = DatabaseAbstractionLayer.createLayer(config);
      Logging.getLogger().finer("dbLayer   : " + dbLayer);

      this.store = new Store(config);
    } catch (Exception ex) {
      Logging.getLogger().severe("#Err > Unable to connect to the database : " + ex.getMessage());
      ex.printStackTrace();
      System.exit(1);
    }

    try {
      this.serverIp = InetAddress.getLocalHost().getHostAddress();
      this.socket = new ServerSocket(this.port);
    } catch (IOException e) {
      Logging.getLogger().severe("#Err > Unable to listen on the port " + port + ".");
      e.printStackTrace();
      System.exit(1);
    }

    loadInternalServices();
  }
  /**
   * Main Method
   *
   * @param args command line arguments
   */
  public static void main(String[] args) {
    // init logging
    try {
      Logging.init("lucane.log", "ALL");
    } catch (IOException ioe) {
      System.err.println("Unable to init logging, exiting.");
      System.exit(1);
    }

    Server server = null;
    ServerConfig config = null;

    try {
      config = new ServerConfig(CONFIG_FILE);
    } catch (Exception e) {
      Logging.getLogger().severe("Unable to read or parse the config file.");
      e.printStackTrace();
      System.exit(1);
    }

    // Server creation
    server = new Server(config);
    server.generateKeys();
    Logging.getLogger().info("Server is ready.");
    server.run();
  }
Beispiel #3
0
 public void disconnect(String name, I_InfoPlayer player) {
   try {
     Naming.unbind("rmi://" + serverInfo.getIpAddr() + ":1099/I_InfoGame");
     Naming.unbind("rmi://" + serverInfo.getIpAddr() + ":1099/" + name);
   } catch (Exception e) {
     System.out.println("Failed unbind");
     System.exit(128);
   }
   System.out.println("Disconnected");
   ServerTimer timer = new ServerTimer(5);
   Thread thread = new Thread(timer);
   thread.start();
   while (!timer.finished()) ;
   timer.shutDown();
   timer = null;
   System.gc();
   try {
     Naming.rebind("rmi://" + serverAddress + ":1099/I_InfoGame", game);
     Naming.rebind("rmi://" + serverAddress + ":1099/" + name, player);
   } catch (Exception e) {
     System.out.println("Failed rebind");
     System.exit(128);
   }
   System.out.println("Reconnected");
 }
Beispiel #4
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);
  }
  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);
      }
    }
  }
Beispiel #6
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;
      }
    }
  }
Beispiel #7
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;
 }
  public static void main(String[] args) {
    int myMark;

    if (args.length == 0) {
      System.out.println("must enter your name");
      System.exit(1);
    }

    String myName = args[0];

    try {
      TicTacToeInterface game = (TicTacToeInterface) java.rmi.Naming.lookup("tic-tac-toe");
      int status = game.register(myName);
      TTTClient client = new TTTClient(game, status);
      game.setPlayer(client);

      if (status == -1) {
        System.out.println("Two players already registered");
        System.exit(1);
      }

      myMark = (status == 0 ? MARK_X : MARK_O);

      client.go(); // game thread

    } catch (Exception e) {
      System.out.println(e);
    }
  }
Beispiel #9
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);
    }
  }
Beispiel #10
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);
    }
  }
 /**
  * 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.");
   }
 }
Beispiel #12
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);
 }
Beispiel #13
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);
    }
  }
Beispiel #14
0
  public static void main(String[] args) {

    if (args.length == 1) {
      if (args[0].equals("-genkey")) {
        try {
          CipherUtils.generateKey();
        } catch (KeyStoreException
            | CertificateException
            | NoSuchAlgorithmException
            | IOException e) {
          e.printStackTrace();
        }
        System.exit(0);
      } else {
        System.exit(-1);
      }
    }

    try {
      Socket s = new Socket("localhost", Servidor.PORT);

      ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
      ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
      CipherUtils cipherUtils = new CipherUtils(ois, oos);
      String test;
      BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
      while ((test = stdIn.readLine()) != null) {
        cipherUtils.encrypt(test);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  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);
  }
Beispiel #16
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);
      }
    }
  }
 /**
  * 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);
   }
 }
Beispiel #18
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();
  }
  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.");
    }
  }
Beispiel #20
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");
 }
Beispiel #21
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;
   }
 }
Beispiel #22
0
  public static void main(String[] args) throws IOException {

    ServerSocket serverSocket = null;
    try {
      serverSocket = new ServerSocket(PORT);
    } catch (IOException e) {
      System.err.println("Could not listen on port: " + PORT + ".");
      System.exit(1);
    }

    while (true) {

      Socket clientSocket = null;
      try {
        clientSocket = serverSocket.accept();
        startTime = System.currentTimeMillis();
      } catch (IOException e) {
        System.err.println("Accept failed.");
        System.exit(1);
      }

      PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
      BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
      String inputLine, outputLine;

      while ((inputLine = in.readLine()) != null) {

        if (messageCount.get(clientSocket) == null) {
          messageCount.put(clientSocket, 1);
        } else {
          messageCount.put(clientSocket, messageCount.get(clientSocket) + 1);
        }

        overallMessageCount += 1;
        System.out.println("---------------------------------------");
        System.out.println("Client: " + clientSocket.toString());
        System.out.println(
            "aktive since " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds");
        System.out.println(new Date(System.currentTimeMillis()));
        System.out.println("Overall Message Count: " + overallMessageCount);
        System.out.println("Message Count from Client: " + messageCount.get(clientSocket));
        System.out.println("Message " + inputLine);
        System.out.println("---------------------------------------");
        outputLine = inputLine.toUpperCase();

        if (outputLine.equals("END")) {
          out.println("abort");
          break;
        }
        out.println(outputLine);
      }
      out.close();
      in.close();
      clientSocket.close();

      System.out.println("All Closed");
    }
    // serverSocket.close();
  }
Beispiel #23
0
  public Cedars(String args[]) throws ArchiveException, IOException, HoneycombTestException {

    verbose = false;

    parseArgs(args);
    initHCClient(host);

    // generate lists of random sizes around 30M and 3M
    // sort ascending to allow continuous expansion
    try {
      initRandom();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
    sizes = new long[n_files];
    for (int i = 0; i < sizes.length; i++) {
      sizes[i] = MIN_SIZE + (long) (rand.nextDouble() * (double) RANGE);
    }
    Arrays.sort(sizes);

    sizes2 = new long[n_files];
    for (int i = 0; i < sizes2.length; i++) {
      sizes2[i] = MIN_SIZE2 + (long) (rand.nextDouble() * (double) RANGE2);
    }
    Arrays.sort(sizes2);

    sizes3 = new long[n_files];
    for (int i = 0; i < sizes3.length; i++) {
      sizes3[i] = MIN_SIZE3 + (long) (rand.nextDouble() * (double) RANGE3);
    }
    Arrays.sort(sizes3);

    oids = new String[n_files];
    Arrays.fill(oids, null);
    shas = new String[n_files];
    Arrays.fill(shas, null);

    if (out_file != null) {
      try {
        String host = clnthost;
        fo = new FileWriter(out_file, true); // append=true
        flog("#S Cedars [" + host + "] " + new Date() + "\n");
      } catch (Exception e) {
        System.err.println("Opening " + out_file);
        e.printStackTrace();
        System.exit(1);
      }
    }
    Runtime.getRuntime().addShutdownHook(new Thread(new Shutdown(), "Shutdown"));
    doIt();

    done = true;
  }
Beispiel #24
0
  public static void main(String args[]) {
    int port;
    String host;

    if (args.length == 1) {
      try {
        port = Integer.parseInt(args[0]);

        doEcho(port);

      } catch (IOException io_ex) {
        io_ex.printStackTrace();
        System.exit(1);

      } catch (NumberFormatException num_ex) {
        num_ex.printStackTrace();
        System.exit(1);
      }
    } else if (args.length == 2) {
      try {
        host = args[0];
        port = Integer.parseInt(args[1]);

        UDPEcho ut = new UDPEcho(host, port);
        Thread thread = new Thread(ut);
        thread.start();

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String s;
        System.out.print("Enter datagram:");
        s = in.readLine();
        while (s != null) {
          ut.send(s);
          try {
            Thread.currentThread().sleep(100);
          } catch (InterruptedException i_ex) {
          }
          System.out.print("Enter datagram:");
          s = in.readLine();
        }
        System.exit(1);

      } catch (IOException io_ex) {
        io_ex.printStackTrace();
        System.exit(1);
      } catch (NumberFormatException num_ex) {
        num_ex.printStackTrace();
        System.exit(1);
      }

    } else {
      usage();
    }
  }
Beispiel #25
0
  public static void clearTable() {
    connectDb();
    String sql = "delete from " + tablename + ";";
    try {
      query.executeUpdate(sql);

    } catch (SQLException e) {
      System.out.println("SQL Exception: " + e);
      System.exit(1);
    }
    System.out.println("Table Cleared Successfully");
  }
  public static void main(String[] args) {
    Socket socket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    BufferedReader userInputStream = null;
    String IP = "127.0.0.1";
    final int PORT_NUM = 4444;
    try {
      socket = new Socket(IP, PORT_NUM);
      out = new PrintWriter(socket.getOutputStream(), true);
      in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (UnknownHostException e) {
      System.out.println("Unknown host:" + IP + " at port: " + PORT_NUM);
      e.printStackTrace();
      System.exit(0);
    } catch (IOException e) {
      System.out.println("Cannot connect to server...");
      e.printStackTrace();
      System.exit(0);
    }
    String userInput, fromServer;
    try {
      userInputStream = new BufferedReader(new InputStreamReader(System.in));
      while ((fromServer = in.readLine()) != null) {
        System.out.println("Server: " + fromServer);
        if (fromServer.equals(":q")) break;

        userInput = userInputStream.readLine();
        Calendar cal = Calendar.getInstance();
        cal.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        if (userInput != null) {
          out.println(userInput + " (sent at " + (sdf.format(cal.getTime())) + ")");
        }
      }
    } catch (IOException e) {
      System.out.println("Could not access data from client printstream...");
      e.printStackTrace();
      System.exit(0);
    }
    try {
      out.close();
      in.close();
      userInputStream.close();
      socket.close();
      System.out.println("I love you, bye.");
      System.out.println("Terminating client...");
    } catch (IOException e) {
      System.out.println("Socket and stream closing error...");
      e.printStackTrace();
      System.exit(0);
    }
  }
  public static void main(String[] args) throws Exception {
    Class thisClass = MethodResultTest.class;
    Class exoticClass = Exotic.class;
    String exoticClassName = Exotic.class.getName();
    ClassLoader testClassLoader = thisClass.getClassLoader();
    if (!(testClassLoader instanceof URLClassLoader)) {
      System.out.println("TEST INVALID: Not loaded by a " + "URLClassLoader: " + testClassLoader);
      System.exit(1);
    }

    URLClassLoader tcl = (URLClassLoader) testClassLoader;
    URL[] urls = tcl.getURLs();
    ClassLoader shadowLoader =
        new ShadowLoader(
            urls,
            testClassLoader,
            new String[] {
              exoticClassName, ExoticMBeanInfo.class.getName(), ExoticException.class.getName()
            });
    Class cl = shadowLoader.loadClass(exoticClassName);
    if (cl == exoticClass) {
      System.out.println(
          "TEST INVALID: Shadow class loader loaded " + "same class as test class loader");
      System.exit(1);
    }
    Thread.currentThread().setContextClassLoader(shadowLoader);

    ObjectName on = new ObjectName("a:b=c");
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    mbs.createMBean(Thing.class.getName(), on);

    final String[] protos = {"rmi", "iiop", "jmxmp"};

    boolean ok = true;
    for (int i = 0; i < protos.length; i++) {
      try {
        ok &= test(protos[i], mbs, on);
        System.out.println();
      } catch (Exception e) {
        System.out.println("TEST FAILED WITH EXCEPTION:");
        e.printStackTrace(System.out);
        ok = false;
      }
    }

    if (ok) System.out.println("Test passed");
    else {
      System.out.println("TEST FAILED");
      System.exit(1);
    }
  }
Beispiel #28
0
  /** Main client entry point for stand-alone operation. */
  public static void main(String[] args) {
    BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%d [%-25t] %-5p: %m%n")));

    CmdLineParser parser = new CmdLineParser();
    CmdLineParser.Option help = parser.addBooleanOption('h', "help");
    CmdLineParser.Option output = parser.addStringOption('o', "output");
    CmdLineParser.Option iface = parser.addStringOption('i', "iface");

    try {
      parser.parse(args);
    } catch (CmdLineParser.OptionException oe) {
      System.err.println(oe.getMessage());
      usage(System.err);
      System.exit(1);
    }

    // Display help and exit if requested
    if (Boolean.TRUE.equals(parser.getOptionValue(help))) {
      usage(System.out);
      System.exit(0);
    }

    String outputValue = (String) parser.getOptionValue(output, DEFAULT_OUTPUT_DIRECTORY);
    String ifaceValue = (String) parser.getOptionValue(iface);

    String[] otherArgs = parser.getRemainingArgs();
    if (otherArgs.length != 1) {
      usage(System.err);
      System.exit(1);
    }

    try {
      Client c = new Client(getIPv4Address(ifaceValue));
      SharedTorrent torrent =
          SharedTorrent.fromFile(new File(otherArgs[0]), new File(outputValue), false);
      c.addTorrent(torrent);

      // Set a shutdown hook that will stop the sharing/seeding and send
      // a STOPPED announce request.
      Runtime.getRuntime().addShutdownHook(new Thread(new ClientShutdown(c, null)));

      c.share();
      if (ClientState.ERROR.equals(torrent.getClientState())) {
        System.exit(1);
      }
    } catch (Exception e) {
      logger.error("Fatal error: {}", e.getMessage(), e);
      System.exit(2);
    }
  }
Beispiel #29
0
 public static void main(String[] argv) {
   int port;
   if (argv.length != 1) {
     System.out.println("Usage: java ChatServer [port number]");
     System.exit(0);
   }
   try {
     port = Integer.parseInt(argv[0]);
   } catch (Exception e) {
     System.err.println("Invalid port number");
     System.exit(1);
   }
   if (port == 0) port = DEFAULT_PORT;
   new ChatServer(port);
 } // main
Beispiel #30
0
  // Run method
  public void run(){
    exptStartTime = (new Date()).getTime();

    // create client to server (Event Listener)
    Socket socket = null;
    PrintWriter out = null;

    try {
      socket = new Socket (ipOfEventListener, portOfServer);
      out = new PrintWriter(socket.getOutputStream(), true);

      while (true){

        while (msgBuffer.lock.tryLock()) {
			// keep polling msgBuffer
	        while (!exptTimeUp() & msgBuffer.isEmpty())
	          ; // get stuck here until msgBuffer contains something or experiment period is up

	        

	        // send message to Event Listener & clear message buffer
	        out.println(msgBuffer.getWholeMsg());
	        System.out.println("Sent: "+ msgBuffer.getWholeMsg());
	        System.out.println("---");
	        msgBuffer.clear();
			msgBuffer.lock.unlock();
		}
		
		// exit if period for experiment is up
        if (exptTimeUp())
          break;

      }
      // Cleanup
      out.close();
      socket.close();
    }
    catch (IOException e) {
      System.err.println("*** FATAL ERROR: " + e.getMessage());
      System.err.println("*** LIKELY REASON: Make sure Push Server is up and listening at the correct IP address and port.");
      System.exit(1);
    }
    catch (Exception e){
      System.err.println("*** FATAL ERROR: " + e.getMessage());
      System.exit(1);
    }
    System.out.println("PushClient exited normally...");
  }