Beispiel #1
0
  @Test
  public void testHandshakeFailsBadTransport() throws Exception {
    LongPollingTransport transport =
        new LongPollingTransport(null, httpClient) {
          @Override
          protected void customize(Request request) {
            // Modify the request so that the server chokes it
            request.method(HttpMethod.PUT);
          }
        };
    final AtomicReference<CountDownLatch> latch = new AtomicReference<>(new CountDownLatch(1));
    BayeuxClient client = new BayeuxClient(cometdURL, transport);
    client
        .getChannel(Channel.META_HANDSHAKE)
        .addListener(
            new ClientSessionChannel.MessageListener() {
              public void onMessage(ClientSessionChannel channel, Message message) {
                Assert.assertFalse(message.isSuccessful());
                latch.get().countDown();
              }
            });
    client.handshake();
    Assert.assertTrue(latch.get().await(5, TimeUnit.SECONDS));

    // Be sure it backoffs and retries
    latch.set(new CountDownLatch(1));
    Assert.assertTrue(latch.get().await(client.getBackoffIncrement() * 2, TimeUnit.MILLISECONDS));

    Assert.assertTrue(client.disconnect(1000));

    // Be sure it does not retry
    latch.set(new CountDownLatch(1));
    Assert.assertFalse(latch.get().await(client.getBackoffIncrement() * 3, TimeUnit.MILLISECONDS));
  }
  public void testOnOutOfMemoryErrorCheck() {
    final AtomicBoolean isSeccompInstalled = new AtomicBoolean();
    final AtomicReference<String> onOutOfMemoryError = new AtomicReference<>();
    final BootstrapCheck.MightForkCheck check =
        new BootstrapCheck.OnOutOfMemoryErrorCheck() {
          @Override
          boolean isSeccompInstalled() {
            return isSeccompInstalled.get();
          }

          @Override
          String onOutOfMemoryError() {
            return onOutOfMemoryError.get();
          }
        };

    final String command = randomAsciiOfLength(16);
    runMightForkTest(
        check,
        isSeccompInstalled,
        () -> onOutOfMemoryError.set(randomBoolean() ? "" : null),
        () -> onOutOfMemoryError.set(command),
        e ->
            assertThat(
                e.getMessage(),
                containsString(
                    "OnOutOfMemoryError ["
                        + command
                        + "]"
                        + " requires forking but is prevented by system call filters ([bootstrap.seccomp=true]);"
                        + " upgrade to at least Java 8u92 and use ExitOnOutOfMemoryError")));
  }
 public Map<String, ? extends Object> getInitServerProperties() {
   final Map<String, Object> map = new HashMap<String, Object>();
   final IPreferencesService preferences = Platform.getPreferencesService();
   final AtomicReference<double[]> dpi = new AtomicReference<double[]>();
   dpi.set(
       RGraphicsPreferencePage.parseDPI(
           preferences.getString(
               RGraphics.PREF_DISPLAY_QUALIFIER,
               RGraphics.PREF_DISPLAY_CUSTOM_DPI_KEY,
               null,
               null)));
   if (dpi.get() == null) {
     Display.getDefault()
         .syncExec(
             new Runnable() {
               public void run() {
                 final Point point = Display.getCurrent().getDPI();
                 dpi.set(new double[] {point.x, point.y});
               }
             });
     if (dpi.get() == null) {
       dpi.set(new double[] {96.0, 96.0});
     }
   }
   map.put("display.ppi", dpi.get()); // $NON-NLS-1$
   return map;
 }
 /** {@inheritDoc} */
 public Object processInvocation(final InterceptorContext context) throws Exception {
   Object target = targetReference.get().getInstance();
   if (target == null) {
     throw new IllegalStateException("No injection target found");
   }
   // if it's an optional injection and the injection source isn't available, then just proceed by
   // skipping the injection
   if (this.factory == null && this.optionalInjection) {
     return context.proceed();
   }
   ManagedReference reference = factory.getReference();
   boolean ok = false;
   try {
     valueReference.set(reference);
     method.invoke(target, reference.getInstance());
     Object result = context.proceed();
     ok = true;
     return result;
   } finally {
     if (!ok) {
       valueReference.set(null);
       reference.release();
     }
   }
 }
  private void onUpdateIccAvailability() {
    if (mUiccController == null) {
      return;
    }

    UiccCardApplication newUiccApplication = getUiccCardApplication();

    UiccCardApplication app = mUiccApplication.get();
    if (app != newUiccApplication) {
      if (app != null) {
        Rlog.d(TAG, "Removing stale icc objects.");
        if (mIccRecords.get() != null) {
          mIccRecords.get().unregisterForNewSms(this);
        }
        mIccRecords.set(null);
        mUiccApplication.set(null);
      }
      if (newUiccApplication != null) {
        Rlog.d(TAG, "New Uicc application found");
        mUiccApplication.set(newUiccApplication);
        mIccRecords.set(newUiccApplication.getIccRecords());
        if (mIccRecords.get() != null) {
          mIccRecords.get().registerForNewSms(this, EVENT_NEW_ICC_SMS, null);
        }
      }
    }
  }
