Beispiel #1
0
 public static void main(String[] args) throws Exception {
   if (args.length != 2) {
     System.out.println("arguments: sourcefile destfile");
     System.exit(1);
   }
   FileChannel in = new FileInputStream(args[0]).getChannel(),
       out = new FileOutputStream(args[1]).getChannel();
   in.transferTo(0, in.size(), out);
   // Or:
   // out.transferFrom(in, 0, in.size());
 }
 public void start() {
   try {
     domainStartTime = System.currentTimeMillis();
     messageIO.start();
     listener = new TcpServer(listenPort);
     listener.registerAcceptCallback(this);
     listener.start();
   } catch (Exception e) {
     Log.exception("DomainServer listener", e);
     System.exit(1);
   }
 }
Beispiel #3
0
  public static void main(String args[]) throws IOException {
    if (args.length != 1) {
      System.err.println("Usage: java LockingExample <input file>");
      System.exit(0);
    }

    FileLock sharedLock = null;
    FileLock exclusiveLock = null;

    try {
      RandomAccessFile raf = new RandomAccessFile(args[0], "rw");

      // get the channel for the file
      FileChannel channel = raf.getChannel();

      System.out.println("trying to acquire lock ...");
      // this locks the first half of the file - exclusive
      exclusiveLock = channel.lock(0, raf.length() / 2, SHARED);
      System.out.println("lock acquired ...");

      /** Now modify the data . . . */
      try {
        // sleep for 10 seconds
        Thread.sleep(10000);
      } catch (InterruptedException ie) {
      }

      // release the lock
      exclusiveLock.release();
      System.out.println("lock released ...");

      // this locks the second half of the file - shared
      sharedLock = channel.lock(raf.length() / 2 + 1, raf.length(), SHARED);

      /** Now read the data . . . */

      // release the lock
      sharedLock.release();
    } catch (java.io.IOException ioe) {
      System.err.println(ioe);
    } finally {
      if (exclusiveLock != null) exclusiveLock.release();
      if (sharedLock != null) sharedLock.release();
    }
  }
Beispiel #4
0
 private static void usage() {
   System.out.println("NAME");
   System.out.println("       HCIOTest - loop writing/reading/comparing data to/from files ");
   System.out.println("       mimicing Honeycomb's IO patterns");
   System.out.println();
   System.out.println("SYNOPSIS");
   System.out.println("       java HCIOTest Tempfile Permfile Size");
   System.err.println();
   System.out.println("DESCRIPTION");
   System.out.println("       HCIOTest takes three parameters:");
   System.out.println("         the complete path of the temporary file to be written");
   System.out.println("         the complete path of the permanent file");
   System.out.println("         the size of the file which must be a multiple of 4096");
   System.out.println();
   System.out.println("EXAMPLES");
   System.out.println("       java HCIOTest /data/tmp/tempfile0 /data/testfile0 102400");
   System.exit(1);
 }
  public static void main(String args[]) {
    if (args.length != 1) {
      System.out.println("Usage: java FastStreamCopy filename");
      System.exit(1);
    }

    NumberFormat digits = NumberFormat.getInstance();
    digits.setMaximumFractionDigits(3);

    long before;
    long after;
    double slowTime;
    double fastTime;
    double speedUp;

    String filename = args[0];
    String contents;

    // Slow method
    System.out.println("Reading file " + args[0] + " using slow method");
    before = System.currentTimeMillis(); // Start timing
    // contents = slowStreamCopy(filename);
    contents = readFile(filename);
    after = System.currentTimeMillis(); // End timing
    slowTime = after - before;
    // System.out.println("File's contents:\n" + contents);

    // Fast method
    System.out.println("Reading file " + args[0] + " using fast method");
    before = System.currentTimeMillis(); // Start timing
    contents = fastStreamCopy(filename);
    after = System.currentTimeMillis(); // End timing
    fastTime = after - before;
    // System.out.println("File's contents:\n" + contents);

    // Comparison
    speedUp = 100d * slowTime / fastTime;
    System.out.println("Slow method required " + slowTime + " ms.");
    System.out.println("Fast method required " + fastTime + " ms.");
    System.out.print("Speed up = " + digits.format(speedUp) + "% ");
    System.out.println(speedUp > 100 ? "Good!" : "Bad!");
  }
 public static void startRDPServer() {
   if (rdpServerStarted) return;
   rdpServerStarted = true;
   rdpServerThread = new Thread(rdpServer, "RDPServer");
   retryThread = new Thread(new RetryThread(), "RDPRetry");
   packetCallbackThread = new Thread(new PacketCallbackThread(), "RDPCallback");
   if (Log.loggingNet) Log.net("static - starting rdpserver thread");
   try {
     selector = Selector.open();
   } catch (Exception e) {
     Log.exception("RDPServer caught exception opening selector", e);
     System.exit(1);
   }
   rdpServerThread.setPriority(rdpServerThread.getPriority() + 2);
   if (Log.loggingDebug)
     Log.debug(
         "RDPServer: starting rdpServerThread with priority " + rdpServerThread.getPriority());
   rdpServerThread.start();
   retryThread.start();
   packetCallbackThread.start();
 }
