public Thread newThread(Runnable r) {
   Thread t =
       new GSThread(group, r, namePrefix + threadNumber.get(), threadNumber.getAndIncrement());
   if (t.isDaemon()) t.setDaemon(false);
   if (t.getPriority() != Thread.MAX_PRIORITY) t.setPriority(Thread.MAX_PRIORITY);
   return t;
 }
 @Override
 public Thread newThread(Runnable r) {
   Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
   if (t.isDaemon()) t.setDaemon(false);
   t.setPriority(threadPriority);
   return t;
 }
 @Override
 public void writeLine(String line) throws IOException {
   if (outputEnabled) {
     double rate;
     if (maxEventRateChecker.updateAndCheckRate()
         && (rate = maxEventRateChecker.getRate()) > maxLogsRate) {
       outputEnabled = false;
       final String message =
           String.format(
               "[WARNING] Application '%s' has exceeded output rate of %.2f messages / second. Application output has been disabled.",
               project.startsWith("/") ? project.substring(1) : project, rate);
       eventService.publish(
           RunnerEvent.messageLoggedEvent(
               processId,
               workspace,
               project,
               new RunnerEvent.LoggedMessage(message, lineCounter.getAndIncrement())));
       return;
     }
     if (line != null) {
       eventService.publish(
           RunnerEvent.messageLoggedEvent(
               processId,
               workspace,
               project,
               new RunnerEvent.LoggedMessage(line, lineCounter.getAndIncrement())));
     }
   }
   super.writeLine(line);
 }
 /** getAndIncrement returns previous value and increments */
 public void testGetAndIncrement() {
   AtomicInteger ai = new AtomicInteger(1);
   assertEquals(1, ai.getAndIncrement());
   assertEquals(2, ai.get());
   ai.set(-2);
   assertEquals(-2, ai.getAndIncrement());
   assertEquals(-1, ai.getAndIncrement());
   assertEquals(0, ai.getAndIncrement());
   assertEquals(1, ai.get());
 }
Example #5
0
  /**
   * Gets the next available port. Every port in the range is tried at most once. Tries to avoid
   * returning the same port on successive invocations (but it may happen if no other available
   * ports are found).
   *
   * @throws NoSuchElementException if no available port is found
   * @return the next available port
   */
  public int getNextAvailable() {
    int range = toPort - fromPort + 1;
    int curr = candidateCounter.getAndIncrement();
    int last = curr + range;
    while (curr < last) {
      int candidate = fromPort + curr % range;
      if (available(candidate)) {
        return candidate;
      }
      curr = candidateCounter.getAndIncrement();
    }

    throw new NoSuchElementException("Could not find an available port within port range");
  }
 /**
  * Finds the accessibility focused {@link android.view.accessibility.AccessibilityNodeInfo}. The
  * search is performed in the window whose id is specified and starts from the node whose
  * accessibility id is specified.
  *
  * @param connectionId The id of a connection for interacting with the system.
  * @param accessibilityWindowId A unique window id. Use {@link
  *     android.view.accessibility.AccessibilityNodeInfo#ACTIVE_WINDOW_ID} to query the currently
  *     active window.
  * @param accessibilityNodeId A unique view id or virtual descendant id from where to start the
  *     search. Use {@link android.view.accessibility.AccessibilityNodeInfo#ROOT_NODE_ID} to start
  *     from the root.
  * @param direction The direction in which to search for focusable.
  * @return The accessibility focused {@link AccessibilityNodeInfo}.
  */
 public AccessibilityNodeInfo focusSearch(
     int connectionId, int accessibilityWindowId, long accessibilityNodeId, int direction) {
   try {
     IAccessibilityServiceConnection connection = getConnection(connectionId);
     if (connection != null) {
       final int interactionId = mInteractionIdCounter.getAndIncrement();
       final long identityToken = Binder.clearCallingIdentity();
       final boolean success =
           connection.focusSearch(
               accessibilityWindowId,
               accessibilityNodeId,
               direction,
               interactionId,
               this,
               Thread.currentThread().getId());
       Binder.restoreCallingIdentity(identityToken);
       if (success) {
         AccessibilityNodeInfo info = getFindAccessibilityNodeInfoResultAndClear(interactionId);
         finalizeAndCacheAccessibilityNodeInfo(info, connectionId);
         return info;
       }
     } else {
       if (DEBUG) {
         Log.w(LOG_TAG, "No connection for connection id: " + connectionId);
       }
     }
   } catch (RemoteException re) {
     Log.w(LOG_TAG, "Error while calling remote accessibilityFocusSearch", re);
   }
   return null;
 }
  @Override
  public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain)
      throws IOException, ServletException {

    try {
      HttpServletResponse hrsp = (HttpServletResponse) rsp;
      if (maxConnections > 0) {

        if (active.getAndIncrement() > maxConnections) {
          String msg = maxConnectionMessage;
          if (msg == null)
            msg =
                "Too many simultaneous requests (this is a small server, after all, this is not a commercial service)";
          hrsp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, msg);
          return;
        }
      }

      Coordination c = coordinator.begin("osgi.enroute.webrequest." + active.incrementAndGet(), 0);
      try {
        chain.doFilter(req, rsp);
        c.end();
      } catch (Throwable t) {
        c.fail(t);
        throw t;
      }
    } finally {
      active.decrementAndGet();
    }
  }
 @CacheEntryModified
 @CacheEntryRemoved
 @CacheEntryVisited
 @CacheEntryCreated
 public void catchEvent(Event e) {
   if (e.isPre()) counter.getAndIncrement();
 }
 DefaultThreadFactory(int threadPriority) {
   this.threadNumber = new AtomicInteger(1);
   this.threadPriority = threadPriority;
   SecurityManager s = System.getSecurityManager();
   this.group = s != null ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
   this.namePrefix = "uil-pool-" + poolNumber.getAndIncrement() + "-thread-";
 }
