Example #1
0
 public static MiruPartitionedActivity mockPartitionedActivity(
     int partitionId,
     byte[] streamId,
     Optional<MiruReadEvent> miruReadEvent,
     Optional<Integer> type) {
   int typeValue = type.or(random.nextInt(4));
   switch (typeValue) {
     case 0:
       return new MiruPartitionedActivityFactory()
           .read(
               1,
               MiruPartitionId.of(partitionId),
               index.incrementAndGet(),
               miruReadEvent.or(mockReadEvent(streamId)));
     case 1:
       return new MiruPartitionedActivityFactory()
           .unread(
               1,
               MiruPartitionId.of(partitionId),
               index.incrementAndGet(),
               miruReadEvent.or(mockReadEvent(streamId)));
     case 2:
       return new MiruPartitionedActivityFactory()
           .allread(
               1,
               MiruPartitionId.of(partitionId),
               index.incrementAndGet(),
               miruReadEvent.or(mockReadEvent(streamId)));
     default:
       return new MiruPartitionedActivityFactory()
           .activity(1, MiruPartitionId.of(partitionId), index.incrementAndGet(), mockActivity());
   }
 }
 private void bucketInsert(
     IStatus child,
     List<IStatus> infos,
     List<IStatus> warnings,
     List<IStatus> errors,
     AtomicInteger infoCount,
     AtomicInteger warnCount,
     AtomicInteger errorCount) {
   int sev = child.getSeverity();
   if (sev < IStatus.WARNING) {
     if (infos.size() < MULTI_STATUS_AGGREGATE_GROUP_MAX || child.isMultiStatus()) {
       infos.add(child);
     }
     infoCount.incrementAndGet();
   } else if (sev < IStatus.ERROR) {
     if (warnings.size() < MULTI_STATUS_AGGREGATE_GROUP_MAX || child.isMultiStatus()) {
       warnings.add(child);
     }
     warnCount.incrementAndGet();
   } else {
     if (errors.size() < MULTI_STATUS_AGGREGATE_GROUP_MAX || child.isMultiStatus()) {
       errors.add(child);
     }
     errorCount.incrementAndGet();
   }
 }
  public void execute() throws Exception {
    final String activeShardCountFailure = checkActiveShardCount();
    final ShardRouting primaryRouting = primary.routingEntry();
    final ShardId primaryId = primaryRouting.shardId();
    if (activeShardCountFailure != null) {
      finishAsFailed(
          new UnavailableShardsException(
              primaryId,
              "{} Timeout: [{}], request: [{}]",
              activeShardCountFailure,
              request.timeout(),
              request));
      return;
    }

    totalShards.incrementAndGet();
    pendingShards.incrementAndGet();
    primaryResult = primary.perform(request);
    final ReplicaRequest replicaRequest = primaryResult.replicaRequest();
    assert replicaRequest.primaryTerm() > 0 : "replicaRequest doesn't have a primary term";
    if (logger.isTraceEnabled()) {
      logger.trace(
          "[{}] op [{}] completed on primary for request [{}]", primaryId, opType, request);
    }

    performOnReplicas(primaryId, replicaRequest);

    successfulShards.incrementAndGet();
    decPendingAndFinishIfNeeded();
  }
 public void onAccept(Socket acceptedSocket) throws IOException {
   acceptCallCount.incrementAndGet();
   try {
     OutputStream out = acceptedSocket.getOutputStream();
     InputStream in = acceptedSocket.getInputStream();
     int loop = new Random().nextInt(2) + 1;
     int secretValue = 1;
     int expected = (int) Math.pow(2, loop);
     for (int i = 0; i < loop; i++) {
       out.write(secretValue);
       int read = in.read();
       if (read != 2 * secretValue) {
         throw new IOException("Authentication Failed");
       }
       secretValue = read;
     }
     if (secretValue != expected) {
       throw new IOException("Authentication Failed");
     }
     out.write(0);
   } catch (IOException e) {
     acceptFailureCount.incrementAndGet();
     throw e;
   }
 }
 @Override
 public void objectToEntry(Collection<RefsetMember<?, ?>> list, TupleOutput output) {
   List<RefsetMember<?, ?>> refsetMembersToWrite = new ArrayList<RefsetMember<?, ?>>(list.size());
   for (RefsetMember<?, ?> refsetMember : list) {
     encountered.incrementAndGet();
     assert refsetMember.primordialSapNid != Integer.MAX_VALUE;
     if (refsetMember.primordialSapNid > maxReadOnlyStatusAtPositionId) {
       if (refsetMember.getTime() != Long.MIN_VALUE) {
         refsetMembersToWrite.add(refsetMember);
       }
     } else {
       if (refsetMember.revisions != null) {
         for (RefsetRevision<?, ?> r : refsetMember.revisions) {
           if (r.getStatusAtPositionNid() > maxReadOnlyStatusAtPositionId
               && r.getTime() != Long.MIN_VALUE) {
             refsetMembersToWrite.add(refsetMember);
             break;
           }
         }
       }
     }
   }
   output.writeInt(refsetMembersToWrite.size()); // List size
   for (RefsetMember<?, ?> refsetMember : refsetMembersToWrite) {
     written.incrementAndGet();
     output.writeInt(refsetMember.getTypeId());
     refsetMember.writeComponentToBdb(output, maxReadOnlyStatusAtPositionId);
   }
 }