Beispiel #7
0
 private static void usage() {
   System.out.println(
       "Usage:  Server <type> [options]\n"
           + "	type:\n"
           + "		B1	Blocking/Single-threaded Server\n"
           + "		BN	Blocking/Multi-threaded Server\n"
           + "		BP	Blocking/Pooled-Thread Server\n"
           + "		N1	Nonblocking/Single-threaded Server\n"
           + "		N2	Nonblocking/Dual-threaded Server\n"
           + "\n"
           + "	options:\n"
           + "		-port port		port number\n"
           + "		    default:  "
           + PORT
           + "\n"
           + "		-backlog backlog	backlog\n"
           + "		    default:  "
           + BACKLOG
           + "\n"
           + "		-secure			encrypt with SSL/TLS");
   System.exit(1);
 }
Beispiel #8
0
  /** @param args */
  public static void main(String[] args) {
    FileChannel fc = null;
    RandomAccessFile raf = null;
    // StringBuilder sb;

    if (args.length != 1) {
      System.out.println("Usage: Ntfs filename");
      System.exit(1);
    }
    /*
    sb = new StringBuilder();
    int[] foo = {129,4,229,33};
    for (int b: foo) {
        sb.insert(0,String.format("%02X", b));
    }
    System.out.println(sb.toString());
    System.exit(0);
    */
    try {
      raf = new RandomAccessFile(args[0], "r");
      fc = raf.getChannel();
      Filesystem fs = new Filesystem(fc);

      fs.demo();
      // fs.displayFs();
    } catch (FileNotFoundException x) {
      System.out.println("FNF exp: " + x.getMessage());
    } catch (IOException x) {
      System.out.println("IO exp: " + x.getMessage());
    } finally {
      if (raf != null)
        try {
          raf.close();
        } catch (IOException e) {
          e.printStackTrace(); // To change body of catch statement use File | Settings | File
          // Templates.
        }
    }
  }
