Example #1
0
class DaemonThreadFactory implements ThreadFactory {

  static final ThreadFactory INSTANCE = new DaemonThreadFactory();

  private static final ThreadFactory DEFAULT = Executors.defaultThreadFactory();

  public Thread newThread(Runnable r) {
    Thread t = DEFAULT.newThread(r);
    t.setDaemon(true);
    return t;
  }
}
Example #2
0
  /**
   * Create the HttpServer to use. Can be overridden if a custom or already existing HttpServer
   * should be used
   *
   * @return HttpServer to use
   * @throws IOException if something fails during the initialisation
   */
  private HttpServer createHttpServer(JolokiaServerConfig pConfig) throws IOException {
    int port = pConfig.getPort();
    InetAddress address = pConfig.getAddress();
    InetSocketAddress socketAddress = new InetSocketAddress(address, port);

    HttpServer server =
        pConfig.useHttps()
            ? createHttpsServer(socketAddress, pConfig)
            : HttpServer.create(socketAddress, pConfig.getBacklog());

    // Prepare executor pool
    Executor executor;
    String mode = pConfig.getExecutor();
    if ("fixed".equalsIgnoreCase(mode)) {
      executor = Executors.newFixedThreadPool(pConfig.getThreadNr(), daemonThreadFactory);
    } else if ("cached".equalsIgnoreCase(mode)) {
      executor = Executors.newCachedThreadPool(daemonThreadFactory);
    } else {
      executor = Executors.newSingleThreadExecutor(daemonThreadFactory);
    }
    server.setExecutor(executor);

    return server;
  }
Example #3
0
  public static void main(String[] args) throws Exception {
    HttpServer s1 = null;
    HttpsServer s2 = null;
    ExecutorService executor = null;
    try {
      String root = System.getProperty("test.src") + "/docs";
      System.out.print("Test12: ");
      InetSocketAddress addr = new InetSocketAddress(0);
      s1 = HttpServer.create(addr, 0);
      s2 = HttpsServer.create(addr, 0);
      HttpHandler h = new FileServerHandler(root);
      HttpContext c1 = s1.createContext("/test1", h);
      HttpContext c2 = s2.createContext("/test1", h);
      executor = Executors.newCachedThreadPool();
      s1.setExecutor(executor);
      s2.setExecutor(executor);
      ctx = new SimpleSSLContext(System.getProperty("test.src")).get();
      s2.setHttpsConfigurator(new HttpsConfigurator(ctx));
      s1.start();
      s2.start();

      int port = s1.getAddress().getPort();
      int httpsport = s2.getAddress().getPort();
      Runner r[] = new Runner[8];
      r[0] = new Runner(true, "http", root + "/test1", port, "smallfile.txt", 23);
      r[1] = new Runner(true, "http", root + "/test1", port, "largefile.txt", 2730088);
      r[2] = new Runner(true, "https", root + "/test1", httpsport, "smallfile.txt", 23);
      r[3] = new Runner(true, "https", root + "/test1", httpsport, "largefile.txt", 2730088);
      r[4] = new Runner(false, "http", root + "/test1", port, "smallfile.txt", 23);
      r[5] = new Runner(false, "http", root + "/test1", port, "largefile.txt", 2730088);
      r[6] = new Runner(false, "https", root + "/test1", httpsport, "smallfile.txt", 23);
      r[7] = new Runner(false, "https", root + "/test1", httpsport, "largefile.txt", 2730088);
      start(r);
      join(r);
      System.out.println("OK");
    } finally {
      delay();
      if (s1 != null) s1.stop(2);
      if (s2 != null) s2.stop(2);
      if (executor != null) executor.shutdown();
    }
  }
Example #4
0
 public void run() {
   System.out.println("JSSE Server listening on port " + cipherTest.serverPort);
   Executor exec = Executors.newFixedThreadPool(cipherTest.THREADS, DaemonThreadFactory.INSTANCE);
   try {
     while (true) {
       final SSLSocket socket = (SSLSocket) serverSocket.accept();
       socket.setSoTimeout(cipherTest.TIMEOUT);
       Runnable r =
           new Runnable() {
             public void run() {
               try {
                 InputStream in = socket.getInputStream();
                 OutputStream out = socket.getOutputStream();
                 handleRequest(in, out);
                 out.flush();
                 socket.close();
                 socket.getSession().invalidate();
               } catch (IOException e) {
                 cipherTest.setFailed();
                 e.printStackTrace();
               } finally {
                 if (socket != null) {
                   try {
                     socket.close();
                   } catch (IOException e) {
                     cipherTest.setFailed();
                     System.out.println("Exception closing socket on server side:");
                     e.printStackTrace();
                   }
                 }
               }
             }
           };
       exec.execute(r);
     }
   } catch (IOException e) {
     cipherTest.setFailed();
     e.printStackTrace();
     //
   }
 }