Beispiel #6
0
  public SpoutEntity(
      SpoutEngine engine,
      Transform transform,
      Controller controller,
      int viewDistance,
      UUID uid,
      boolean load) {
    id.set(NOTSPAWNEDID);
    this.transform.set(transform);

    if (uid != null) {
      this.uid = uid;
    } else {
      this.uid = UUID.randomUUID();
    }

    chunkLive = new AtomicReference<Chunk>();
    entityManagerLive = new AtomicReference<EntityManager>();
    controllerLive = new AtomicReference<Controller>();

    if (transform != null && load) {
      chunkLive.set(transform.getPosition().getWorld().getChunkFromBlock(transform.getPosition()));
      entityManagerLive.set(((SpoutRegion) chunkLive.get().getRegion()).getEntityManager());
    }

    viewDistanceLive.set(viewDistance);

    controllerLive.set(controller);
    if (controller != null) {
      controller.attachToEntity(this);
      if (controller instanceof PlayerController) {
        setObserver(true);
      }
    }
  }
  /**
   * Transitions to the {@code newState} if not already in that state and calls any associated event
   * listener.
   */
  private void transitionTo(State newState, CheckedRunnable listener) {
    boolean transitioned = false;
    synchronized (this) {
      if (!getState().equals(newState)) {
        switch (newState) {
          case CLOSED:
            state.set(new ClosedState(this));
            break;
          case OPEN:
            state.set(new OpenState(this));
            break;
          case HALF_OPEN:
            state.set(new HalfOpenState(this));
            break;
        }
        transitioned = true;
      }
    }

    if (transitioned && listener != null) {
      try {
        listener.run();
      } catch (Exception ignore) {
      }
    }
  }
  public void receiveMail(ThreadService.Event event) {
    synchronized (this) {
      // if we're already aborting, we can receive no further mail
      if (status.get() == Status.ABORTING) return;

      // FIXME: this was not checking null before, but maybe it should
      mail.set(event);
      switch (event.type) {
        case KILL:
          status.set(Status.ABORTING);
      }

      // If this thread is sleeping or stopped, wake it
      notify();
    }

    // interrupt the target thread in case it's blocking or waiting
    // WARNING: We no longer interrupt the target thread, since this usually means
    // interrupting IO and with NIO that means the channel is no longer usable.
    // We either need a new way to handle waking a target thread that's waiting
    // on IO, or we need to accept that we can't wake such threads and must wait
    // for them to complete their operation.
    // threadImpl.interrupt();

    // new interrupt, to hopefully wake it out of any blocking IO
    this.interrupt();
  }
Beispiel #9
0
  /**
   * Creates a dummy output directory without compiling the module. Either this method or {@link
   * #precompile} should be called first.
   */
  synchronized Job.Result initWithoutPrecompile(TreeLogger logger)
      throws UnableToCompleteException {

    long startTime = System.currentTimeMillis();
    CompileDir compileDir = outboxDir.makeCompileDir(logger);
    TreeLogger compileLogger = makeCompileLogger(compileDir, logger);
    ModuleDef module;
    try {
      module = loadModule(compileLogger);

      logger.log(TreeLogger.INFO, "Loading Java files in " + inputModuleName + ".");
      CompilerOptions loadOptions = new CompilerOptionsImpl(compileDir, inputModuleName, options);
      compilerContext = compilerContextBuilder.options(loadOptions).unitCache(unitCache).build();

      // Loads and parses all the Java files in the GWT application using the JDT.
      // (This is warmup to make compiling faster later; we stop at this point to avoid
      // needing to know the binding properties.)
      module.getCompilationState(compileLogger, compilerContext);

      setUpCompileDir(compileDir, module, compileLogger);
      if (launcherDir != null) {
        launcherDir.update(module, compileDir, compileLogger);
      }

      outputModuleName.set(module.getName());
    } finally {
      // Make the compile log available no matter what happens.
      lastBuild.set(compileDir);
    }

    long elapsedTime = System.currentTimeMillis() - startTime;
    compileLogger.log(TreeLogger.Type.INFO, "Module setup completed in " + elapsedTime + " ms");

    return new Result(compileDir, module.getName(), null);
  }