Example #6
0
  private Ref readRef(String name, RefList<Ref> packed) throws IOException {
    final RefList<LooseRef> curList = looseRefs.get();
    final int idx = curList.find(name);
    if (0 <= idx) {
      final LooseRef o = curList.get(idx);
      final LooseRef n = scanRef(o, name);
      if (n == null) {
        if (looseRefs.compareAndSet(curList, curList.remove(idx))) modCnt.incrementAndGet();
        return packed.get(name);
      }

      if (o == n) return n;
      if (looseRefs.compareAndSet(curList, curList.set(idx, n))) modCnt.incrementAndGet();
      return n;
    }

    final LooseRef n = scanRef(null, name);
    if (n == null) return packed.get(name);

    // check whether the found new ref is the an additional ref. These refs
    // should not go into looseRefs
    for (int i = 0; i < additionalRefsNames.length; i++)
      if (name.equals(additionalRefsNames[i])) return n;

    if (looseRefs.compareAndSet(curList, curList.add(idx, n))) modCnt.incrementAndGet();
    return n;
  }
  /**
   * Sends a unicast message and - depending on the options - returns a result
   *
   * @param msg the message to be sent. The destination needs to be non-null
   * @param opts the options to be used
   * @return T the result
   * @throws Exception If there was problem sending the request, processing it at the receiver, or
   *     processing it at the sender.
   * @throws TimeoutException If the call didn't succeed within the timeout defined in options (if
   *     set)
   */
  public <T> T sendMessage(Message msg, RequestOptions opts) throws Exception {
    Address dest = msg.getDest();
    if (dest == null)
      throw new IllegalArgumentException("message destination is null, cannot send message");

    if (opts != null) {
      msg.setFlag(opts.getFlags()).setTransientFlag(opts.getTransientFlags());
      if (opts.getScope() > 0) msg.setScope(opts.getScope());
      if (opts.getMode() == ResponseMode.GET_NONE) async_unicasts.incrementAndGet();
      else sync_unicasts.incrementAndGet();
    }

    UnicastRequest<T> req = new UnicastRequest<T>(msg, corr, dest, opts);
    req.execute();

    if (opts != null && opts.getMode() == ResponseMode.GET_NONE) return null;

    Rsp<T> rsp = req.getResult();
    if (rsp.wasSuspected()) throw new SuspectedException(dest);

    Throwable exception = rsp.getException();
    if (exception != null) {
      if (exception instanceof Error) throw (Error) exception;
      else if (exception instanceof RuntimeException) throw (RuntimeException) exception;
      else if (exception instanceof Exception) throw (Exception) exception;
      else throw new RuntimeException(exception);
    }

    if (rsp.wasUnreachable()) throw new UnreachableException(dest);
    if (!rsp.wasReceived() && !req.responseReceived())
      throw new TimeoutException("timeout sending message to " + dest);
    return rsp.getValue();
  }
  private SliderRow forgeSliderRow(Slider slider) {
    String startLabel = slider.getStartLabel();
    TextElement startLabelEl =
        uifactory.addTextElement(
            "start.label." + count.incrementAndGet(), "start.label", 256, startLabel, flc);
    startLabelEl.setDomReplacementWrapperRequired(false);
    String endLabel = slider.getEndLabel();
    TextElement endLabelEl =
        uifactory.addTextElement(
            "end.label." + count.incrementAndGet(), "end.label", 256, endLabel, flc);
    endLabelEl.setDomReplacementWrapperRequired(false);

    SliderRow row = new SliderRow(slider, startLabelEl, endLabelEl);
    if (!restrictedEdit) {
      FormLink deleteButton =
          uifactory.addFormLink(
              "del." + count.incrementAndGet(),
              "delete_slider",
              "",
              null,
              flc,
              Link.BUTTON | Link.NONTRANSLATED);
      deleteButton.setDomReplacementWrapperRequired(false);
      deleteButton.setIconLeftCSS("o_icon o_icon-lg o_icon_delete_item");
      deleteButton.setUserObject(row);
      row.setDeleteButton(deleteButton);
      flc.contextPut("deleteButtons", Boolean.TRUE);
    }
    return row;
  }