Beispiel #9
0
  public static void main(String[] argv) {
    if (argv.length != 3) {
      usage();
    }

    String tempFile = argv[0];
    String testFile = argv[1];
    int fileSize = Integer.valueOf(argv[2]).intValue();
    int exitcode = 0;
    int numRead;
    int numThisBuf;
    int numWritten;

    if ((fileSize <= 0) || (fileSize % 4096 != 0)) {
      System.out.println("Error: size is not a multiple of 4096!!!!!!");
      System.out.println();
      usage();
    }

    try {
      int bufSize = 4096;
      byte[] inBytes = new byte[bufSize];
      byte[] outBytes = new byte[bufSize];
      Random ioRandom = new Random(2006);
      ioRandom.nextBytes(outBytes);
      ByteBuffer inBuf = ByteBuffer.allocate(bufSize);
      ByteBuffer outBuf = ByteBuffer.wrap(outBytes);

      //
      // Loop forever
      //
      while (true) {
        //
        // Write the temporary file
        //
        FileOutputStream fos = new FileOutputStream(tempFile);
        FileChannel foc = fos.getChannel();
        numWritten = 0;
        while (numWritten < fileSize) {
          outBuf.clear(); // sets limit to capacity & position to zero
          while (outBuf.hasRemaining()) {
            numWritten += foc.write(outBuf);
          }
        }

        //
        // Move to permanent location
        //
        FileChannel srcChannel = new FileInputStream(tempFile).getChannel();
        FileChannel dstChannel = new FileOutputStream(testFile).getChannel();
        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
        srcChannel.close();
        dstChannel.close();
        boolean success = (new File(tempFile)).delete();
        if (!success) {
          System.out.println("Warning: unable to delete temporary file");
        }

        //
        // Read and compare
        //
        FileInputStream fis = new FileInputStream(testFile);
        FileChannel fic = fis.getChannel();

        for (numRead = 0, numThisBuf = 0; numRead < fileSize; numThisBuf = 0) {
          inBuf.rewind(); // Set the buffer position to 0
          numThisBuf = fic.read(inBuf);
          while (numThisBuf < bufSize) {
            numThisBuf += fic.read(inBuf);
          }
          numRead += bufSize;
          inBuf.rewind(); // Set the buffer position to 0
          inBuf.get(inBytes);
          boolean same = Arrays.equals(inBytes, outBytes);
          if (same = false) {
            System.out.println("Data read does not equal data written at " + numRead + " bytes");
          }
        }
      }

    } catch (FileNotFoundException fnfe) {
      fnfe.printStackTrace(System.err);
      exitcode = 1;
      // break;
    } catch (SecurityException se) {
      se.printStackTrace(System.err);
      exitcode = 1;
      // break;
    } catch (Throwable t) {
      t.printStackTrace(System.err);
      exitcode = 1;
    }

    System.exit(exitcode);
  }
  public static void main(String args[]) {
    String worldName = System.getProperty("multiverse.worldname");
    Properties properties = InitLogAndPid.initLogAndPid(args, worldName, null);

    System.err.println("Multiverse server version " + ServerVersion.getVersionString());

    List<String> agentNames = new LinkedList<String>();

    LongOpt[] longopts = new LongOpt[2];
    longopts[0] = new LongOpt("pid", LongOpt.REQUIRED_ARGUMENT, null, 2);
    longopts[1] = new LongOpt("port", LongOpt.REQUIRED_ARGUMENT, null, 3);
    Getopt opt = new Getopt("DomainServer", args, "a:m:t:p:P:", longopts);
    int c;
    int port = DEFAULT_PORT;

    String portStr = properties.getProperty("multiverse.msgsvr_port");
    if (portStr != null) port = Integer.parseInt(portStr);

    PluginStartGroup pluginStartGroup = new PluginStartGroup();

    while ((c = opt.getopt()) != -1) {
      switch (c) {
        case 'a':
          agentNames.add(opt.getOptarg());
          break;
        case 't':
        case 'm':
          // ignore RuntimeMarshalling flags
          opt.getOptarg();
          break;
        case 'p':
          String pluginSpec = opt.getOptarg();
          String[] pluginDef = pluginSpec.split(",", 2);
          if (pluginDef.length != 2) {
            System.err.println("Invalid plugin spec format: " + pluginSpec);
            Log.error("Invalid plugin spec format: " + pluginSpec);
            System.exit(1);
          }
          int expected = Integer.parseInt(pluginDef[1]);
          pluginStartGroup.add(pluginDef[0], expected);
          break;
        case '?':
          System.exit(1);
          break;
        case 'P':
          break;
        case 2:
          // ignore --pid
          opt.getOptarg();
          break;
          // port
        case 3:
          String arg = opt.getOptarg();
          port = Integer.parseInt(arg);
          break;
        default:
          break;
      }
    }

    String svrName = System.getProperty("multiverse.loggername");
    String runDir = System.getProperty("multiverse.rundir");

    // Windows non-Cygwin only - save process ID for status script
    if (System.getProperty("os.name").contains("Windows") && svrName != null && runDir != null) {
      saveProcessID(svrName, runDir);
    }

    // parse command-line options

    domainServer = new DomainServer(port);
    domainServer.setAgentNames(agentNames);
    domainServer.setWorldName(worldName);
    domainServer.start();

    pluginStartGroup.prepareDependencies(properties, worldName);
    domainServer.addPluginStartGroup(pluginStartGroup);
    pluginStartGroup.pluginAvailable("Domain", "Domain");

    String timeoutStr = properties.getProperty("multiverse.startup_timeout");
    int timeout = 120;
    if (timeoutStr != null) {
      timeout = Integer.parseInt(timeoutStr);
    }

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    ScheduledFuture<?> timeoutHandler =
        scheduler.schedule(new TimeoutRunnable(timeout), timeout, TimeUnit.SECONDS);

    javax.crypto.SecretKey domainKey = SecureTokenUtil.generateDomainKey();
    // XXX Use a random keyID for now. Ideally, this would be semi-unique.
    long keyId = new Random().nextLong();
    encodedDomainKey = Base64.encodeBytes(SecureTokenUtil.encodeDomainKey(keyId, domainKey));
    Log.debug("generated domain key: " + encodedDomainKey);

    try {
      pluginStartGroup.awaitDependency("Domain");
      timeoutHandler.cancel(false);
      String availableMessage = properties.getProperty("multiverse.world_available_message");
      String availableFile = properties.getProperty("multiverse.world_available_file");
      if (availableFile != null) touchFile(FileUtil.expandFileName(availableFile));
      if (availableMessage != null) System.err.println("\n" + availableMessage);
      while (true) {
        Thread.sleep(10000000);
      }
    } catch (Exception ex) {
      Log.exception("DomainServer.main", ex);
    }
  }