Beispiel #10
0
  private synchronized MinnBot initCommands()
      throws UnknownHostException, UnsupportedDataTypeException {
    try {
      EvalUtil.init();
    } catch (ScriptException e) {
      logger.logThrowable(e);
    }
    // User commands
    tmp = new PublicManager(prefix, logger, this);
    AtomicReference<CmdManager> manager = new AtomicReference<>(tmp);
    handler.registerManager(manager.get());

    // Voice
    if (audio) {
      manager.set(new AudioCommandManager(prefix, logger));
      handler.registerManager(manager.get());
    }

    manager.set(new RoleCommandManager(prefix, logger));
    handler.registerManager(manager.get());

    manager.set(new GoofyManager(prefix, logger, giphy, this));
    handler.registerManager(manager.get());

    manager.set(new CustomManager(prefix, logger));
    handler.registerManager(manager.get());
    return this;
  }
  @SuppressWarnings("nls")
  private TodorooCursor<Task> constructCursor() {
    String tagName = null;
    if (getActiveTagData() != null) tagName = getActiveTagData().getValue(TagData.NAME);

    String[] emergentTags = TagService.getInstance().getEmergentTags();
    StringProperty tagProperty =
        new StringProperty(null, TAGS_METADATA_JOIN + "." + TagService.TAG.name);

    Criterion tagsJoinCriterion =
        Criterion.and(
            Field.field(TAGS_METADATA_JOIN + "." + Metadata.KEY.name)
                .eq(TagService.KEY), // $NON-NLS-1$
            Task.ID.eq(Field.field(TAGS_METADATA_JOIN + "." + Metadata.TASK.name)),
            Criterion.not(tagProperty.in(emergentTags)));
    if (tagName != null)
      tagsJoinCriterion =
          Criterion.and(
              tagsJoinCriterion,
              Field.field(TAGS_METADATA_JOIN + "." + TagService.TAG.name).neq(tagName));

    // TODO: For now, we'll modify the query to join and include the task rabbit and tag data here.
    // Eventually, we might consider restructuring things so that this query is constructed
    // elsewhere.
    String joinedQuery =
        Join.left(
                    Metadata.TABLE.as(TR_METADATA_JOIN),
                    Criterion.and(
                        Field.field(TR_METADATA_JOIN + "." + Metadata.KEY.name)
                            .eq(TaskRabbitMetadata.METADATA_KEY), // $NON-NLS-1$
                        Task.ID.eq(Field.field(TR_METADATA_JOIN + "." + Metadata.TASK.name))))
                .toString() //$NON-NLS-1$
            + Join.left(Metadata.TABLE.as(TAGS_METADATA_JOIN), tagsJoinCriterion)
                .toString() //$NON-NLS-1$
            + filter.getSqlQuery();

    sqlQueryTemplate.set(SortHelper.adjustQueryForFlagsAndSort(joinedQuery, sortFlags, sortSort));

    String groupedQuery;
    if (sqlQueryTemplate.get().contains("GROUP BY")) groupedQuery = sqlQueryTemplate.get();
    else if (sqlQueryTemplate.get().contains("ORDER BY")) // $NON-NLS-1$
    groupedQuery =
          sqlQueryTemplate
              .get()
              .replace("ORDER BY", "GROUP BY " + Task.ID + " ORDER BY"); // $NON-NLS-1$
    else groupedQuery = sqlQueryTemplate.get() + " GROUP BY " + Task.ID;
    sqlQueryTemplate.set(groupedQuery);

    // Peform query
    try {
      return taskService.fetchFiltered(sqlQueryTemplate.get(), null, taskProperties());
    } catch (SQLiteException e) {
      // We don't show this error anymore--seems like this can get triggered
      // by a strange bug, but there seems to not be any negative side effect.
      // For now, we'll suppress the error
      // See http://astrid.com/home#tags-7tsoi/task-1119pk
      return null;
    }
  }
 @SuppressWarnings("unused") // invoked by reflection from tearDown2()
 private static void cleanup() {
   disconnectFromDS();
   MemoryAllocatorImpl.freeOffHeapMemory();
   cache.set(null);
   system.set(null);
   isSmallerVM.set(false);
 }