Example #9
0
 @Test
 public void testWebsocketStreamCallbackAsynchronously() {
   this.server =
       vertx.createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT));
   AtomicInteger done = new AtomicInteger();
   ServerWebSocketStream stream = server.websocketStream();
   stream.handler(req -> {});
   ThreadLocal<Object> stack = new ThreadLocal<>();
   stack.set(true);
   stream.endHandler(
       v -> {
         assertTrue(Vertx.currentContext().isEventLoopContext());
         assertNull(stack.get());
         if (done.incrementAndGet() == 2) {
           testComplete();
         }
       });
   server.listen(
       ar -> {
         assertTrue(Vertx.currentContext().isEventLoopContext());
         assertNull(stack.get());
         ThreadLocal<Object> stack2 = new ThreadLocal<>();
         stack2.set(true);
         server.close(
             v -> {
               assertTrue(Vertx.currentContext().isEventLoopContext());
               assertNull(stack2.get());
               if (done.incrementAndGet() == 2) {
                 testComplete();
               }
             });
         stack2.set(null);
       });
   await();
 }
Example #10
0
  protected String createRowId(Map<String, Object> data) {
    Long ots = null;
    Object ov;

    ov = data.get("logTimestamp");
    if (ov == null) {
      // return new Text("9999");
      return null;
    }

    if (ov instanceof Long) {
      ots = (Long) ov;
    } else if (ov instanceof Integer) {
      // logger.warn("Invalid logTimestamp(int) - raw-log:" + new String(event.getBody()));
      ots = ((Integer) ov).longValue();
    } else if (ov instanceof String) {
      // logger.warn("Invalid logTimestamp(string) - raw-log:" + new String(event.getBody()));
      ots = Long.parseLong((String) ov);
    }

    if (ots == null) {
      // logger.warn("Invalid logTimestamp(empty) - raw-log:" + new String(event.getBody()));
      // return new Text("9999");
      return null;
    }

    Integer oid = (Integer) data.get("oid");
    if (oid == null) oid = oidSerial.incrementAndGet();

    Integer ser = serial.incrementAndGet();
    return String.format("%s.%04d%04d", timeFmt.print(ots), oid % 10000, ser % 10000);
  }
