Example #1
1
  private void loop() {
    while (thread == Thread.currentThread()) {
      try {
        Request key = peekKey();
        if (key == null) throw new IOException("end of stream");
        synchronized (response_map) {
          Response response = (Response) response_map.get(key);
          if (response == null) {
            if (log.level >= 4) log.println("Invalid key, skipping message");
            doSkip();
          } else {
            doRecv(response);
            response.isReceived = true;
            response_map.notifyAll();
          }
        }
      } catch (Exception ex) {
        String msg = ex.getMessage();
        boolean timeout = msg != null && msg.equals("Read timed out");
        /* If just a timeout, try to disconnect gracefully
         */
        boolean hard = timeout == false;

        if (!timeout && log.level >= 3) ex.printStackTrace(log);

        try {
          disconnect(hard);
        } catch (IOException ioe) {
          ioe.printStackTrace(log);
        }
      }
    }
  }
  /** 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);
    }
  }
Example #3
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();
   }
 }
Example #4
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 #5
0
  public SSLResult fingerprint() throws IOException, FingerprintError {

    SSLConfigCollector scc;

    scc = new SSLConfigCollector(host, port, si);
    scc.setCertValidator(cv);

    startDate = new Date();

    sslSupport = SSLResult.UNKNOWN;

    // If a delay is set, wait some time, except for
    // the first request
    if (!initial && (delay > 0)) {
      if (Debug.get(Debug.Delay)) {
        System.err.println("Delaying request.");
      }
      try {
        Thread.sleep(delay);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
    }
    initial = false;

    try {
      scc.probe();
      sslSupport = SSLResult.SUPPORTED;
      sslSupportReason = null;
    } catch (NoSSLException e) {
      // This exception is thrown when the protocol support
      // for ssl is not available
      sslSupport = SSLResult.UNSUPPORTED;
      sslSupportReason = e.toString();
    } catch (FingerprintException e) {
      sslSupport = SSLResult.UNSUPPORTED;
      sslSupportReason = e.toString();
    } catch (IOException e) {
      sslSupport = SSLResult.UNKNOWN;
      sslSupportReason = e.toString();
    }
    endDate = new Date();

    protos = scc.getSupportedProtos();

    ProbeResult pres =
        new ProbeResult(
            host,
            port,
            startDate,
            endDate,
            sslSupport,
            sslSupportReason,
            scc.getServerCertificates(),
            scc.serverCertificateVerifies(),
            scc.serverCertNameMatch());

    pres.setProtosResult(protos);
    return pres;
  }
 /*
  * Receives votes from clients, passes them on to Voting
  * Notice that this has to happen over TCP instead of UDP to make voting reliable
  */
 public void run() {
   try {
     ServerSocket serverSocket = new ServerSocket();
     InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), VOTING_PORT);
     serverSocket.bind(address);
     serverSocket.setSoTimeout(200);
     while (!Thread.currentThread().isInterrupted()) {
       // TODO: May need to thread this further if client submissions get larger
       try {
         Socket socket = serverSocket.accept();
         BufferedReader reader =
             new BufferedReader(new InputStreamReader(socket.getInputStream()));
         String s = null;
         while ((s = reader.readLine()) != null) {
           voting.addVote(s);
           logger.log(Level.FINE, "Received vote for " + s);
         }
       } catch (SocketTimeoutException e) {
         logger.log(Level.FINE, "No votes received in 200ms interval");
       }
     }
   } catch (IOException ex) {
     logger.log(Level.SEVERE, null, ex);
   }
 }
    /** @param workTokDir Token directory (common for multiple nodes). */
    private void cleanupResources(File workTokDir) {
      RandomAccessFile lockFile = null;

      FileLock lock = null;

      try {
        lockFile = new RandomAccessFile(new File(workTokDir, LOCK_FILE_NAME), "rw");

        lock = lockFile.getChannel().lock();

        if (lock != null) processTokenDirectory(workTokDir);
        else if (log.isDebugEnabled())
          log.debug(
              "Token directory is being processed concurrently: " + workTokDir.getAbsolutePath());
      } catch (OverlappingFileLockException ignored) {
        if (log.isDebugEnabled())
          log.debug(
              "Token directory is being processed concurrently: " + workTokDir.getAbsolutePath());
      } catch (FileLockInterruptionException ignored) {
        Thread.currentThread().interrupt();
      } catch (IOException e) {
        U.error(log, "Failed to process directory: " + workTokDir.getAbsolutePath(), e);
      } finally {
        U.releaseQuiet(lock);
        U.closeQuiet(lockFile);
      }
    }
  /** Looks up the local database, creating if necessary. */
  private DataSource findDatabaseImpl(String url, String driverName) throws SQLException {
    try {
      synchronized (_databaseMap) {
        DBPool db = _databaseMap.get(url);

        if (db == null) {
          db = new DBPool();

          db.setVar(url + "-" + _gId++);

          DriverConfig driver = db.createDriver();

          ClassLoader loader = Thread.currentThread().getContextClassLoader();

          Class driverClass = Class.forName(driverName, false, loader);

          driver.setType(driverClass);
          driver.setURL(url);

          db.init();

          _databaseMap.put(url, db);
        }

        return db;
      }
    } catch (RuntimeException e) {
      throw e;
    } catch (SQLException e) {
      throw e;
    } catch (Exception e) {
      throw ConfigException.create(e);
    }
  }