Example #10
0
 @Override
 public Thread newThread(Runnable r) {
   Thread thread = new Thread(r);
   thread.setDaemon(true);
   thread.setName(String.format("AMQPConnection-%s", THREAD_COUNT.getAndIncrement()));
   return thread;
 }
  /*
   * (non-Javadoc)
   *
   * @see
   * asia.stampy.common.mina.StampyMinaMessageListener#messageReceived(asia.
   * stampy.common.message.StampyMessage,
   * org.apache.mina.core.session.IoSession, asia.stampy.common.HostPort)
   */
  @Override
  public void messageReceived(StampyMessage<?> message, HostPort hostPort) throws Exception {
    switch (message.getMessageType()) {
      case CONNECTED:
        connected = true;
        start = System.nanoTime();
        System.out.println("Sending " + times + " messages to the server, receipts requested...");
        sendAcks(); // should be a threaded operation in prod
        break;
      case ERROR:
        System.out.println(
            "Unexpected error " + ((ErrorMessage) message).getHeader().getMessageHeader());
        break;
      case RECEIPT:
        receipts.getAndIncrement();

        if (receipts.get() == times) {
          synchronized (waiter) {
            waiter.notifyAll();
          }
        }

        break;
      default:
        System.out.println("Unexpected message " + message.getMessageType());
        break;
    }
  }
  @Override
  public BroadcastAction filter(
      HttpServletRequest request, HttpServletResponse response, Object message) {

    if (request.getHeader("User-Agent") != null
            && request.getAttribute("X-Atmosphere-Transport") == null
        || request.getAttribute("X-Atmosphere-Transport") != null
            && ((String) request.getAttribute("X-Atmosphere-Transport"))
                .equalsIgnoreCase("long-polling")) {
      String userAgent = request.getHeader("User-Agent").toLowerCase();
      if (userAgent != null && userAgent.startsWith("opera") && message instanceof String) {
        StringBuilder sb =
            new StringBuilder("<script id=\"atmosphere_")
                .append(uniqueScriptToken.getAndIncrement())
                .append("\">")
                .append("window.parent.$.atmosphere.streamingCallback")
                .append("('")
                .append(message.toString())
                .append("');</script>");
        message = sb.toString();
        return new BroadcastAction(BroadcastAction.ACTION.CONTINUE, message);
      }
    }
    return new BroadcastAction(BroadcastAction.ACTION.CONTINUE, null);
  }
 public StreamData getStream(UUID streamID) {
   // probably should do this over UDP.
   try {
     JSONRPC2Request jr = new JSONRPC2Request("getstream", id.getAndIncrement());
     Map<String, Object> params = new HashMap<String, Object>();
     params.put("streamid", streamID.toString());
     jr.setNamedParams(params);
     JSONRPC2Response jres = jsonSession.send(jr);
     if (jres.indicatesSuccess()) {
       Map<String, Object> jo = (Map<String, Object>) jres.getResult();
       if ((Boolean) jo.get("present")) {
         StreamData sd = new StreamData();
         sd.currentLog = UUID.fromString((String) jo.get("currentlog"));
         sd.startPos = (Long) jo.get("startpos");
         sd.epoch = (Long) jo.get("epoch");
         sd.startLog = UUID.fromString((String) jo.get("startlog"));
         return sd;
       } else {
         return null;
       }
     }
   } catch (Exception e) {
     log.error("other error", e);
     return null;
   }
   return null;
 }
 public void save(Campaign campaign) {
   if (campaign.getId() == null) {
     Integer id = NEXT_ID.getAndIncrement();
     campaign.setId(id);
   }
   campaigns.put(campaign.getId(), campaign);
 }
 /**
  * Performs an accessibility action on an {@link AccessibilityNodeInfo}.
  *
  * @param connectionId The id of a connection for interacting with the system.
  * @param accessibilityWindowId A unique window id. Use {@link
  *     android.view.accessibility.AccessibilityNodeInfo#ACTIVE_WINDOW_ID} to query the currently
  *     active window.
  * @param accessibilityNodeId A unique view id or virtual descendant id from where to start the
  *     search. Use {@link android.view.accessibility.AccessibilityNodeInfo#ROOT_NODE_ID} to start
  *     from the root.
  * @param action The action to perform.
  * @param arguments Optional action arguments.
  * @return Whether the action was performed.
  */
 public boolean performAccessibilityAction(
     int connectionId,
     int accessibilityWindowId,
     long accessibilityNodeId,
     int action,
     Bundle arguments) {
   try {
     IAccessibilityServiceConnection connection = getConnection(connectionId);
     if (connection != null) {
       final int interactionId = mInteractionIdCounter.getAndIncrement();
       final long identityToken = Binder.clearCallingIdentity();
       final boolean success =
           connection.performAccessibilityAction(
               accessibilityWindowId,
               accessibilityNodeId,
               action,
               arguments,
               interactionId,
               this,
               Thread.currentThread().getId());
       Binder.restoreCallingIdentity(identityToken);
       if (success) {
         return getPerformAccessibilityActionResultAndClear(interactionId);
       }
     } else {
       if (DEBUG) {
         Log.w(LOG_TAG, "No connection for connection id: " + connectionId);
       }
     }
   } catch (RemoteException re) {
     Log.w(LOG_TAG, "Error while calling remote performAccessibilityAction", re);
   }
   return false;
 }