Example #11
0
 /**
  * Increases the life count.
  *
  * @see com.sun.star.uno.IBridge#acquire
  */
 public void acquire() {
   if (DEBUG) {
     int x = _life_count.incrementAndGet();
     System.err.println("##### " + getClass().getName() + ".acquire:" + x);
   } else {
     _life_count.incrementAndGet();
   }
 }
 public int generateOpaque() {
   int rv = SEQ_NUMBER.incrementAndGet();
   while (rv < 0) {
     SEQ_NUMBER.compareAndSet(rv, 0);
     rv = SEQ_NUMBER.incrementAndGet();
   }
   return rv;
 }
 private int generateTaskId() {
   // get the next ID but avoid an invalid ID
   int taskId = nextTaskId.incrementAndGet();
   while (taskId == FileDeletionTask.INVALID_TASK_ID) {
     taskId = nextTaskId.incrementAndGet();
   }
   return taskId;
 }
Example #14
0
  /**
   * this method finds potential options based on the detected main subject; it is usually used when
   * none of the ontology-related annotations exist
   *
   * @param key
   * @return
   */
  public List<Vote> generateGenericVotes(
      SuggestionKey key, POC poc, boolean addNone, Integer max, List<SemanticConcept> toSkip) {
    Set<String> avoidThese = new HashSet<String>();
    if (toSkip != null)
      for (SemanticConcept concept : toSkip) {
        String uri = concept.getOntologyElement().getData().toString();
        avoidThese.add(uri);
      }
    String text = key.getText();
    List<Vote> votes = new ArrayList<Vote>();
    List<OntologyElement> elements;
    try {
      elements = findGenericOntologyElements(max);

      for (OntologyElement element : elements) {
        if (avoidThese.contains(element.getData().toString())) continue;
        element.setAnnotation(poc.getAnnotation());
        // run some similarity metric here and use some threshold...
        // if similarityScore>threshold then add this to the
        // clarificationOptions
        String pPropertyShortName = "";
        String suggestion = ((SerializableURI) element.getData()).toString();
        try {
          SerializableURI elementUri = new SerializableURI(suggestion, false);
          pPropertyShortName = elementUri.getResourceName();
        } catch (Exception e) {
          pPropertyShortName = suggestion;
        }
        String niceLabel = StringUtil.beautifyString(pPropertyShortName);
        Vote vote = new Vote();
        long id = incrementer.incrementAndGet();
        vote.setId(id);
        SemanticConcept candidateSemanticConcept = new SemanticConcept();
        candidateSemanticConcept.setOntologyElement(element);
        SemanticConcept clonedConcept = (SemanticConcept) candidateSemanticConcept.clone();
        vote.setCandidate(clonedConcept);
        double totalSimilarity = similarityCalculator.findSimilarity(text, niceLabel);
        vote.setVote(totalSimilarity);
        votes.add(vote);
        votes.addAll(addAdditionalVotes(element, poc, text, pPropertyShortName, false));
      }

      // here we add datatypeProperties with no domain etc.
      votes.addAll(
          generateVotesFromOntologyElements(findHangingElements(), avoidThese, poc, null, text));
    } catch (Exception e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    // add None element
    if (addNone) {
      Vote vote = VoteGenerator.generateNoneVote(incrementer.incrementAndGet());
      vote.getCandidate().getOntologyElement().setAnnotation(poc.getAnnotation());
      votes.add(vote);
    }
    return votes;
  }
 /** Generate an opaque ID. */
 static int generateOpaque() {
   int rv = seqNumber.incrementAndGet();
   while (rv < 0) {
     if (seqNumber.compareAndSet(rv, 0)) {
       rv = seqNumber.incrementAndGet();
     }
   }
   return rv;
 }
 /**
  * Return a new observe option number. This method is thread-safe as it increases the option
  * number atomically.
  *
  * @return a new observe option number
  */
 public int getNextObserveNumber() {
   int next = number.incrementAndGet();
   while (next >= 1 << 24) {
     number.compareAndSet(next, 0);
     next = number.incrementAndGet();
   }
   // assert 0 <= next && next < 1<<24;
   return next;
 }
 public void store(K key, V value) {
   store.put(key, value);
   callCount.incrementAndGet();
   storeCount.incrementAndGet();
   if (storeLatch != null) {
     storeLatch.countDown();
   }
   events.offer(STORE_EVENTS.STORE);
 }
Example #18
0
 @Test
 public void failAfter() throws Exception {
   for (int i = 0; i < 2; i++) {
     AtomicInteger count = new AtomicInteger();
     int val = i;
     TestSuite suite =
         TestSuite.create("my_suite")
             .test("my_test_1", context -> count.compareAndSet(0, 1))
             .test(
                 "my_test_2",
                 context -> {
                   if (val == 0) {
                     count.compareAndSet(1, 2);
                   } else {
                     count.compareAndSet(2, 3);
                   }
                 });
     if (i == 0) {
       suite =
           suite.after(
               context -> {
                 count.incrementAndGet();
                 context.fail("the_message");
               });
     } else {
       AtomicBoolean failed = new AtomicBoolean();
       suite =
           suite.afterEach(
               context -> {
                 count.incrementAndGet();
                 if (failed.compareAndSet(false, true)) {
                   context.fail("the_message");
                 }
               });
     }
     TestReporter reporter = new TestReporter();
     run(suite, reporter);
     reporter.await();
     if (i == 0) {
       assertEquals(3, count.get());
       assertEquals(1, reporter.exceptions.size());
       assertEquals(2, reporter.results.size());
       assertEquals("my_test_1", reporter.results.get(0).name());
       assertTrue(reporter.results.get(0).succeeded());
       assertEquals("my_test_2", reporter.results.get(1).name());
       assertTrue(reporter.results.get(1).succeeded());
     } else {
       assertEquals(4, count.get());
       assertEquals(0, reporter.exceptions.size());
       assertEquals(2, reporter.results.size());
       assertEquals("my_test_1", reporter.results.get(0).name());
       assertTrue(reporter.results.get(0).failed());
       assertEquals("my_test_2", reporter.results.get(1).name());
       assertTrue(reporter.results.get(1).succeeded());
     }
   }
 }
 /** incrementAndGet increments and returns current value */
 public void testIncrementAndGet() {
   AtomicInteger ai = new AtomicInteger(1);
   assertEquals(2, ai.incrementAndGet());
   assertEquals(2, ai.get());
   ai.set(-2);
   assertEquals(-1, ai.incrementAndGet());
   assertEquals(0, ai.incrementAndGet());
   assertEquals(1, ai.incrementAndGet());
   assertEquals(1, ai.get());
 }
Example #20
0
 public static final void offerReadLatency(long latencyNanos, boolean pread) {
   if (pread) {
     fsPreadLatenciesNanos.offer(latencyNanos); // might be silently dropped, if the queue is full
     preadOps.incrementAndGet();
     preadTimeNano.addAndGet(latencyNanos);
   } else {
     fsReadLatenciesNanos.offer(latencyNanos); // might be silently dropped, if the queue is full
     readTimeNano.addAndGet(latencyNanos);
     readOps.incrementAndGet();
   }
 }
  @Test
  public void testGroupingByWithDomain() {
    List<String> data = Arrays.asList("a", "foo", "test", "ququq", "bar", "blahblah");
    Collector<String, ?, String> collector =
        MoreCollectors.collectingAndThen(
            MoreCollectors.groupingBy(
                String::length,
                IntStreamEx.range(10).boxed().toSet(),
                TreeMap::new,
                MoreCollectors.first()),
            Object::toString);
    checkShortCircuitCollector(
        "groupingWithDomain",
        "{0=Optional.empty, 1=Optional[a], 2=Optional.empty, 3=Optional[foo], 4=Optional[test], 5=Optional[ququq], "
            + "6=Optional.empty, 7=Optional.empty, 8=Optional[blahblah], 9=Optional.empty}",
        data.size(),
        data::stream,
        collector);

    Map<String, String> name2sex = new LinkedHashMap<>();
    name2sex.put("Mary", "Girl");
    name2sex.put("John", "Boy");
    name2sex.put("James", "Boy");
    name2sex.put("Lucie", "Girl");
    name2sex.put("Fred", "Boy");
    name2sex.put("Thomas", "Boy");
    name2sex.put("Jane", "Girl");
    name2sex.put("Ruth", "Girl");
    name2sex.put("Melanie", "Girl");
    Collector<Entry<String, String>, ?, Map<String, List<String>>> groupingBy =
        MoreCollectors.groupingBy(
            Entry::getValue,
            StreamEx.of("Girl", "Boy").toSet(),
            MoreCollectors.mapping(Entry::getKey, MoreCollectors.head(2)));
    AtomicInteger counter = new AtomicInteger();
    Map<String, List<String>> map =
        EntryStream.of(name2sex).peek(c -> counter.incrementAndGet()).collect(groupingBy);
    assertEquals(Arrays.asList("Mary", "Lucie"), map.get("Girl"));
    assertEquals(Arrays.asList("John", "James"), map.get("Boy"));
    assertEquals(4, counter.get());

    Collector<Entry<String, String>, ?, Map<String, String>> groupingByJoin =
        MoreCollectors.groupingBy(
            Entry::getValue,
            StreamEx.of("Girl", "Boy").toSet(),
            MoreCollectors.mapping(
                Entry::getKey, Joining.with(", ").maxChars(16).cutAfterDelimiter()));
    counter.set(0);
    Map<String, String> mapJoin =
        EntryStream.of(name2sex).peek(c -> counter.incrementAndGet()).collect(groupingByJoin);
    assertEquals("Mary, Lucie, ...", mapJoin.get("Girl"));
    assertEquals("John, James, ...", mapJoin.get("Boy"));
    assertEquals(7, counter.get());
  }
  /**
   * Increment the {@link #communicationExceptionCounter} if the given throwable or one of its cause
   * is an instance of on of {@link #communicationExceptionsTypes} ; otherwise, increment {@link
   * #otherExceptionCounter}.
   */
  public void incrementExceptionCount(Throwable throwable) {

    if (throwable instanceof ServiceUnavailableException) {
      serviceUnavailableExceptionCounter.incrementAndGet();
    } else if (containsThrowableOfType(throwable, communicationExceptionsTypes)) {
      communicationExceptionCounter.incrementAndGet();
    } else if (containsThrowableOfType(throwable, businessExceptionsTypes)) {
      businessExceptionCounter.incrementAndGet();
    } else {
      otherExceptionCounter.incrementAndGet();
    }
  }
  private void performOnReplica(final ShardRouting shard, final ReplicaRequest replicaRequest) {
    if (logger.isTraceEnabled()) {
      logger.trace(
          "[{}] sending op [{}] to replica {} for request [{}]",
          shard.shardId(),
          opType,
          shard,
          replicaRequest);
    }

    totalShards.incrementAndGet();
    pendingShards.incrementAndGet();
    replicasProxy.performOn(
        shard,
        replicaRequest,
        new ActionListener<TransportResponse.Empty>() {
          @Override
          public void onResponse(TransportResponse.Empty empty) {
            successfulShards.incrementAndGet();
            decPendingAndFinishIfNeeded();
          }

          @Override
          public void onFailure(Exception replicaException) {
            logger.trace(
                "[{}] failure while performing [{}] on replica {}, request [{}]",
                replicaException,
                shard.shardId(),
                opType,
                shard,
                replicaRequest);
            if (ignoreReplicaException(replicaException)) {
              decPendingAndFinishIfNeeded();
            } else {
              RestStatus restStatus = ExceptionsHelper.status(replicaException);
              shardReplicaFailures.add(
                  new ReplicationResponse.ShardInfo.Failure(
                      shard.shardId(), shard.currentNodeId(), replicaException, restStatus, false));
              String message =
                  String.format(Locale.ROOT, "failed to perform %s on replica %s", opType, shard);
              logger.warn("[{}] {}", replicaException, shard.shardId(), message);
              replicasProxy.failShard(
                  shard,
                  primary.routingEntry(),
                  message,
                  replicaException,
                  ReplicationOperation.this::decPendingAndFinishIfNeeded,
                  ReplicationOperation.this::onPrimaryDemoted,
                  throwable -> decPendingAndFinishIfNeeded());
            }
          }
        });
  }
Example #24
0
  Object doExecute(String requestName, Statement statement, Method method, Object[] args)
      throws IllegalAccessException, InvocationTargetException {
    assert requestName != null;
    assert statement != null;
    assert method != null;

    // on ignore les requêtes explain exécutées par DatabaseInformations
    if (!sqlCounter.isDisplayed() || requestName.startsWith("explain ")) {
      ACTIVE_CONNECTION_COUNT.incrementAndGet();
      try {
        return method.invoke(statement, args);
      } finally {
        ACTIVE_CONNECTION_COUNT.decrementAndGet();
      }
    }

    final long start = System.currentTimeMillis();
    boolean systemError = true;
    try {
      ACTIVE_CONNECTION_COUNT.incrementAndGet();

      // note perf: selon un paramètre current-sql(/requests)-disabled,
      // on pourrait ici ne pas binder un nouveau contexte à chaque requête sql
      sqlCounter.bindContext(requestName, requestName, null, -1);

      final Object result = method.invoke(statement, args);
      systemError = false;
      return result;
    } catch (final InvocationTargetException e) {
      if (e.getCause() instanceof SQLException) {
        final int errorCode = ((SQLException) e.getCause()).getErrorCode();
        if (errorCode >= 20000 && errorCode < 30000) {
          // Dans Oracle par exemple, les erreurs 20000 à 30000 sont standardisées
          // comme étant des erreurs lancées par l'application dans des procédures stockées
          // pour être traitées comme des erreurs de saisies ou comme des règles de gestion.
          // Ce ne sont donc pas des erreurs systèmes.
          systemError = false;
        }
      }
      throw e;
    } finally {
      // Rq : on n'utilise pas la création du statement et l'appel à la méthode close du statement
      // comme début et fin d'une connexion active, car en fonction de l'application
      // la méthode close du statement peut ne jamais être appelée
      // (par exemple, seule la méthode close de la connection peut être appelée ce qui ferme aussi
      // le statement)
      // Rq : pas de temps cpu pour les requêtes sql car c'est 0 ou quasiment 0
      ACTIVE_CONNECTION_COUNT.decrementAndGet();
      final long duration = Math.max(System.currentTimeMillis() - start, 0);
      sqlCounter.addRequest(requestName, duration, -1, systemError, -1);
    }
  }
Example #25
0
  /**
   * Checks client health periodically to see if we are connected. Tries to reconnect if not
   * connected.
   */
  private void checkClient() {

    try {

      /** If the errorCount is greater than 0, make sure we are still connected. */
      if (errorCount.get() > 0) {
        errorCount.set(0);
        if (backendServiceHttpClient == null || backendServiceHttpClient.isClosed()) {

          if (backendServiceHttpClient != null) {
            try {
              backendServiceHttpClient.stop();
            } catch (Exception ex) {
              logger.debug("Was unable to stop the client connection", ex);
            }
          }
          backendServiceHttpClient = httpClientBuilder.buildAndStart();
          lastHttpClientStart = time;
        }
      }

      /** If the ping builder is present, use it to ping the service. */
      if (pingBuilder.isPresent()) {

        if (backendServiceHttpClient != null) {
          pingBuilder
              .get()
              .setBinaryReceiver(
                  (code, contentType, body) -> {
                    if (code >= 200 && code < 299) {
                      pingCount.incrementAndGet();
                    } else {
                      errorCount.incrementAndGet();
                    }
                  })
              .setErrorHandler(
                  e -> {
                    logger.error("Error doing ping operation", e);
                    errorCount.incrementAndGet();
                  });

          final HttpRequest httpRequest = pingBuilder.get().build();

          backendServiceHttpClient.sendHttpRequest(httpRequest);
        }
      }

    } catch (Exception ex) {
      errorHandler.accept(ex);
      logger.error("Unable to check connection");
    }
  }
Example #26
0
 @Override
 public void execute() {
   try (Jedis jedis = sentinelPool.getResource()) {
     String ret =
         jedis.setex("" + failCount.incrementAndGet(), 10000, Thread.currentThread().getName());
     if (ret == null || !"OK".equals(ret)) System.err.println("" + failCount.get() + " fail");
   } catch (Exception e) {
     // 记录错误的次数
     failCount.incrementAndGet();
     System.err.println(e.getMessage());
     Thread.currentThread().interrupt();
   }
 } // --> end function execute
    @Bean
    public OrchestrateTemplate orchestrateTemplate() {

      OrchestrateTemplate template = new OrchestrateTemplate();
      template.setEndpoint("http://localhost:5124/v0");
      template.setPort(5124);
      template.setUseSSL(false);
      template.setApiKey("OUR-API-KEY");
      template.addPreSaveListener(i -> preSaveCount.incrementAndGet());
      template.addPostSaveListener(i -> postSaveCount.incrementAndGet());

      return template;
    }
 /**
  * Add a {@link SelectorHandler}
  *
  * @param selectorHandler - the {@link SelectorHandler}
  */
 public void addSelectorHandler(SelectorHandler selectorHandler) {
   selectorHandlers.add(selectorHandler);
   if (stateHolder.getState(false) != null && !State.STOPPED.equals(stateHolder.getState())) {
     addSelectorHandlerOnReadControllers(selectorHandler);
     if (readySelectorHandlerCounter != null) {
       readySelectorHandlerCounter.incrementAndGet();
     }
     if (stoppedSelectorHandlerCounter != null) {
       stoppedSelectorHandlerCounter.incrementAndGet();
     }
     startSelectorHandlerRunner(selectorHandler, true);
   }
 }
Example #29
0
 /**
  * Returns the index for the passed enum type
  *
  * @param enumType The enum type to get the index for
  * @return the index for the passed enum type
  */
 public int index(Class<T> enumType) {
   if (!indexByName.containsKey(enumType.getName())) {
     synchronized (indexByName) {
       if (!indexByName.containsKey(enumType.getName())) {
         indexByName.put(enumType.getName(), enumType);
         int index = INDEX_SEQ.incrementAndGet();
         indexByIndex.put(INDEX_SEQ.incrementAndGet(), enumType);
         return index;
       }
     }
   }
   return indexByIndex.inverse().get(enumType);
 }
  @Test
  public void shouldFailUntilImportExecutes() throws Exception {
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().create();

    final Set<String> imports =
        new HashSet<String>() {
          {
            add("import java.awt.Color");
          }
        };

    final AtomicInteger successes = new AtomicInteger(0);
    final AtomicInteger failures = new AtomicInteger(0);

    // issue 1000 scripts in one thread using a class that isn't imported.  this will result in
    // failure.
    // while that thread is running start a new thread that issues an addImports to include that
    // class.
    // this should block further evals in the first thread until the import is complete at which
    // point
    // evals in the first thread will resume and start to succeed
    final Thread t1 =
        new Thread(
            () ->
                IntStream.range(0, 1000)
                    .mapToObj(i -> gremlinExecutor.eval("Color.BLACK"))
                    .forEach(
                        f -> {
                          f.exceptionally(t -> failures.incrementAndGet()).join();
                          if (!f.isCompletedExceptionally()) successes.incrementAndGet();
                        }));

    final Thread t2 =
        new Thread(
            () -> {
              while (failures.get() < 500) {}
              gremlinExecutor.getScriptEngines().addImports(imports);
            });

    t1.start();
    t2.start();

    t1.join();
    t2.join();

    assertTrue(successes.intValue() > 0);
    assertTrue(failures.intValue() >= 500);

    gremlinExecutor.close();
  }