Example #9
0
  @Override
  public void run() {

    nextTickTime = System.currentTimeMillis() + tickTime;
    // final String oldThreadName=Thread.currentThread().getName();
    try {
      currentThread = Thread.currentThread();
      lastStart = System.currentTimeMillis();
      lastClient = null;
      final boolean allSuspended = CMLib.threads().isAllSuspended();
      if ((CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)) && (!allSuspended)) {
        for (final Iterator<TickClient> i = tickers(); i.hasNext(); ) {
          final TickClient client = i.next();
          lastClient = client;
          // if(client.getCurrentTickDown()<=1)
          // currentThread.setName(oldThreadName+":"+getName()+":"+client.getName());
          if (client.tickTicker(false)) {
            delTicker(client); // cant do i.remove, its an streeset
          }
        }
      }
    } finally {
      lastStop = System.currentTimeMillis();
      milliTotal += (lastStop - lastStart);
      tickTotal++;
      currentThread = null;
      // Thread.currentThread().setName(oldThreadName);
    }
    if (tickers.size() == 0) {
      if (CMLib.threads() instanceof ServiceEngine)
        ((ServiceEngine) CMLib.threads()).delTickGroup(this);
    }
  }
  public void checkPermission(Permission perm) {
    StackTraceElement[] stack = Thread.currentThread().getStackTrace();
    boolean needsRestriction = false;
    String restrictor = "";
    for (int i = 3; i < stack.length; i++) {
      String clazz = stack[i].getClassName();
      String method = stack[i].getMethodName();
      if (clazz.equals("java.security.AccessController") && method.equals("doPrivileged")) {
        break;
      }
      if (clazz.startsWith("java.")
          || clazz.startsWith("apple.")
          || clazz.startsWith("javax.")
          || clazz.startsWith("sun.")) {

      } else {
        needsRestriction = true;
        restrictor = stack[i].toString();
        break;
      }
    }
    /*
    if (! needsRestriction) {
    System.out.println("NO RESTRICTION  "+Arrays.asList(cc));
    }*/
    // Allow all other actions
    if (needsRestriction && !isImplied(perm)) {
      System.err.println("StrictSecurityManager.checkPermision(" + perm + ")");
      System.err.println("  " + Arrays.asList(stack));
      System.err.println("  " + restrictor);
      throw new AccessControlException("Not allowed " + perm, perm);
    }
  }
  /**
   * Returns an input stream to the resource.
   *
   * @param resource The path leading to the resource. Can be an URL, a path leading to a class
   *     resource or a {@link File}.
   * @return InputStream instance.
   * @throws IOException If the resource could not be found or opened.
   */
  public static InputStream openInputStream(String resource) throws IOException {
    try {
      // See if the resource is an URL first.
      final URL url = new URL(resource);
      // success, load the resource.
      return url.openStream();
    } catch (MalformedURLException e) {
      // No luck. Fallback to class loader paths.
    }

    // Try current thread's class loader first.
    final ClassLoader ldr = Thread.currentThread().getContextClassLoader();

    InputStream is;
    if (ldr != null && (is = ldr.getResourceAsStream(resource)) != null) {
      return is;
    } else if ((is = ResourceUtils.class.getResourceAsStream(resource)) != null) {
      return is;
    } else if ((is = ClassLoader.getSystemResourceAsStream(resource)) != null) {
      return is;
    }

    // Try file path
    final File f = new File(resource);
    if (f.exists() && f.isFile() && f.canRead()) {
      return new FileInputStream(f);
    }

    throw new IOException("Could not locate resource: " + resource);
  }
Example #12
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;
  }