Example #16
0
 @Override
 public Thread newThread(Runnable runnable) {
   Thread thread =
       new Thread(runnable, "Executor{" + namePrefix + "-" + idCounter.getAndIncrement() + "}");
   thread.setDaemon(daemon);
   return thread;
 }
 public void addNewDownload(
     String url,
     String fileName,
     String target,
     boolean autoResume,
     boolean autoRename,
     final RequestCallBack<File> callback)
     throws Exception {
   final DownloadInfo downloadInfo = new DownloadInfo();
   downloadInfo.setDownloadUrl(url);
   downloadInfo.setAutoRename(autoRename);
   downloadInfo.setAutoResume(autoResume);
   downloadInfo.setFileName(fileName);
   downloadInfo.setFileSavePath(target);
   downloadInfo.setId(mCount.getAndIncrement());
   HttpUtils http = new HttpUtils();
   //        http.configRequestThreadPoolSize(maxDownloadThread);
   HttpHandler<File> handler =
       http.download(
           url, target, autoResume, autoRename, new ManagerCallBack(downloadInfo, callback));
   downloadInfo.setHandler(handler);
   downloadInfo.setState(handler.getState());
   downloadInfoList.add(downloadInfo);
   infoImpl.insert(downloadInfo);
 }
Example #18
0
  private OutMessage(
      final DBCollection collection,
      final Mongo m,
      OpCode opCode,
      final DBEncoder enc,
      final DBObject query,
      final int options,
      final ReadPreference readPref) {
    _collection = collection;
    _mongo = m;
    _encoder = enc;

    _buffer = _mongo._bufferPool.get();
    _buffer.reset();
    set(_buffer);

    _id = REQUEST_ID.getAndIncrement();
    _opCode = opCode;

    writeMessagePrologue(opCode);

    if (query == null) {
      _query = null;
      _queryOptions = 0;
    } else {
      _query = query;

      int allOptions = options;
      if (readPref != null && readPref.isSlaveOk()) {
        allOptions |= Bytes.QUERYOPTION_SLAVEOK;
      }

      _queryOptions = allOptions;
    }
  }