Example #5
0
public class FileDescLoader {
  private static final Logger log = LoggerFactory.getLogger(FileDescLoader.class);
  private static final ExecutorService exec = Executors.newCachedThreadPool();

  public static void load(Collection<FileDesc> files, Path root, int blocSize, Pattern pattern)
      throws IOException {
    root = root.toAbsolutePath().normalize();
    Visitor visitor = new Visitor(root, blocSize, pattern);
    Files.walkFileTree(root, visitor);
    for (Future<FileDesc> future : visitor.futures()) {
      try {
        files.add(future.get());
      } catch (Exception e) {
        log.error("", e);
      }
    }
  }

  /** @return matching bloc B bloc -> A bloc */
  public static Map<Integer, Integer> diff(FileDesc a, FileDesc b) {
    Map<Integer, List<IndexedHash>> blocA = new HashMap<Integer, List<IndexedHash>>();
    int i = 0;
    for (Bloc bloc : a.blocs) {
      List<IndexedHash> l = blocA.get(bloc.roll);
      if (l == null) {
        l = new ArrayList<IndexedHash>();
        blocA.put(bloc.roll, l);
      }
      l.add(new IndexedHash(i++, bloc.hash));
    }

    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    loop:
    for (i = 0; i < b.blocs.length; i++) {
      Bloc blocB = b.blocs[i];
      List<IndexedHash> list = blocA.get(blocB.roll);
      if (list != null) {
        for (IndexedHash bloc : list) {
          if (blocB.hash.equals(bloc.h)) {
            map.put(i, bloc.i);
            continue loop;
          }
        }
      }
    }
    return map;
  }

  public static FileDesc loadFile(Path root, Path file, int blocSize)
      throws NoSuchAlgorithmException, FileNotFoundException, IOException {
    MessageDigest md = MessageDigest.getInstance("SHA-512");
    MessageDigest fileMd = MessageDigest.getInstance("SHA-512");

    FileDesc desc = new FileDesc(file.toString(), null, null);
    List<Bloc> list = new ArrayList<Bloc>();
    try (FileInputStream fis = new FileInputStream(root.resolve(file).toString())) {
      byte[] buf = new byte[blocSize];
      byte[] h;
      int s;
      while ((s = fis.read(buf)) != -1) {
        int c;
        while (s < buf.length && (c = fis.read()) != -1) buf[s++] = (byte) c;
        fileMd.update(buf, 0, s);

        // padding
        byte p = 0;
        while (s < buf.length) buf[s++] = ++p;
        h = md.digest(buf);
        Bloc bloc = new Bloc(RollingChecksum.compute(buf), new Hash(h));
        list.add(bloc);
      }
      h = fileMd.digest();
      desc.fileHash = new Hash(h);
      desc.blocs = list.toArray(new Bloc[0]);
    }
    return desc;
  }

  private static class Visitor implements FileVisitor<Path> {
    private Path root;
    private int blocSize;
    private Matcher m;
    private List<Future<FileDesc>> futures = new ArrayList<>();

    public Visitor(Path root, int blocFile, Pattern pattern) {
      this.root = root;
      this.blocSize = blocFile;
      this.m = pattern == null ? null : pattern.matcher("");
    }

    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
        throws IOException {
      if (m != null) m.reset(root.relativize(dir).toString());
      return m == null || m.matches() || m.hitEnd()
          ? FileVisitResult.CONTINUE
          : FileVisitResult.SKIP_SUBTREE;
    }

    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
      if (attrs.isRegularFile()) {
        if (m != null) m.reset(root.relativize(file).toString());
        if (m == null || m.matches())
          futures.add(exec.submit(new FileLoader(root, file, blocSize)));
      }
      return FileVisitResult.CONTINUE;
    }

    public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
      return FileVisitResult.CONTINUE;
    }

    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
      return FileVisitResult.CONTINUE;
    }

    public List<Future<FileDesc>> futures() {
      return futures;
    }
  }

  private static class FileLoader implements Callable<FileDesc> {
    private Path file;
    private int blocSize;
    private Path root;

    public FileLoader(Path root, Path file, int blocSize) throws IOException {
      this.root = root;
      this.file = file;
      this.blocSize = blocSize;
    }

    public FileDesc call() throws Exception {
      return loadFile(root, root.relativize(file), blocSize);
    }
  }

  public static class IndexedHash {
    public int i;
    public Hash h;

    public IndexedHash(int i, Hash h) {
      this.i = i;
      this.h = h;
    }
  }
}
 public static Executor getExecutor() {
   if (executor == null) executor = Executors.newFixedThreadPool(4);
   return executor;
 }