Example #13
0
 private void closeClientSocket() {
   try {
     client.close();
   } catch (IOException ex) {
     Log.warn(Thread.currentThread().getName() + ": failed to close client socket.", ex);
   }
 }
Example #14
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();
      }
    }
  }
Example #15
0
  public Worker(String url, boolean verbose) throws Exception {
    Document doc;
    doc = Jsoup.connect(url).get();
    // select anchors with href only
    Elements links = doc.select("a[href]");
    String l_Href;
    String host;
    int linksNum;
    Parser parser;
    for (Element link : links) {
      // absolute = http:// added
      l_Href = link.attr("abs:href");
      if (!l_Href.isEmpty()) {
        parser = new Parser(l_Href);
        host = parser.getHost();
        // if tempStats contains the url, add one to the value
        if (tempStats.containsKey(host)) {
          linksNum = tempStats.get(host);
          tempStats.put(host, linksNum += 1);
        }
        // if it doesn't, add it

        else {
          tempStats.put(host, 1);
        }
        // parse the url
        tempQueue.add(parser.getURL());
      }
    }
    if (verbose) {
      System.out.println(
          Thread.currentThread().getName() + " : " + tempQueue.size() + " links from " + url);
    }
  }
Example #16
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);
    }
  }
Example #17
0
  public void run() {
    final byte[] receive_buf = new byte[65535];
    DatagramPacket packet = new DatagramPacket(receive_buf, receive_buf.length);
    byte[] data;
    ByteArrayInputStream inp_stream;
    DataInputStream inp = null;
    Message msg;

    while (mcast_sock != null && receiver != null && Thread.currentThread().equals(receiver)) {
      packet.setData(receive_buf, 0, receive_buf.length);
      try {
        mcast_sock.receive(packet);
        data = packet.getData();
        inp_stream = new ExposedByteArrayInputStream(data, 0, data.length);
        inp = new DataInputStream(inp_stream);
        msg = new Message();
        msg.readFrom(inp);
        up(new Event(Event.MSG, msg));
      } catch (SocketException socketEx) {
        break;
      } catch (Throwable ex) {
        log.error("failed receiving packet (from " + packet.getSocketAddress() + ")", ex);
      } finally {
        Util.close(inp);
      }
    }
    if (log.isTraceEnabled()) log.trace("receiver thread terminated");
  }
 /**
  * Closes the socket and stops the listener thread.
  *
  * @throws IOException
  */
 public void close() throws IOException {
   boolean interrupted = false;
   WorkerTask l = listener;
   if (l != null) {
     l.terminate();
     l.interrupt();
     if (socketTimeout > 0) {
       try {
         l.join();
       } catch (InterruptedException ex) {
         interrupted = true;
         logger.warn(ex);
       }
     }
     listener = null;
   }
   DatagramSocket closingSocket = socket;
   if ((closingSocket != null) && (!closingSocket.isClosed())) {
     closingSocket.close();
   }
   socket = null;
   if (interrupted) {
     Thread.currentThread().interrupt();
   }
 }
Example #19
0
 /** Override so that stop() blocks until the run thread is no longer running. */
 @Override
 public void stop() throws Exception {
   super.stop();
   CountDownLatch countDownLatch = stoppedLatch.get();
   if (countDownLatch != null && Thread.currentThread() != this.runnerThread) {
     countDownLatch.await(1, TimeUnit.SECONDS);
   }
 }
Example #20
0
 private synchronized void startThread() {
   if (!aladin.NETWORK) return;
   if (thread != null) return;
   thread = new Thread(this, "Cache updater");
   Util.decreasePriority(Thread.currentThread(), thread);
   //      thread.setPriority( Thread.NORM_PRIORITY -2);
   thread.start();
 }
Example #21
0
    public void run() {
      while (Thread.currentThread() == thread) {
        con.run();
        count++;
        con = null;

        if (count > 200 || threadpool.size() > 20) return;

        synchronized (this) {
          releaseRunner(this);
          try {
            wait();
          } catch (InterruptedException ir) {
            Thread.currentThread().interrupt();
          }
        }
      }
    }
 /**
  * @param log Logger.
  * @param time Time.
  * @param msg Message.
  */
 private static void log0(@Nullable IgniteLogger log, long time, String msg) {
   if (log != null) {
     if (log.isDebugEnabled()) log.debug(msg);
     else log.warning(msg);
   } else
     X.println(
         String.format(
             "[%s][%s]%s",
             DEBUG_DATE_FMT.get().format(time), Thread.currentThread().getName(), msg));
 }