Example #19
0
  private void setDefaultBootDevice() {
    // In the time of disk creation the VM ID is an empty Guid, this is changed to the real ID only
    // after the reading
    // of the OS properties which comes after the disks creation so the disk VM elements are set to
    // the wrong VM ID
    // this part sets them to the correct VM ID
    for (DiskImage disk : _images) {
      disk.getDiskVmElements()
          .stream()
          .forEach(dve -> dve.setId(new VmDeviceId(disk.getId(), vmBase.getId())));
      disk.setDiskVmElements(disk.getDiskVmElements());
    }

    boolean hasBootDevice =
        vmBase
            .getManagedDeviceMap()
            .values()
            .stream()
            .anyMatch(device -> device.getBootOrder() > 0);
    if (hasBootDevice) {
      return;
    }

    AtomicInteger order =
        new AtomicInteger(1); // regular non-final variable cannot be used in lambda expression
    _images
        .stream()
        .filter(d -> d.getDiskVmElementForVm(vmBase.getId()).isBoot())
        .map(image -> vmBase.getManagedDeviceMap().get(image.getId()))
        .filter(Objects::nonNull)
        .forEachOrdered(device -> device.setBootOrder(order.getAndIncrement()));
  }
Example #20
0
  public void run(String arg) {
    final ExecutorService executorService =
        Cluster.activeCluster()
            ? Cluster.getCluster().getService(1)
            : Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    final ArrayList<Future<ArrayList<Float>>> futures = new ArrayList<Future<ArrayList<Float>>>();

    for (int i = 0; i < 128; ++i) {
      final ArrayList<Float> floats = new ArrayList<Float>();
      final Float f = new Float(i);
      final Integer id = uid.getAndIncrement();

      floats.add(f);
      ifmap.put(id, f);
      fimap.put(f, id);
      ffmap.put(f, f);
      futures.add(executorService.submit(new EqCall(floats)));
    }

    try {
      for (Future<ArrayList<Float>> fu : futures) {
        Float fc = fu.get().get(0);
        // Integer i = fimap.get(fc);
        // Float fo = i == null ? null : ifmap.get(i);
        Float fo = ffmap.get(fc);
        String eqstr = fo == fc ? "they are equal" : "they are unequal";
        IJ.log("Got back float " + fc + " keyed to " + fo + " and " + eqstr);
      }
    } catch (InterruptedException ie) {
      IJ.log("Woops: " + ie);
    } catch (ExecutionException ee) {
      IJ.log("Woops: " + ee);
    }
  }
 /**
  * Return integer of next value
  *
  * @return the integer
  * @throws NoSuchElementException
  */
 @Override
 public Integer next() {
   if (!hasNext()) {
     throw new NoSuchElementException();
   }
   return count.getAndIncrement();
 }
  private static Client startClient(Path tempDir, TransportAddress... transportAddresses) {
    Settings clientSettings =
        Settings.settingsBuilder()
            .put("name", "qa_smoke_client_" + counter.getAndIncrement())
            .put(
                InternalSettingsPreparer.IGNORE_SYSTEM_PROPERTIES_SETTING,
                true) // prevents any settings to be replaced by system properties.
            .put("client.transport.ignore_cluster_name", true)
            .put(Environment.PATH_HOME_SETTING.getKey(), tempDir)
            .put("node.mode", "network")
            .build(); // we require network here!

    TransportClient.Builder transportClientBuilder =
        TransportClient.builder().settings(clientSettings);
    TransportClient client =
        transportClientBuilder.build().addTransportAddresses(transportAddresses);

    logger.info("--> Elasticsearch Java TransportClient started");

    Exception clientException = null;
    try {
      ClusterHealthResponse health = client.admin().cluster().prepareHealth().get();
      logger.info(
          "--> connected to [{}] cluster which is running [{}] node(s).",
          health.getClusterName(),
          health.getNumberOfNodes());
    } catch (Exception e) {
      clientException = e;
    }

    assumeNoException(
        "Sounds like your cluster is not running at " + clusterAddresses, clientException);

    return client;
  }
  /**
   * Create a tmp file, and return its absolute path
   *
   * @param prefix
   * @param suffix
   * @param directory
   * @return {@code null} if file could not be created
   * @throws IOException
   */
  public String createTempFile(String prefix, String suffix, File directory)
      throws IllegalArgumentException, IOException {

    if (prefix.length() < 3) throw new IllegalArgumentException("Prefix string too short");
    if (suffix == null) suffix = ".tmp";

    String folder = null;

    if (directory == null) {
      folder = getTmpFolderPath();
    } else {
      folder = directory.getAbsolutePath();
    }

    int counter = tmpFileCounter.getAndIncrement();
    String fileName = prefix + counter + suffix;
    String path = folder + File.separator + fileName;

    boolean created = createFile(path);
    if (!created) {
      throw new IOException();
    }

    return path;
  }
 @Override
 public Thread newThread(Runnable r) {
   Thread t = new Thread(r, executorName + "-" + sequence.getAndIncrement());
   t.setDaemon(true);
   t.setPriority(Thread.NORM_PRIORITY + 1);
   return t;
 }
 @Override
 public TestResource create(String key) throws Exception {
   if (createException != null) throw createException;
   TestResource r = new TestResource(Integer.toString(created.getAndIncrement()));
   if (!isCreatedValid) r.invalidate();
   return r;
 }
  /**
   * Tests whether the Who Am I? extended operation with an internal authenticated connection
   * succeeds with default setting of "ds-cfg-reject-unauthenticated-requests".
   *
   * @throws Exception If an unexpected problem occurs.
   */
  @Test()
  public void testAuthWAIDefCfg() throws Exception {
    DirectoryServer.setRejectUnauthenticatedRequests(false);

    Socket s = new Socket("127.0.0.1", TestCaseUtils.getServerLdapPort());
    LDAPReader reader = new LDAPReader(s);
    LDAPWriter writer = new LDAPWriter(s);

    AtomicInteger nextMessageID = new AtomicInteger(1);
    LDAPAuthenticationHandler authHandler =
        new LDAPAuthenticationHandler(reader, writer, "localhost", nextMessageID);
    authHandler.doSimpleBind(
        3,
        ByteString.valueOf("cn=Directory Manager"),
        ByteString.valueOf("password"),
        new ArrayList<Control>(),
        new ArrayList<Control>());
    ByteString authzID = authHandler.requestAuthorizationIdentity();
    assertNotNull(authzID);

    LDAPMessage unbindMessage =
        new LDAPMessage(nextMessageID.getAndIncrement(), new UnbindRequestProtocolOp());
    writer.writeMessage(unbindMessage);
    s.close();
  }
  private void checkForSharedSourceCommand(AccessNode aNode) {
    // create a top level key to avoid the full command toString
    String modelName = aNode.getModelName();
    Command cmd = aNode.getCommand();

    // don't share full scans against internal sources, it's a waste of buffering
    if (CoreConstants.SYSTEM_MODEL.equals(modelName)
        || CoreConstants.SYSTEM_ADMIN_MODEL.equals(modelName)
        || TempMetadataAdapter.TEMP_MODEL.getName().equals(modelName)) {
      if (!(cmd instanceof Query)) {
        return;
      }
      Query query = (Query) cmd;
      if (query.getOrderBy() == null && query.getCriteria() == null) {
        return;
      }
    }

    AccessNode other = sharedCommands.get(cmd);
    if (other == null) {
      sharedCommands.put(cmd, aNode);
    } else {
      if (other.info == null) {
        other.info = new RegisterRequestParameter.SharedAccessInfo();
        other.info.id = sharedId.getAndIncrement();
      }
      other.info.sharingCount++;
      aNode.info = other.info;
    }
  }
  /**
   * Tests whether the who am I? extended operation with an unauthenticated connection fails with
   * new setting of "ds-cfg-reject-unauthenticated-requests".
   *
   * @throws UnsupportedEncodingException If an unexpected problem occurs.
   * @throws IOException If an unexpected problem occurs.
   * @throws ClientException If an unexpected problem occurs.
   */
  @Test
  public void testUnauthWAINewCfg()
      throws UnsupportedEncodingException, IOException, ClientException {
    try {
      DirectoryServer.setRejectUnauthenticatedRequests(true);

      Socket s = new Socket("127.0.0.1", TestCaseUtils.getServerLdapPort());
      LDAPReader reader = new LDAPReader(s);
      LDAPWriter writer = new LDAPWriter(s);
      AtomicInteger nextMessageID = new AtomicInteger(1);
      LDAPAuthenticationHandler authHandler =
          new LDAPAuthenticationHandler(reader, writer, "localhost", nextMessageID);
      ByteString authzID = null;
      try {
        authzID = authHandler.requestAuthorizationIdentity();
      } catch (LDAPException e) {
        assertNull(authzID);
      } finally {
        LDAPMessage unbindMessage =
            new LDAPMessage(nextMessageID.getAndIncrement(), new UnbindRequestProtocolOp());
        writer.writeMessage(unbindMessage);
        s.close();
      }
    } finally {
      DirectoryServer.setRejectUnauthenticatedRequests(false);
    }
  }