Beispiel #11
0
  public static void readCommand() {
    try {

      if (!reader.ready()) {
        return;
      }

      StringTokenizer tokens = new StringTokenizer(reader.readLine());

      if (tokens.hasMoreTokens()) {

        switch (tokens.nextToken()) {
          case "/listen":
            listen(tokens);
            break;

          case "/stop":
            stop();
            break;

          case "/list":
            if (port[0] == -1) {
              System.err.println("Error: start listening before");
            }

            for (Entry<String, SocketChannel> client : clients.entrySet()) {
              System.out.println(client.getKey());
            }

            if (clients.entrySet().isEmpty()) {
              System.out.println("list: no clients online");
            }
            break;

          case "/send":
            if (tokens.hasMoreTokens()) {
              String name = tokens.nextToken();
              if (clients.containsKey(name)) {
                if (tokens.hasMoreTokens()) {
                  sendMessage(
                      clients.get(name),
                      MessageUtils.message("<server>", getMessageFromTokens(tokens)));
                } else {
                  System.err.println("send: message is empty");
                }
              } else {
                System.err.println("send: no such client");
              }
            } else {
              System.err.println("send: no client name");
            }
            break;

          case "/sendall":
            if (tokens.hasMoreTokens()) {
              notifyAllClients(getMessageFromTokens(tokens));
            } else {
              System.err.println("sendall: message is empty");
            }
            break;

          case "/kill":
            kill(tokens);
            break;

          case "/exit":
            if (port[0] != -1) {
              stop();
            }
            Utils.tryClose(selector);
            System.exit(0);
            break;

          default:
            System.err.print("Error: unknown command");
            break;
        }

      } else {
        System.err.println("Error: empty input");
      }

    } catch (Exception expt) {
      Utils.printErrorAndExit(expt.getMessage());
    }
  }