Beispiel #13
0
  private TodorooCursor<Task> constructCursor() {
    String tagName = null;
    if (getActiveTagData() != null) {
      tagName = getActiveTagData().getName();
    }

    Criterion tagsJoinCriterion =
        Criterion.and(
            Field.field(TAGS_METADATA_JOIN + "." + Metadata.KEY.name)
                .eq(TaskToTagMetadata.KEY), // $NON-NLS-1$
            Field.field(TAGS_METADATA_JOIN + "." + Metadata.DELETION_DATE.name).eq(0),
            Task.ID.eq(Field.field(TAGS_METADATA_JOIN + "." + Metadata.TASK.name)));
    if (tagName != null) {
      tagsJoinCriterion =
          Criterion.and(
              tagsJoinCriterion,
              Field.field(TAGS_METADATA_JOIN + "." + TaskToTagMetadata.TAG_NAME.name).neq(tagName));
    }

    // TODO: For now, we'll modify the query to join and include the things like tag data here.
    // Eventually, we might consider restructuring things so that this query is constructed
    // elsewhere.
    String joinedQuery =
        Join.left(Metadata.TABLE.as(TAGS_METADATA_JOIN), tagsJoinCriterion)
                .toString() //$NON-NLS-1$
            + Join.left(
                TaskAttachment.TABLE.as(FILE_METADATA_JOIN),
                Task.UUID.eq(Field.field(FILE_METADATA_JOIN + "." + TaskAttachment.TASK_UUID.name)))
            + filter.getSqlQuery();

    sqlQueryTemplate.set(SortHelper.adjustQueryForFlagsAndSort(joinedQuery, sortFlags, sortSort));

    String groupedQuery;
    if (sqlQueryTemplate.get().contains("GROUP BY")) {
      groupedQuery = sqlQueryTemplate.get();
    } else if (sqlQueryTemplate.get().contains("ORDER BY")) // $NON-NLS-1$
    {
      groupedQuery =
          sqlQueryTemplate
              .get()
              .replace("ORDER BY", "GROUP BY " + Task.ID + " ORDER BY"); // $NON-NLS-1$
    } else {
      groupedQuery = sqlQueryTemplate.get() + " GROUP BY " + Task.ID;
    }
    sqlQueryTemplate.set(groupedQuery);

    // Peform query
    try {
      return taskService.fetchFiltered(sqlQueryTemplate.get(), null, taskProperties());
    } catch (SQLiteException e) {
      // We don't show this error anymore--seems like this can get triggered
      // by a strange bug, but there seems to not be any negative side effect.
      // For now, we'll suppress the error
      // See http://astrid.com/home#tags-7tsoi/task-1119pk
      log.error(e.getMessage(), e);
      return null;
    }
  }
 private void connect(IClient client) {
   WatchKey key = new WatchKey(conn, project, kind);
   if (watches.containsKey(key)) {
     AtomicReference<IWatcher> watcherRef = watches.get(key);
     watcherRef.set(client.watch(project.getName(), this, kind));
     state.set(State.CONNECTED);
     lastConnect = System.currentTimeMillis();
   }
 }