Example #29
0
 /**
  * Traverse tree recursively and generate dot code for vertices.
  *
  * @param n The root node.
  * @param eoiCounter The counter for the execution order index.
  * @param nodeIds The map containing the node IDs.
  * @param ps The stream on which the generated code will be printed.
  * @param includeWeights Determines whether to include weights or not.
  */
 private static void dotVerticesFromSubTree(
     final AbstractCallTreeNode<?> n,
     final AtomicInteger eoiCounter,
     final Map<AbstractCallTreeNode<?>, Integer> nodeIds,
     final PrintStream ps,
     final boolean includeWeights) {
   final int thisId = nodeIds.get(n);
   for (final WeightedDirectedCallTreeEdge<?> child : n.getChildEdges()) {
     final StringBuilder strBuild = new StringBuilder(1024);
     final int childId = nodeIds.get(child.getTarget());
     strBuild
         .append('\n')
         .append(thisId)
         .append("->")
         .append(childId)
         .append("[style=solid,arrowhead=none");
     if (includeWeights) {
       strBuild.append(",label=\"").append(child.getTargetWeight().get()).append('"');
     } else if (eoiCounter != null) {
       strBuild.append(",label=\"").append(eoiCounter.getAndIncrement()).append(".\"");
     }
     strBuild.append(" ]");
     ps.println(strBuild.toString());
     AbstractCallTreeFilter.dotVerticesFromSubTree(
         child.getTarget(), eoiCounter, nodeIds, ps, includeWeights);
   }
 }
  /**
   * Get a map from author names to their ids in the database. The authors that are not in the
   * database are added to it.
   *
   * @param conn the connection to the database
   * @param history the history to get the author names from
   * @param reposId the id of the repository
   * @return a map from author names to author ids
   */
  private Map<String, Integer> getAuthors(ConnectionResource conn, History history, int reposId)
      throws SQLException {
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    PreparedStatement ps = conn.getStatement(GET_AUTHORS);
    ps.setInt(1, reposId);
    try (ResultSet rs = ps.executeQuery()) {
      while (rs.next()) {
        map.put(rs.getString(1), rs.getInt(2));
      }
    }

    PreparedStatement insert = conn.getStatement(ADD_AUTHOR);
    insert.setInt(1, reposId);
    for (HistoryEntry entry : history.getHistoryEntries()) {
      String author = entry.getAuthor();
      if (!map.containsKey(author)) {
        int id = nextAuthorId.getAndIncrement();
        insert.setString(2, author);
        insert.setInt(3, id);
        insert.executeUpdate();
        map.put(author, id);
        conn.commit();
      }
    }

    return map;
  }