Example #23
0
 /**
  * Display on screen, pause for t milliseconds, and turn on <em>animation mode</em>: subsequent
  * calls to drawing methods such as <tt>line()</tt>, <tt>circle()</tt>, and <tt>square()</tt> will
  * not be displayed on screen until the next call to <tt>show()</tt>. This is useful for producing
  * animations (clear the screen, draw a bunch of shapes, display on screen for a fixed amount of
  * time, and repeat). It also speeds up drawing a huge number of shapes (call <tt>show(0)</tt> to
  * defer drawing on screen, draw the shapes, and call <tt>show(0)</tt> to display them all on
  * screen at once).
  *
  * @param t number of milliseconds
  */
 public static void show(int t) {
   defer = false;
   draw();
   try {
     Thread.currentThread().sleep(t);
   } catch (InterruptedException e) {
     System.out.println("Error sleeping");
   }
   defer = true;
 }
Example #24
0
  public boolean go() throws Exception {
    ss = new ServerSocket(0);

    Thread thr = new Thread(this);
    thr.start();

    Thread.currentThread().sleep(1000);

    ss.close();

    Thread.currentThread().sleep(1000);

    if (isClosed()) {
      return true;
    } else {
      failed("ServerSocket.accept() wasn't preempted");
      return false;
    }
  }
Example #25
0
 /**
  * Acceptor thread. Continuously accept new connections. Create a new thread for each new
  * connection and put it in conns. When the thread should stop, it is interrupted by the thread
  * creator.
  */
 public void run() {
   while (!srv_sock.isClosed() && !Thread.currentThread().isInterrupted()) {
     TCPConnection conn = null;
     Socket client_sock = null;
     try {
       client_sock = srv_sock.accept();
       conn = new TCPConnection(client_sock);
       Address peer_addr = conn.getPeerAddress();
       mapper.getLock().lock();
       try {
         boolean currentConnectionOpen = mapper.hasOpenConnection(peer_addr);
         boolean replaceWithNewConnection = false;
         if (currentConnectionOpen) {
           replaceWithNewConnection = peer_addr.compareTo(local_addr) > 0;
         }
         if (!currentConnectionOpen || replaceWithNewConnection) {
           mapper.removeConnection(peer_addr);
           mapper.addConnection(peer_addr, conn);
           conn.start(mapper.getThreadFactory()); // starts handler thread on this socket
         } else {
           Util.close(conn);
         }
       } finally {
         mapper.getLock().unlock();
       }
     } catch (SocketException se) {
       boolean threadExiting = srv_sock.isClosed() || Thread.currentThread().isInterrupted();
       if (threadExiting) {
         break;
       } else {
         if (log.isWarnEnabled()) log.warn("Could not accept connection from peer ", se);
         Util.close(conn);
         Util.close(client_sock);
       }
     } catch (Exception ex) {
       if (log.isWarnEnabled()) log.warn("Could not read accept connection from peer " + ex);
       Util.close(conn);
       Util.close(client_sock);
     }
   }
   if (log.isTraceEnabled()) log.trace(Thread.currentThread().getName() + " terminated");
 }
Example #26
0
 /** Creates a new instance of TestLoad */
 public static void main(String[] args) {
   try {
     while (true) {
       TestLoad test = new TestLoad(args);
       test.start();
       Thread.currentThread().sleep(CREATE_DELAY);
     }
   } catch (InterruptedException ex) {
     ex.printStackTrace();
   }
 }
  protected int pick(int iThink, boolean couldCreate) {
    final int id = Thread.currentThread().hashCode();
    final int s = _availSafe.size();
    for (int i = 0; i < s; i++) {
      DBPort p = _availSafe.get(i);
      if (p._lastThread == id) return i;
    }

    if (couldCreate) return -1;
    return iThink;
  }
Example #28
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();
    }
  }
 public void run() {
   Thread t = Thread.currentThread();
   while (t == gameloop) {
     try {
       Thread.sleep(20);
     } catch (InterruptedException e) {
       e.printStackTrace();
     }
     repaint();
   }
 }
Example #30
0
    /**
     * Sends data using the 'out' output stream of the socket
     *
     * @param data
     * @param offset
     * @param length
     * @param acquire_lock
     * @throws Exception
     */
    private void _send(byte[] data, int offset, int length, boolean acquire_lock) throws Exception {
      if (acquire_lock) send_lock.lock();

      try {
        doSend(data, offset, length);
        updateLastAccessed();
      } catch (InterruptedException iex) {
        Thread.currentThread().interrupt(); // set interrupt flag again
      } finally {
        if (acquire_lock) send_lock.unlock();
      }
    }