Beispiel #15
0
 public MockSnmpAgent(final File confFile, final URL moFile) {
   super(
       BOOT_COUNT_FILE,
       confFile,
       new CommandProcessor(
           new OctetString(MPv3.createLocalEngineID(new OctetString("MOCKAGENT")))));
   m_moLoader.set(new PropertiesBackedManagedObject());
   m_moFile.set(moFile);
   agent.setWorkerPool(ThreadPool.create("RequestPool", 4));
 }
 public void clearFast() {
   result.set(UNSET);
   exception.set(UNSET);
   this.forXOf = null;
   this.essential = null;
   this.count.set(0);
   this.max.set(0);
   this.completedExceptionally = false;
   this.done = false;
 }
  private void reset() {
    clientException.set(null);
    serverException.set(null);
    clientHandler.handshakeCounter = 0;
    serverHandler.handshakeCounter = 0;
    clientChannel = null;
    serverChannel = null;

    clientSslHandler = null;
    serverSslHandler = null;
  }
  /** Cleans up resources to avoid excessive memory usage. */
  public void cleanUp() {
    topSnapshot.set(null);
    singleMsgs.clear();
    fullMsgs.clear();
    rcvdIds.clear();
    oldestNode.set(null);
    partReleaseFut = null;

    Collection<ClusterNode> rmtNodes = this.rmtNodes;

    if (rmtNodes != null) rmtNodes.clear();
  }
 public static void resetStats() {
   firstRequestStart.set(null);
   lastRequestStart.set(null);
   firstRequestEnd.set(null);
   lastRequestEnd.set(null);
   startedRequests.set(0L);
   completedRequests.set(0L);
   concurrency.set(0L);
   maxConcurrency.set(0L);
   totConcurrency.set(0L);
   avgConcurrency.set(0.0D);
 }
  @Test
  public void testDoubleListener() {
    final Message message = Message.create("Ziz");
    final String content = "abyssum abyssus invocat";

    stub2.listen(message, (controller, subject, args) -> inbox1.set(args[0]));
    stub2.listen(message, (controller, subject, args) -> inbox2.set(args[0]));
    stub1.shout(message, "", content);

    assertEquals(content, inbox1.get());
    assertEquals(content, inbox2.get());
  }
  @Test
  public void testResubscribeOnRehandshake() throws Exception {
    AtomicReference<CountDownLatch> messageLatch = new AtomicReference<CountDownLatch>();
    ResubscribeOnRehandshakeService s = new ResubscribeOnRehandshakeService(messageLatch);
    boolean processed = processor.process(s);
    assertTrue(processed);

    final CountDownLatch subscribeLatch = new CountDownLatch(1);
    bayeuxClient
        .getChannel(Channel.META_SUBSCRIBE)
        .addListener(
            new ClientSessionChannel.MessageListener() {
              public void onMessage(ClientSessionChannel channel, Message message) {
                subscribeLatch.countDown();
              }
            });

    bayeuxClient.handshake();
    assertTrue(bayeuxClient.waitFor(1000, BayeuxClient.State.CONNECTED));
    assertTrue(subscribeLatch.await(5, TimeUnit.SECONDS));

    messageLatch.set(new CountDownLatch(1));
    bayeuxClient.getChannel("/foo").publish(new HashMap());
    assertTrue(messageLatch.get().await(5, TimeUnit.SECONDS));

    bayeuxClient.disconnect();
    assertTrue(bayeuxClient.waitFor(1000, BayeuxClient.State.DISCONNECTED));

    // Rehandshake
    bayeuxClient.handshake();
    assertTrue(bayeuxClient.waitFor(1000, BayeuxClient.State.CONNECTED));

    // Republish, it must have resubscribed
    messageLatch.set(new CountDownLatch(1));
    bayeuxClient.getChannel("/foo").publish(new HashMap());
    assertTrue(messageLatch.get().await(5, TimeUnit.SECONDS));

    bayeuxClient.disconnect();
    assertTrue(bayeuxClient.waitFor(1000, BayeuxClient.State.DISCONNECTED));

    boolean deprocessed = processor.deprocess(s);
    assertTrue(deprocessed);

    // Rehandshake
    bayeuxClient.handshake();
    assertTrue(bayeuxClient.waitFor(1000, BayeuxClient.State.CONNECTED));

    // Republish, it must not have resubscribed
    messageLatch.set(new CountDownLatch(1));
    bayeuxClient.getChannel("/foo").publish(new HashMap());
    assertFalse(messageLatch.get().await(1, TimeUnit.SECONDS));
  }
  @Override
  public synchronized void run() {
    instant.set(Instant.now());
    System.out.println(Thread.currentThread().getName() + " share  start time : " + instant.get());
    try {
      TimeUnit.SECONDS.sleep((int) Math.random() * 10);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    instant.set(Instant.now());

    System.out.println(Thread.currentThread().getName() + "share  end time : " + instant.get());
  }
  @VisibleForTesting
  protected void poll() {
    Exhibitors localExhibitors = exhibitors.get();
    Map<String, String> values = queryExhibitors(localExhibitors);

    int count = getCountFromValues(values);
    if (count == 0) {
      log.warn("0 count returned from Exhibitors. Using backup connection values.");
      values = useBackup(localExhibitors);
      count = getCountFromValues(values);
    }

    if (count > 0) {
      int port = Integer.parseInt(values.get(VALUE_PORT));
      StringBuilder newConnectionString = new StringBuilder();
      List<String> newHostnames = Lists.newArrayList();

      for (int i = 0; i < count; ++i) {
        if (newConnectionString.length() > 0) {
          newConnectionString.append(",");
        }
        String server = values.get(VALUE_SERVER_PREFIX + i);
        newConnectionString.append(server).append(":").append(port);
        newHostnames.add(server);
      }

      String newConnectionStringValue = newConnectionString.toString();
      if (!newConnectionStringValue.equals(connectionString.get())) {
        log.info(
            "Connection string has changed. Old value (%s), new value (%s)",
            connectionString.get(), newConnectionStringValue);
      }
      Exhibitors newExhibitors =
          new Exhibitors(
              newHostnames,
              localExhibitors.getRestPort(),
              new Exhibitors.BackupConnectionStringProvider() {
                @Override
                public String getBackupConnectionString() throws Exception {
                  return masterExhibitors
                      .get()
                      .getBackupConnectionString(); // this may be overloaded by clients. Make sure
                                                    // there is always a method call to get the
                                                    // value.
                }
              });
      connectionString.set(newConnectionStringValue);
      exhibitors.set(newExhibitors);
    }
  }
 @Override
 public void onResponse(final Response coapResponse) {
   LOG.debug("Received coap response: {}", coapResponse);
   try {
     final T lwM2mResponseT = buildResponse(coapResponse);
     if (lwM2mResponseT != null) {
       ref.set(lwM2mResponseT);
     }
   } catch (final RuntimeException e) {
     exception.set(e);
   } finally {
     latch.countDown();
   }
 }
Beispiel #25
0
  public void run() {

    //
    String welcome = shell.getWelcome();
    writer.println(welcome);
    writer.flush();

    //
    while (true) {
      String prompt = getPrompt();
      String line;
      try {
        writer.println();
        writer.flush();
        if ((line = reader.readLine(prompt)) == null) {
          break;
        }
      } catch (IOException e) {
        // What should we do other than that ?
        break;
      }

      //
      ShellProcess process = shell.createProcess(line);
      JLineProcessContext context = new JLineProcessContext(this);
      current.set(process);
      try {
        process.execute(context);
        try {
          context.latch.await();
        } catch (InterruptedException ignore) {
          // At the moment
        }
      } finally {
        current.set(null);
      }
      ShellResponse response = context.resp.get();

      //
      if (response instanceof ShellResponse.Cancelled) {
        // Do nothing
      } else if (response instanceof ShellResponse.Close) {
        break;
      } else {
        response.getReader().writeAnsiTo(writer);
        writer.flush();
      }
    }
  }
  @Test
  public void test_BasicAuthentication_WithAuthenticationRemoved() throws Exception {
    startBasic(new EmptyServerHandler());

    final AtomicReference<CountDownLatch> requests = new AtomicReference<>(new CountDownLatch(2));
    Request.Listener.Empty requestListener =
        new Request.Listener.Empty() {
          @Override
          public void onSuccess(Request request) {
            requests.get().countDown();
          }
        };
    client.getRequestListeners().add(requestListener);

    AuthenticationStore authenticationStore = client.getAuthenticationStore();
    URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort());
    BasicAuthentication authentication = new BasicAuthentication(uri, realm, "basic", "basic");
    authenticationStore.addAuthentication(authentication);

    Request request =
        client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure");
    ContentResponse response = request.timeout(5, TimeUnit.SECONDS).send();
    Assert.assertNotNull(response);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS));

    authenticationStore.removeAuthentication(authentication);

    requests.set(new CountDownLatch(1));
    request =
        client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure");
    response = request.timeout(5, TimeUnit.SECONDS).send();
    Assert.assertNotNull(response);
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS));

    Authentication.Result result = authenticationStore.findAuthenticationResult(request.getURI());
    Assert.assertNotNull(result);
    authenticationStore.removeAuthenticationResult(result);

    requests.set(new CountDownLatch(1));
    request =
        client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure");
    response = request.timeout(5, TimeUnit.SECONDS).send();
    Assert.assertNotNull(response);
    Assert.assertEquals(401, response.getStatus());
    Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS));
  }
  private void processBackgroundCallback(CuratorEvent event) throws Exception {
    String path = null;
    boolean nodeExists = false;
    if (event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue()) {
      path = event.getPath();
      nodeExists = true;
    } else if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
      path = event.getName();
    } else if (event.getResultCode() == KeeperException.Code.NOAUTH.intValue()) {
      log.warn("Client does not have authorisation to write node at path {}", event.getPath());
      authFailure.set(true);
      return;
    }
    if (path != null) {
      authFailure.set(false);
      nodePath.set(path);
      watchNode();

      if (nodeExists) {
        client.setData().inBackground(setDataCallback).forPath(getActualPath(), getData());
      } else {
        initialisationComplete();
      }
    } else {
      createNode();
    }
  }
  /**
   * Start the server running - accepting connections, receiving messages. If the server is already
   * running, it will not be started again. This method is designed to be called in its own thread
   * and will not return until the server is stopped.
   *
   * @throws RuntimeException if the server fails
   */
  public void run() {
    // ensure that the server is not started twice
    if (!state.compareAndSet(State.STOPPED, State.RUNNING)) {
      started(true);
      return;
    }

    Selector selector = null;
    ServerSocketChannel server = null;
    try {
      selector = Selector.open();
      server = ServerSocketChannel.open();
      server.socket().bind(new InetSocketAddress(port));
      server.configureBlocking(false);
      server.register(selector, SelectionKey.OP_ACCEPT);
      started(false);
      while (state.get() == State.RUNNING) {
        selector.select(100); // check every 100ms whether the server has been requested to stop
        for (Iterator<SelectionKey> it = selector.selectedKeys().iterator(); it.hasNext(); ) {
          SelectionKey key = it.next();
          try {
            // remove key from the ready list
            it.remove();
            if (key.isConnectable()) {
              ((SocketChannel) key.channel()).finishConnect();
            }
            if (key.isAcceptable()) {
              // accept connection
              SocketChannel client = server.accept();
              client.configureBlocking(false);
              client.socket().setTcpNoDelay(true);
              // channel is registered for further events such as read or write
              SelectionKey acceptKey = client.register(selector, SelectionKey.OP_READ);
              connection(acceptKey);
            }
            if (key.isReadable()) {
              for (ByteBuffer message : readIncomingMessage(key)) {
                messageReceived(message, key);
              }
            }
          } catch (IOException ioe) {
            resetKey(key);
            disconnected(key);
          }
        }
      }
    } catch (Throwable e) {
      throw new RuntimeException("Server failure: " + e.getMessage());
    } finally {
      try {
        selector.close();
        server.socket().close();
        server.close();
        state.set(State.STOPPED);
        stopped();
      } catch (Exception e) {
        // do nothing - server failed
      }
    }
  }
    @Get
    public void get(AtmosphereResource resource) {
      r.set(resource);
      resource
          .addEventListener(
              new OnSuspend() {
                @Override
                public void onSuspend(AtmosphereResourceEvent event) {
                  AtmosphereRequest request =
                      new AtmosphereRequest.Builder()
                          .pathInfo("/inputStreamInjection")
                          .method("POST")
                          .body("message")
                          .build();

                  try {
                    event
                        .getResource()
                        .getAtmosphereConfig()
                        .framework()
                        .doCometSupport(request, AtmosphereResponse.newInstance());
                  } catch (IOException e) {
                    e.printStackTrace();
                  } catch (ServletException e) {
                    e.printStackTrace();
                  }
                }
              })
          .suspend();
    }
    @Override
    public void run() {
      for (int i = 0; i < NUM_GROUPS; i++) {
        for (int j = 1; j <= INSERTIONS_PER_GROUP; j++) {
          // Choosing a unique object id
          int oid = i * INSERTIONS_PER_GROUP + j + oidOffset;
          rootsHolder.addRoot(getNameOID(oid, i), new ObjectID(oid, i));
        }
      }

      try {
        int index = barrier.await();
        assertEquals(2 * NUM_GROUPS * INSERTIONS_PER_GROUP, rootsHolder.size());
        if (index == 0) {
          markLookupInProgress();
        }
        barrier.await();
        if (index == 1) {
          verifyMarked();
          unmarkLookupInProgress();
        }
        barrier.await();
        if (index == 0) {
          verifyUnmarked();
        }
      } catch (Throwable throwable) {
        System.out.println(throwable.getMessage());
        throwable.printStackTrace();
        errorMarker.set(throwable);
      }
    }