Java Code Examples for java.util.concurrent.atomic.AtomicBoolean

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project big-data-plugin, under directory /shims/common/test-src/org/pentaho/hadoop/shim/common/mapred/.

Source file: RunningJobProxyTest.java

  33 
vote

@Test public void isComplete() throws IOException {
  final AtomicBoolean called=new AtomicBoolean(false);
  RunningJobProxy proxy=new RunningJobProxy(new MockRunningJob(){
    @Override public boolean isComplete() throws IOException {
      called.set(true);
      return true;
    }
  }
);
  assertTrue(proxy.isComplete());
  assertTrue(called.get());
}
 

Example 2

From project ACLS-protocol-library, under directory /aclslib/src/test/java/au/edu/uq/cmm/acslib/service/.

Source file: MonitoredThreadServiceBaseTest.java

  32 
vote

@Test public void testStartupShutdown() throws InterruptedException {
  BlockingDeque<String> status=new LinkedBlockingDeque<String>();
  AtomicBoolean killSwitch=new AtomicBoolean();
  Service service=new MTSBTestService(status,killSwitch,1,1,500);
  Assert.assertNull(status.pollFirst());
  Assert.assertEquals(State.INITIAL,service.getState());
  service.startup();
  Assert.assertEquals(State.STARTED,service.getState());
  Assert.assertEquals("running",status.pollFirst(2,TimeUnit.SECONDS));
  service.shutdown();
  Assert.assertEquals(State.STOPPED,service.getState());
  Assert.assertEquals("finished",status.pollFirst(2,TimeUnit.SECONDS));
}
 

Example 3

From project awaitility, under directory /awaitility/src/test/java/com/jayway/awaitility/.

Source file: UsingAtomicTest.java

  32 
vote

@Test(timeout=2000) public void usingAtomicBooleanAndTimeout() throws Exception {
  exception.expect(TimeoutException.class);
  exception.expectMessage("expected <true> but was <false> within 200 milliseconds.");
  AtomicBoolean atomic=new AtomicBoolean(false);
  await().atMost(200,MILLISECONDS).untilAtomic(atomic,equalTo(true));
}
 

Example 4

From project crash, under directory /shell/core/src/test/java/org/crsh/processor/term/.

Source file: AbstractProcessorTestCase.java

  32 
vote

public void testTermClose() throws Exception {
  final AtomicBoolean closed=new AtomicBoolean();
  processor.addListener(new Closeable(){
    public void close() throws IOException {
      closed.set(true);
    }
  }
);
  term.publish(TermEvent.close());
  assertJoin(thread);
  assertTrue(closed.get());
}
 

Example 5

From project dimdwarf, under directory /dimdwarf-core/src/test/java/net/orfjackal/dimdwarf/db/inmemory/.

Source file: GroupLockSpec.java

  32 
vote

public void theLockedKeyCanNotBeRelockedUntilItIsFirstUnlocked(){
  AtomicBoolean wasUnlocked=new AtomicBoolean(false);
  unlockInNewThread(handle,wasUnlocked);
  lock.lockAll("A");
  specify(wasUnlocked.get());
}
 

Example 6

From project eclipse-instasearch, under directory /instasearch/test/it/unibz/instasearch/indexing/.

Source file: SearcherTest.java

  32 
vote

private void assertFileMatches(String expectedFile,String searchString,boolean exact) throws Exception {
  AtomicBoolean isExact=new AtomicBoolean();
  List<SearchResultDoc> docs=search(searchString,isExact);
  assertEquals(expectedFile,docs.get(0).getFileName());
  assertEquals("Exact query comparison failed",exact,isExact.get());
}
 

Example 7

From project efflux, under directory /src/test/java/com/biasedbit/efflux/participant/.

Source file: DefaultParticipantDatabaseTest.java

  32 
vote

@Test public void testDoWithReceivers() throws Exception {
  this.testAddReceiver();
  final AtomicBoolean doSomething=new AtomicBoolean();
  this.database.doWithReceivers(new ParticipantOperation(){
    @Override public void doWithParticipant(    RtpParticipant participant) throws Exception {
      doSomething.set(true);
    }
  }
);
  assertTrue(doSomething.get());
}
 

Example 8

From project fastjson, under directory /src/main/java/com/alibaba/fastjson/serializer/.

Source file: AtomicBooleanSerializer.java

  32 
vote

public void write(JSONSerializer serializer,Object object,Object fieldName,Type fieldType) throws IOException {
  SerializeWriter out=serializer.getWriter();
  AtomicBoolean val=(AtomicBoolean)object;
  if (val.get()) {
    out.append("true");
  }
 else {
    out.append("false");
  }
}
 

Example 9

From project guice-jit-providers, under directory /core/test/com/google/inject/.

Source file: ProvisionListenerTest.java

  32 
vote

public void testModuleRequestInjection(){
  final AtomicBoolean notified=new AtomicBoolean();
  Guice.createInjector(new AbstractModule(){
    @Override protected void configure(){
      requestInjection(new Object(){
        @Inject Foo foo;
      }
);
      bindListener(Matchers.any(),new SpecialChecker(Foo.class,getClass().getName() + ".configure(",notified));
    }
  }
);
  assertTrue(notified.get());
}
 

Example 10

From project jackrabbit-oak, under directory /oak-mk/src/test/java/org/apache/jackrabbit/mk/blobs/.

Source file: AbstractBlobStoreTest.java

  32 
vote

public void testCloseStream() throws Exception {
  final AtomicBoolean closed=new AtomicBoolean();
  InputStream in=new InputStream(){
    public void close(){
      closed.set(true);
    }
    public int read() throws IOException {
      return -1;
    }
  }
;
  store.writeBlob(in);
  assertTrue(closed.get());
}
 

Example 11

From project jbosgi-framework, under directory /core/src/test/java/org/jboss/test/osgi/msc/.

Source file: ServiceTrackerTestCase.java

  32 
vote

@Test public void testImmediateCallToListenerAdded() throws Exception {
  final AtomicBoolean listenerAdded=new AtomicBoolean();
  ServiceListener<Object> listener=new AbstractServiceListener<Object>(){
    @Override public void listenerAdded(    ServiceController<? extends Object> controller){
      listenerAdded.set(true);
    }
  }
;
  ServiceBuilder<String> builder=serviceTarget.addService(ServiceName.of("serviceA"),new ServiceA());
  builder.addListener(listener);
  builder.install();
  Assert.assertTrue("Listener added",listenerAdded.get());
}
 

Example 12

From project jboss-common-beans, under directory /src/test/java/org/jboss/common/beans/property/.

Source file: GenericArrayEditorTestCase.java

  32 
vote

@Override public int compare(AtomicBoolean[] o1,AtomicBoolean[] o2){
  if (o1.length != o2.length) {
    return 1;
  }
  for (int index=0; index < o1.length; index++) {
    AtomicBoolean a1=o1[index];
    AtomicBoolean a2=o2[index];
    if (a1.get() != a2.get()) {
      return 1;
    }
  }
  return 0;
}
 

Example 13

From project jboss-logmanager, under directory /src/test/java/org/jboss/logmanager/.

Source file: FilterTests.java

  32 
vote

public void testAcceptAllFilter(){
  final Filter filter=AcceptAllFilter.getInstance();
  final AtomicBoolean ran=new AtomicBoolean();
  final Handler handler=new CheckingHandler(ran);
  final Logger logger=Logger.getLogger("filterTest");
  logger.setUseParentHandlers(false);
  logger.addHandler(handler);
  logger.setLevel(Level.INFO);
  logger.setFilter(filter);
  handler.setLevel(Level.INFO);
  logger.info("This is a test.");
  assertTrue("Handler wasn't run",ran.get());
}
 

Example 14

From project accent, under directory /src/test/java/net/lshift/accent/.

Source file: ControlledConnectionProxy.java

  31 
vote

public ControlledConnectionProxy(int listenPort,String id,String host,int port,BlockingCell<Exception> reportEnd) throws IOException {
  this.listenPort=listenPort;
  this.host=host;
  this.port=port;
  this.idLabel=": <" + id + "> ";
  this.reportEnd=reportEnd;
  this.started=new AtomicBoolean(false);
}
 

Example 15

From project activemq-apollo, under directory /apollo-itests/src/test/java/org/apache/activemq/apollo/.

Source file: ProducerFlowControlSendFailTest.java

  31 
vote

@Override public void ignorePubisherRecoverAfterBlock() throws Exception {
  ActiveMQConnectionFactory factory=(ActiveMQConnectionFactory)createConnectionFactory();
  factory.setUseAsyncSend(true);
  connection=(ActiveMQConnection)factory.createConnection();
  connections.add(connection);
  connection.start();
  final Session session=connection.createSession(false,Session.CLIENT_ACKNOWLEDGE);
  final MessageProducer producer=session.createProducer(queueA);
  final AtomicBoolean keepGoing=new AtomicBoolean(true);
  Thread thread=new Thread("Filler"){
    @Override public void run(){
      while (keepGoing.get()) {
        try {
          producer.send(session.createTextMessage("Test message"));
          if (gotResourceException.get()) {
            Thread.sleep(200);
          }
        }
 catch (        Exception e) {
          e.printStackTrace();
        }
      }
    }
  }
;
  thread.start();
  waitForBlockedOrResourceLimit(new AtomicBoolean(false));
  MessageConsumer consumer=session.createConsumer(queueA);
  TextMessage msg;
  for (int idx=0; idx < 10; ++idx) {
    msg=(TextMessage)consumer.receive(1000);
    if (msg != null) {
      msg.acknowledge();
    }
  }
  keepGoing.set(false);
}
 

Example 16

From project AeminiumRuntime, under directory /src/aeminium/runtime/tests/.

Source file: AtomicTaskDeadLock.java

  31 
vote

@Test(timeout=2000) public void createAtomicTaskDeadLock(){
  final AtomicBoolean deadlock=new AtomicBoolean(false);
  Runtime rt=getRuntime();
  rt.init();
  rt.addErrorHandler(new ErrorHandler(){
    @Override public void handleTaskException(    Task task,    Throwable t){
    }
    @Override public void handleTaskDuplicatedSchedule(    Task task){
    }
    @Override public void handleLockingDeadlock(){
      deadlock.set(true);
    }
    @Override public void handleInternalError(    Error err){
    }
    @Override public void handleDependencyCycle(    Task task){
    }
  }
);
  DataGroup dg1=rt.createDataGroup();
  DataGroup dg2=rt.createDataGroup();
  Task t1=createAtomicTask(rt,dg1,dg2);
  rt.schedule(t1,Runtime.NO_PARENT,Runtime.NO_DEPS);
  Task t2=createAtomicTask(rt,dg2,dg1);
  rt.schedule(t2,Runtime.NO_PARENT,Runtime.NO_DEPS);
  try {
    Thread.sleep(1500);
  }
 catch (  InterruptedException e1) {
  }
  if (!deadlock.get()) {
    Assert.fail("Could not find deadlock");
    rt.shutdown();
  }
}
 

Example 17

From project aether-core, under directory /aether-impl/src/main/java/org/eclipse/aether/internal/impl/.

Source file: DefaultArtifactResolver.java

  31 
vote

ResolutionItem(RequestTrace trace,Artifact artifact,ArtifactResult result,LocalArtifactResult local,RemoteRepository repository){
  this.trace=trace;
  this.artifact=artifact;
  this.resolved=new AtomicBoolean(false);
  this.result=result;
  this.request=result.getRequest();
  this.local=local;
  this.repository=repository;
}
 

Example 18

From project airlift, under directory /dbpool/src/test/java/io/airlift/dbpool/.

Source file: ManagedDataSourceTest.java

  31 
vote

@Test public void testAcquirePermitInterrupted() throws Exception {
  final ManagedDataSource dataSource=new MockManagedDataSource(1,new Duration(5000,MILLISECONDS));
  assertEquals(dataSource.getMaxConnectionWaitMillis(),5000);
  Connection connection=dataSource.getConnection();
  assertEquals(dataSource.getConnectionsActive(),1);
  final CountDownLatch startLatch=new CountDownLatch(1);
  final CountDownLatch endLatch=new CountDownLatch(1);
  final AtomicBoolean wasInterrupted=new AtomicBoolean();
  final AtomicReference<SQLException> exception=new AtomicReference<SQLException>();
  Thread createThread=new Thread(){
    @Override public void run(){
      startLatch.countDown();
      try {
        dataSource.getConnection();
      }
 catch (      SQLException e) {
        exception.set(e);
      }
 finally {
        wasInterrupted.set(isInterrupted());
        endLatch.countDown();
      }
    }
  }
;
  createThread.start();
  startLatch.await();
  createThread.interrupt();
  endLatch.await();
  assertTrue(wasInterrupted.get(),"createThread.isInterrupted()");
  SQLException sqlException=exception.get();
  assertNotNull(sqlException);
  assertInstanceOf(sqlException.getCause(),InterruptedException.class);
  connection.close();
  assertEquals(dataSource.getConnectionsActive(),0);
}
 

Example 19

From project Arecibo, under directory /aggregator/src/main/java/com/ning/arecibo/aggregator/concurrent/.

Source file: KeyedExecutor.java

  31 
vote

private KeyedBucket(String key){
  this.guard=new AtomicBoolean();
  this.queue=new LinkedBlockingQueue<Runnable>();
  this.key=key;
  this.waitTimeStart=new AtomicLong(0L);
  this.waitTimeEnd=new AtomicLong(0L);
}
 

Example 20

From project astyanax, under directory /src/main/java/com/netflix/astyanax/mapping/.

Source file: Mapping.java

  31 
vote

/** 
 * @param clazz clazz type to map
 * @param annotationSet annotations to use when analyzing a bean
 */
public Mapping(Class<T> clazz,AnnotationSet<?,?> annotationSet){
  this.clazz=clazz;
  String localKeyFieldName=null;
  ImmutableMap.Builder<String,Field> builder=ImmutableMap.builder();
  AtomicBoolean isKey=new AtomicBoolean();
  Set<String> usedNames=Sets.newHashSet();
  for (  Field field : clazz.getDeclaredFields()) {
    String name=mapField(field,annotationSet,builder,usedNames,isKey);
    if (isKey.get()) {
      Preconditions.checkArgument(localKeyFieldName == null);
      localKeyFieldName=name;
    }
  }
  Preconditions.checkNotNull(localKeyFieldName);
  fields=builder.build();
  idFieldName=localKeyFieldName;
}
 

Example 21

From project avro, under directory /lang/java/ipc/src/test/java/org/apache/avro/ipc/.

Source file: TestNettyServerWithCallbacks.java

  31 
vote

@Ignore @Test public void performanceTest() throws Exception {
  final int threadCount=8;
  final long runTimeMillis=10 * 1000L;
  ExecutorService threadPool=Executors.newFixedThreadPool(threadCount);
  System.out.println("Running performance test for " + runTimeMillis + "ms...");
  final AtomicLong rpcCount=new AtomicLong(0L);
  final AtomicBoolean runFlag=new AtomicBoolean(true);
  final CountDownLatch startLatch=new CountDownLatch(threadCount);
  for (int ii=0; ii < threadCount; ii++) {
    threadPool.submit(new Runnable(){
      @Override public void run(){
        try {
          startLatch.countDown();
          startLatch.await(2,TimeUnit.SECONDS);
          while (runFlag.get()) {
            rpcCount.incrementAndGet();
            Assert.assertEquals("Hello, World!",simpleClient.hello("World!"));
          }
        }
 catch (        Exception e) {
          e.printStackTrace();
        }
      }
    }
);
  }
  startLatch.await(2,TimeUnit.SECONDS);
  Thread.sleep(runTimeMillis);
  runFlag.set(false);
  threadPool.shutdown();
  Assert.assertTrue("Timed out shutting down thread pool",threadPool.awaitTermination(2,TimeUnit.SECONDS));
  System.out.println("Completed " + rpcCount.get() + " RPCs in "+ runTimeMillis+ "ms => "+ (((double)rpcCount.get() / (double)runTimeMillis) * 1000)+ " RPCs/sec, "+ ((double)runTimeMillis / (double)rpcCount.get())+ " ms/RPC.");
}
 

Example 22

From project azkaban, under directory /azkaban/src/unit/azkaban/flow/.

Source file: GroupedExecutableFlowTest.java

  31 
vote

@Test public void testAllBaseJobsCompleted() throws Exception {
  EasyMock.replay(mockFlow1,mockFlow2,props);
  final JobManager factory=EasyMock.createStrictMock(JobManager.class);
  EasyMock.replay(factory);
  final IndividualJobExecutableFlow completedJob1=new IndividualJobExecutableFlow("blah","blah",factory);
  final IndividualJobExecutableFlow completedJob2=new IndividualJobExecutableFlow("blah","blah",factory);
  flow=new GroupedExecutableFlow("blah",completedJob1,completedJob2);
  completedJob1.markCompleted();
  completedJob2.markCompleted();
  AtomicBoolean callbackWasCalled=new AtomicBoolean(false);
  flow.execute(props,new OneCallFlowCallback(callbackWasCalled){
    @Override public void theCallback(    Status status){
      Assert.assertEquals(Status.SUCCEEDED,status);
    }
  }
);
  Assert.assertTrue("Callback wasn't called!?",callbackWasCalled.get());
  EasyMock.verify(factory);
}
 

Example 23

From project bndtools, under directory /bndtools.core/src/bndtools/builder/.

Source file: NewBuilder.java

  31 
vote

boolean isCnfChanged() throws Exception {
  IProject cnfProject=WorkspaceUtils.findCnfProject();
  if (cnfProject == null) {
    logger.logError("Bnd configuration project (cnf) is not available in the Eclipse workspace.",null);
    return false;
  }
  IResourceDelta cnfDelta=getDelta(cnfProject);
  if (cnfDelta == null) {
    log(LOG_FULL,"no delta available for cnf project, ignoring");
    return false;
  }
  final AtomicBoolean result=new AtomicBoolean(false);
  cnfDelta.accept(new IResourceDeltaVisitor(){
    public boolean visit(    IResourceDelta delta) throws CoreException {
      if (!isChangeDelta(delta))       return false;
      if (IResourceDelta.MARKERS == delta.getFlags())       return false;
      IResource resource=delta.getResource();
      if (resource.getType() == IResource.ROOT || resource.getType() == IResource.PROJECT)       return true;
      if (resource.getType() == IResource.FOLDER && resource.getName().equals("ext")) {
        log(LOG_FULL,"detected change in cnf due to resource %s, kind=0x%x, flags=0x%x",resource.getFullPath(),delta.getKind(),delta.getFlags());
        result.set(true);
      }
      if (resource.getType() == IResource.FILE) {
        if (Workspace.BUILDFILE.equals(resource.getName())) {
          result.set(true);
          log(LOG_FULL,"detected change in cnf due to resource %s, kind=0x%x, flags=0x%x",resource.getFullPath(),delta.getKind(),delta.getFlags());
        }
 else {
        }
      }
      return false;
    }
  }
);
  return result.get();
}
 

Example 24

From project bonecp, under directory /bonecp/src/test/java/com/jolbox/bonecp/.

Source file: TestConnectionHandle.java

  31 
vote

/** 
 * Test marking of possibly broken status.
 * @throws SecurityException
 * @throws NoSuchFieldException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
@Test public void testMarkPossiblyBroken() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
  Field field=this.testClass.getClass().getDeclaredField("possiblyBroken");
  field.setAccessible(true);
  field.set(this.testClass,false);
  this.testClass.markPossiblyBroken(new SQLException());
  Assert.assertTrue(field.getBoolean(this.testClass));
  expect(this.mockPool.getDbIsDown()).andReturn(new AtomicBoolean()).anyTimes();
  this.mockPool.connectionStrategy.terminateAllConnections();
  this.mockLogger.error((String)anyObject(),anyObject());
  replay(this.mockPool);
  this.testClass.markPossiblyBroken(new SQLException("test","08001"));
  verify(this.mockPool);
}
 

Example 25

From project Carolina-Digital-Repository, under directory /services/src/test/java/edu/unc/lib/dl/cdr/services/processing/.

Source file: DelayEnhancement.java

  31 
vote

public static void init(){
  inIsApplicable=new AtomicInteger(0);
  incompleteServices=new AtomicInteger(0);
  betweenApplicableAndEnhancement=new AtomicInteger(0);
  servicesCompleted=new AtomicInteger(0);
  inService=new AtomicInteger(0);
  blockingObject=new Object();
  flag=new AtomicBoolean(true);
}
 

Example 26

From project clojure, under directory /src/jvm/clojure/lang/.

Source file: Var.java

  31 
vote

Var(Namespace ns,Symbol sym){
  this.ns=ns;
  this.sym=sym;
  this.threadBound=new AtomicBoolean(false);
  this.root=new Unbound(this);
  setMeta(PersistentHashMap.EMPTY);
}
 

Example 27

From project cloudhopper-smpp, under directory /src/test/java/com/cloudhopper/smpp/demo/.

Source file: PerformanceClientMain.java

  31 
vote

public ClientSessionTask(CountDownLatch allSessionsBoundSignal,CountDownLatch startSendingSignal,DefaultSmppClient clientBootstrap,SmppSessionConfiguration config){
  this.allSessionsBoundSignal=allSessionsBoundSignal;
  this.startSendingSignal=startSendingSignal;
  this.clientBootstrap=clientBootstrap;
  this.config=config;
  this.submitRequestSent=0;
  this.submitResponseReceived=0;
  this.sendingDone=new AtomicBoolean(false);
}
 

Example 28

From project clustermeister, under directory /provisioning/src/test/java/com/github/nethad/clustermeister/provisioning/jppf/.

Source file: PublicIpIntegrationTest.java

  31 
vote

@Test public void testDriverBlockingUntilPublicIpAvailable() throws InterruptedException {
  final Lock lock=new ReentrantLock();
  final Condition condition=lock.newCondition();
  final AtomicBoolean isBlocking=new AtomicBoolean(false);
  final JPPFLocalDriver driver=new JPPFLocalDriver(null);
  new Thread(new Runnable(){
    @Override public void run(){
      lock.lock();
      try {
        isBlocking.set(true);
        condition.signal();
      }
  finally {
        lock.unlock();
      }
      driver.getIpAddress();
    }
  }
).start();
  lock.lock();
  try {
    while (!isBlocking.get()) {
      condition.await();
      Thread.sleep(100);
    }
  }
  finally {
    lock.unlock();
  }
  nodeDeployer.addListener(driver);
  assertThat(driver.getIpAddress(),is("1.2.3.5"));
}
 

Example 29

From project collector, under directory /src/main/java/com/ning/metrics/collector/realtime/amq/.

Source file: ActiveMQConnection.java

  31 
vote

public ActiveMQConnection(final CollectorConfig baseConfig){
  useBytesMessage=new AtomicBoolean(baseConfig.getActiveMQUseBytesMessage());
  String uri=baseConfig.getActiveMQUri();
  if (uri != null) {
    this.connectionFactory=new ActiveMQConnectionFactory(uri);
    this.connectionFactory.setUseAsyncSend(baseConfig.getActiveMQUseAsyncSend());
  }
}
 

Example 30

From project cometd, under directory /cometd-java/cometd-java-client/src/test/java/org/cometd/client/.

Source file: BayeuxClientConcurrentTest.java

  31 
vote

@Test public void testHandshakeListenersAreNotifiedBeforeConnectListeners() throws Exception {
  final BayeuxClient client=new BayeuxClient(cometdURL,LongPollingTransport.create(null,httpClient));
  client.setDebugEnabled(debugTests());
  final int sleep=1000;
  final AtomicBoolean handshaken=new AtomicBoolean();
  client.getChannel(Channel.META_HANDSHAKE).addListener(new ClientSessionChannel.MessageListener(){
    public void onMessage(    ClientSessionChannel channel,    Message message){
      try {
        Thread.sleep(sleep);
        handshaken.set(true);
      }
 catch (      InterruptedException x) {
      }
    }
  }
);
  final CountDownLatch connectLatch=new CountDownLatch(1);
  client.getChannel(Channel.META_CONNECT).addListener(new ClientSessionChannel.MessageListener(){
    public void onMessage(    ClientSessionChannel channel,    Message message){
      if (handshaken.get())       connectLatch.countDown();
    }
  }
);
  client.handshake();
  assertTrue(connectLatch.await(2 * sleep,TimeUnit.MILLISECONDS));
  disconnectBayeuxClient(client);
}
 

Example 31

From project CommunityCase, under directory /src/org/community/intellij/plugins/communitycase/update/.

Source file: UpdateLocallyModifiedDialog.java

  31 
vote

/** 
 * Show the dialog if needed
 * @param project the project
 * @param root    the vcs root
 * @return true if showing is not needed or operation completed successfully
 */
public static boolean showIfNeeded(final Project project,final VirtualFile root){
  final ArrayList<String> files=new ArrayList<String>();
  try {
    scanFiles(project,root,files);
    final AtomicBoolean rc=new AtomicBoolean(true);
    if (!files.isEmpty()) {
      com.intellij.util.ui.UIUtil.invokeAndWaitIfNeeded(new Runnable(){
        public void run(){
          UpdateLocallyModifiedDialog d=new UpdateLocallyModifiedDialog(project,root,files);
          d.show();
          rc.set(d.isOK());
        }
      }
);
      if (rc.get()) {
        if (!files.isEmpty()) {
          revertFiles(project,root,files);
        }
      }
    }
    return rc.get();
  }
 catch (  final VcsException e) {
    com.intellij.util.ui.UIUtil.invokeAndWaitIfNeeded(new Runnable(){
      public void run(){
        UiUtil.showOperationError(project,e,"Checking for locally modified files");
      }
    }
);
    return false;
  }
}
 

Example 32

From project components-ness-jackson, under directory /src/test/java/com/nesscomputing/jackson/.

Source file: TestNessObjectMapperProvider.java

  31 
vote

@Test public void testCustomUUID() throws Exception {
  final UUID orig=UUID.fromString("550e8400-e29b-41d4-a716-446655440000");
  final AtomicBoolean called=new AtomicBoolean(false);
  ObjectMapper mapper=getObjectMapper(null,new AbstractModule(){
    @Override protected void configure(){
      bind(new TypeLiteral<JsonDeserializer<UUID>>(){
      }
).toInstance(new CustomUuidDeserializer(){
        @Override protected UUID _deserialize(        String value,        DeserializationContext ctxt) throws IOException, JsonProcessingException {
          UUID foo=super._deserialize(value,ctxt);
          called.set(true);
          return foo;
        }
      }
);
    }
  }
);
  UUID uuid=mapper.readValue('"' + orig.toString() + '"',new TypeReference<UUID>(){
  }
);
  Assert.assertEquals(orig,uuid);
  Assert.assertTrue(called.get());
}
 

Example 33

From project components-ness-jdbi, under directory /src/main/java/com/nesscomputing/jdbi/template/.

Source file: TemplateGroupLoader.java

  31 
vote

public static StringTemplateGroup load(final String name,final URL resourceUrl){
  if (resourceUrl == null) {
    throw new TemplateLoaderException("Error loading StringTemplate: Resource %s does not exist!",name);
  }
  Reader reader;
  try {
    reader=new InputStreamReader(resourceUrl.openStream(),Charset.forName("UTF-8"));
  }
 catch (  IOException ex) {
    throw new TemplateLoaderException(ex,"Error loading StringTemplate: %s",name);
  }
  final AtomicBoolean error=new AtomicBoolean(false);
  final StringTemplateGroup result=new StringTemplateGroup(reader,AngleBracketTemplateLexer.class,new StringTemplateErrorListener(){
    @Override public void error(    final String msg,    final Throwable e){
      LOG.error(e,msg);
      error.set(true);
    }
    @Override public void warning(    final String msg){
      LOG.warn(msg);
    }
  }
);
  if (error.get()) {
    throw new TemplateLoaderException("Error loading StringTemplate: %s",name);
  }
  return result;
}
 

Example 34

From project components-ness-lifecycle, under directory /src/test/java/com/nesscomputing/lifecycle/guice/.

Source file: TestLifecycleAnnotations.java

  31 
vote

@Test public void testLifecycleAnnotationsOnSuperclass(){
  final AtomicBoolean isConfigured=new AtomicBoolean();
  Guice.createInjector(new AbstractModule(){
    @Override protected void configure(){
      binder().requireExplicitBindings();
      binder().disableCircularProxies();
      install(new LifecycleModule());
      bind(LifecycleTest.class).toInstance(new LifecycleTest(){
        @SuppressWarnings("unused") @OnStage(LifecycleStage.CONFIGURE) void configure(){
          Preconditions.checkState(isStarted == false && isStopped == false);
          isConfigured.set(true);
        }
      }
);
      requestInjection(TestLifecycleAnnotations.this);
    }
  }
);
  assertFalse(isConfigured.get());
  assertFalse(tester.isStarted);
  assertFalse(tester.isStopped);
  lifecycle.executeTo(LifecycleStage.START_STAGE);
  assertTrue(isConfigured.get());
  assertTrue(tester.isStarted);
  assertFalse(tester.isStopped);
  lifecycle.executeTo(LifecycleStage.STOP_STAGE);
  assertTrue(tester.isStarted);
  assertTrue(tester.isStopped);
}
 

Example 35

From project curator, under directory /curator-client/src/test/java/com/netflix/curator/.

Source file: BasicTests.java

  31 
vote

@Test public void testExpiredSession() throws Exception {
  final Timing timing=new Timing();
  final CountDownLatch latch=new CountDownLatch(1);
  Watcher watcher=new Watcher(){
    @Override public void process(    WatchedEvent event){
      if (event.getState() == Event.KeeperState.Expired) {
        latch.countDown();
      }
    }
  }
;
  final CuratorZookeeperClient client=new CuratorZookeeperClient(server.getConnectString(),timing.session(),timing.connection(),watcher,new RetryOneTime(2));
  client.start();
  try {
    final AtomicBoolean firstTime=new AtomicBoolean(true);
    RetryLoop.callWithRetry(client,new Callable<Object>(){
      @Override public Object call() throws Exception {
        if (firstTime.compareAndSet(true,false)) {
          try {
            client.getZooKeeper().create("/foo",new byte[0],ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
          }
 catch (          KeeperException.NodeExistsException ignore) {
          }
          KillSession.kill(client.getZooKeeper(),server.getConnectString());
          Assert.assertTrue(timing.awaitLatch(latch));
        }
        ZooKeeper zooKeeper=client.getZooKeeper();
        client.blockUntilConnectedOrTimedOut();
        Assert.assertNotNull(zooKeeper.exists("/foo",false));
        return null;
      }
    }
);
  }
  finally {
    client.close();
  }
}
 

Example 36

From project disruptor, under directory /src/test/java/com/lmax/disruptor/experimental/.

Source file: MultiThreadedClaimStrategyV2Test.java

  31 
vote

@Test public void shouldNotReturnNextClaimSequenceUntilBufferHasReserve() throws InterruptedException {
  final Sequence dependentSequence=new Sequence(Sequencer.INITIAL_CURSOR_VALUE);
  final Sequence[] dependentSequences={dependentSequence};
  claimStrategy.setSequence(claimStrategy.getBufferSize() - 1L,dependentSequences);
  final AtomicBoolean done=new AtomicBoolean(false);
  final CountDownLatch beforeLatch=new CountDownLatch(1);
  final CountDownLatch afterLatch=new CountDownLatch(1);
  final Runnable publisher=new Runnable(){
    @Override public void run(){
      beforeLatch.countDown();
      assertEquals(claimStrategy.getBufferSize(),claimStrategy.incrementAndGet(dependentSequences));
      done.set(true);
      afterLatch.countDown();
    }
  }
;
  new Thread(publisher).start();
  beforeLatch.await();
  Thread.sleep(1000L);
  assertFalse(done.get());
  dependentSequence.set(dependentSequence.get() + 1L);
  afterLatch.await();
  assertEquals(claimStrategy.getBufferSize(),claimStrategy.getSequence());
}
 

Example 37

From project disruptor_1, under directory /code/src/test/java/com/lmax/disruptor/.

Source file: RingBufferTest.java

  31 
vote

@Test public void shouldPreventProducersOvertakingConsumerWrapPoint() throws InterruptedException {
  final int ringBufferSize=4;
  final CountDownLatch latch=new CountDownLatch(ringBufferSize);
  final AtomicBoolean producerComplete=new AtomicBoolean(false);
  final RingBuffer<StubEntry> ringBuffer=new RingBuffer<StubEntry>(StubEntry.ENTRY_FACTORY,ringBufferSize);
  final TestConsumer consumer=new TestConsumer(ringBuffer.createConsumerBarrier());
  final ProducerBarrier<StubEntry> producerBarrier=ringBuffer.createProducerBarrier(consumer);
  Thread thread=new Thread(new Runnable(){
    @Override public void run(){
      for (int i=0; i <= ringBufferSize; i++) {
        StubEntry entry=producerBarrier.nextEntry();
        entry.setValue(i);
        producerBarrier.commit(entry);
        latch.countDown();
      }
      producerComplete.set(true);
    }
  }
);
  thread.start();
  latch.await();
  assertThat(Long.valueOf(ringBuffer.getCursor()),is(Long.valueOf(ringBufferSize - 1)));
  assertFalse(producerComplete.get());
  consumer.run();
  thread.join();
  assertTrue(producerComplete.get());
}
 

Example 38

From project dragon, under directory /hadoop-dragon-core/src/main/java/org/apache/hadoop/realtime/app/rm/.

Source file: RMCommunicator.java

  31 
vote

public RMCommunicator(AppContext context){
  super("RMCommunicator");
  this.context=context;
  this.eventHandler=context.getEventHandler();
  this.applicationId=context.getApplicationID();
  this.applicationAttemptId=context.getApplicationAttemptId();
  this.stopped=new AtomicBoolean(false);
}
 

Example 39

From project droid-comic-viewer, under directory /src/net/robotmedia/acv/comic/.

Source file: ACVComic.java

  31 
vote

private Bitmap getBitmap(ACVContent content,final WebView w,int containerWidth,int containerHeight){
  final Rect rect=content.createRect(containerWidth,containerHeight);
  final CountDownLatch signal=new CountDownLatch(1);
  final Bitmap b=Bitmap.createBitmap(rect.width(),rect.height(),Bitmap.Config.RGB_565);
  final AtomicBoolean ready=new AtomicBoolean(false);
  final String html=this.getContentFromSource(content);
  final String baseURL=this.getContentBaseURL();
  w.post(new Runnable(){
    @Override public void run(){
      w.setWebViewClient(new WebViewClient(){
        @Override public void onPageFinished(        WebView view,        String url){
          ready.set(true);
        }
      }
);
      w.setPictureListener(new PictureListener(){
        @Override public void onNewPicture(        WebView view,        Picture picture){
          if (ready.get()) {
            final Canvas c=new Canvas(b);
            view.draw(c);
            w.setPictureListener(null);
            signal.countDown();
          }
        }
      }
);
      w.layout(0,0,rect.width(),rect.height());
      w.loadDataWithBaseURL(baseURL,html,"text/html","UTF-8",null);
    }
  }
);
  try {
    signal.await();
  }
 catch (  InterruptedException e) {
    e.printStackTrace();
  }
  return b;
}
 

Example 40

From project ElectricSleep, under directory /src/com/androsz/electricsleepbeta/app/.

Source file: SleepActivity.java

  31 
vote

@Override protected void onCreate(final Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  mServiceBound=new AtomicBoolean();
  setTitle(R.string.monitoring_sleep);
  airplaneModeOn=Settings.System.getInt(getContentResolver(),Settings.System.AIRPLANE_MODE_ON,0) != 0;
  registerReceiver(sleepStoppedReceiver,new IntentFilter(SleepMonitoringService.SLEEP_STOPPED));
  sleepChart=(SleepChart)findViewById(R.id.sleep_movement_chart);
  sleepChart.setVisibility(View.VISIBLE);
  startService(new Intent(this,SleepMonitoringService.class));
}
 

Example 41

From project enterprise, under directory /ha/src/test/java/org/neo4j/kernel/ha/zookeeper/.

Source file: TestZooClient.java

  31 
vote

@Test public void testWaitsForZKQuorumToComeUp() throws Exception {
  final long millisForSessionToExpire=1000;
  Map<String,String> stringConfig=new HashMap<String,String>();
  stringConfig.put(HaSettings.coordinators.name(),"127.0.0.1:3181");
  stringConfig.put(HaSettings.server_id.name(),"1");
  stringConfig.put(HaSettings.zk_session_timeout.name(),Long.toString(millisForSessionToExpire));
  Config config=new Config(new ConfigurationDefaults(OnlineBackupSettings.class,GraphDatabaseSettings.class,HaSettings.class).apply(stringConfig));
  ZooClient client=new ZooClient("",StringLogger.SYSTEM,config,null,DummyClusterReceiver,new MasterClientResolver.F18(StringLogger.SYSTEM,Client.DEFAULT_READ_RESPONSE_TIMEOUT_SECONDS,Client.DEFAULT_READ_RESPONSE_TIMEOUT_SECONDS,Client.DEFAULT_MAX_NUMBER_OF_CONCURRENT_CHANNELS_PER_CLIENT,DEFAULT_FRAME_LENGTH));
  final AtomicBoolean stop=new AtomicBoolean(false);
  Thread launchesZK=new Thread(new Runnable(){
    @Override public void run(){
      LocalhostZooKeeperCluster cluster=null;
      try {
        Thread.sleep((millisForSessionToExpire) * 2);
        cluster=new LocalhostZooKeeperCluster(getClass(),3181);
        while (!stop.get()) {
          Thread.sleep(150);
        }
      }
 catch (      Throwable e) {
        e.printStackTrace();
      }
 finally {
        if (cluster != null) {
          cluster.shutdown();
        }
      }
    }
  }
);
  launchesZK.setDaemon(true);
  launchesZK.start();
  client.waitForSyncConnected(AbstractZooKeeperManager.WaitMode.STARTUP);
  client.shutdown();
  stop.set(true);
  launchesZK.join();
}
 

Example 42

From project eucalyptus, under directory /clc/modules/cluster-manager/src/edu/ucsb/eucalyptus/cloud/cluster/.

Source file: ClusterAllocator.java

  31 
vote

public ClusterAllocator(ResourceToken vmToken,VmAllocationInfo vmAllocInfo){
  this.msgMap=Multimaps.newHashMultimap();
  this.vmAllocInfo=vmAllocInfo;
  this.pendingEvents=new ConcurrentLinkedQueue<QueuedEvent>();
  this.cluster=Clusters.getInstance().lookup(vmToken.getCluster());
  this.state=State.START;
  this.rollback=new AtomicBoolean(false);
  for (  NetworkToken networkToken : vmToken.getNetworkTokens())   this.setupNetworkMessages(networkToken);
  this.setupVmMessages(vmToken);
}
 

Example 43

From project flume, under directory /flume-ng-channels/flume-file-channel/src/test/java/org/apache/flume/channel/file/encryption/.

Source file: TestFileChannelEncryption.java

  31 
vote

/** 
 * Test fails without FLUME-1565
 */
@Test public void testThreadedConsume() throws Exception {
  int numThreads=20;
  Map<String,String> overrides=getOverridesForEncryption();
  overrides.put(FileChannelConfiguration.CAPACITY,String.valueOf(10000));
  channel=createFileChannel(overrides);
  channel.start();
  Assert.assertTrue(channel.isOpen());
  Executor executor=Executors.newFixedThreadPool(numThreads);
  Set<String> in=fillChannel(channel,"threaded-consume");
  final AtomicBoolean error=new AtomicBoolean(false);
  final CountDownLatch startLatch=new CountDownLatch(numThreads);
  final CountDownLatch stopLatch=new CountDownLatch(numThreads);
  final Set<String> out=Collections.synchronizedSet(new HashSet<String>());
  for (int i=0; i < numThreads; i++) {
    executor.execute(new Runnable(){
      @Override public void run(){
        try {
          startLatch.countDown();
          startLatch.await();
          out.addAll(takeEvents(channel,10));
        }
 catch (        Throwable t) {
          error.set(true);
          LOGGER.error("Error in take thread",t);
        }
 finally {
          stopLatch.countDown();
        }
      }
    }
);
  }
  stopLatch.await();
  Assert.assertFalse(error.get());
  compareInputAndOut(in,out);
}
 

Example 44

From project Flume-Hive, under directory /src/javatest/com/cloudera/flume/agent/diskfailover/.

Source file: TestDiskFailoverSource.java

  31 
vote

/** 
 * WAL should succeed on open even if its internal opens fail. It will block on next() while continuing to try get a valid source of events. This test demonstrates this by starting the WALSource, calling next in a separate thread, and waits a little. Nothing should have happened.
 */
@Test public void testSurviveErrorOnOpen() throws IOException, InterruptedException {
  LOG.info("Survive error on open with WALSource");
  File basedir=FileUtil.mktempdir();
  basedir.deleteOnExit();
  File logDir=new File(basedir,NaiveFileWALManager.LOGGEDDIR);
  logDir.mkdirs();
  File corrupt=new File(logDir,"walempty.00000000.20091104-101213997-0800.seq");
  LOG.info("corrupt file is named: " + corrupt.getAbsolutePath());
  corrupt.createNewFile();
  corrupt.deleteOnExit();
  DiskFailoverManager dfman=new NaiveFileFailoverManager(basedir);
  final DiskFailoverSource src=new DiskFailoverSource(dfman);
  src.open();
  src.recover();
  final AtomicBoolean okstate=new AtomicBoolean(true);
  Thread t=new Thread(){
    public void run(){
      try {
        src.next();
      }
 catch (      IOException e) {
        e.printStackTrace();
      }
 finally {
        okstate.set(false);
      }
    }
  }
;
  t.start();
  Clock.sleep(3000);
  src.close();
  assertTrue(okstate.get());
  FileUtil.rmr(basedir);
}
 

Example 45

From project flume_1, under directory /flume-core/src/test/java/com/cloudera/flume/agent/diskfailover/.

Source file: TestDiskFailoverSource.java

  31 
vote

/** 
 * WAL should succeed on open even if its internal opens fail. It will block on next() while continuing to try get a valid source of events. This test demonstrates this by starting the WALSource, calling next in a separate thread, and waits a little. Nothing should have happened.
 */
@Test public void testSurviveErrorOnOpen() throws IOException, InterruptedException {
  LOG.info("Survive error on open with WALSource");
  File basedir=FileUtil.mktempdir();
  basedir.deleteOnExit();
  File logDir=new File(basedir,NaiveFileWALManager.LOGGEDDIR);
  logDir.mkdirs();
  File corrupt=new File(logDir,"walempty.00000000.20091104-101213997-0800.seq");
  LOG.info("corrupt file is named: " + corrupt.getAbsolutePath());
  corrupt.createNewFile();
  corrupt.deleteOnExit();
  DiskFailoverManager dfman=new NaiveFileFailoverManager(basedir);
  final DiskFailoverSource src=new DiskFailoverSource(dfman);
  src.open();
  src.recover();
  final AtomicBoolean okstate=new AtomicBoolean(true);
  Thread t=new Thread(){
    public void run(){
      try {
        src.next();
      }
 catch (      Exception e) {
        e.printStackTrace();
      }
 finally {
        okstate.set(false);
      }
    }
  }
;
  t.start();
  Clock.sleep(3000);
  src.close();
  assertTrue(okstate.get());
  FileUtil.rmr(basedir);
}
 

Example 46

From project gatein-common, under directory /logging/src/test/java/org/gatein/common/logging/.

Source file: LogTestCase.java

  31 
vote

public void testConcurrentGetRace() throws Exception {
  final ReentrantLock lock=LoggerFactoryImpl.getLock();
  lock.lock();
  final AtomicReference<Logger> loggerRef=new AtomicReference<Logger>();
  final AtomicBoolean done=new AtomicBoolean();
  Thread t=new Thread(){
    public void run(){
      Logger logger=LoggerFactory.getLogger("testConcurrentGetRace");
      loggerRef.set(logger);
      done.set(true);
    }
  }
;
  t.start();
  while (!lock.hasQueuedThread(t)) {
    Thread.sleep(1);
  }
  assertEquals(null,LoggerFactoryImpl.peekLogger("testConcurrentGetRace"));
  Logger logger=LoggerFactory.getLogger("testConcurrentGetRace");
  assertNotNull(logger);
  lock.unlock();
  while (!done.get()) {
    Thread.sleep(1);
  }
  assertSame(logger,loggerRef.get());
}
 

Example 47

From project gecko, under directory /src/test/java/com/taobao/gecko/core/intergration/tcp/.

Source file: SessionTimeoutUnitTest.java

  31 
vote

@Test(timeout=60 * 1000) public void testSessionTimeout() throws Exception {
  TCPConnectorController connector=new TCPConnectorController();
  final AtomicBoolean closed=new AtomicBoolean(false);
  connector.setHandler(new HandlerAdapter(){
    @Override public void onSessionClosed(    Session session){
      System.out.println("Client End,session is closed");
      closed.set(true);
    }
  }
);
  connector.connect(new InetSocketAddress("localhost",1997));
  connector.awaitConnectUnInterrupt();
synchronized (this) {
    while (!this.expired.get() || !closed.get()) {
      this.wait(1000);
    }
  }
}
 

Example 48

From project Gemini-Blueprint, under directory /core/src/main/java/org/eclipse/gemini/blueprint/service/exporter/support/internal/support/.

Source file: LazyTargetResolver.java

  31 
vote

public LazyTargetResolver(Object target,BeanFactory beanFactory,String beanName,boolean cacheService,ListenerNotifier notifier,boolean lazyListeners){
  this.target=target;
  this.beanFactory=beanFactory;
  this.beanName=beanName;
  this.cacheService=cacheService;
  this.notifier=notifier;
  this.activated=new AtomicBoolean(!lazyListeners);
}
 

Example 49

From project GenericKnimeNodes, under directory /com.genericworkflownodes.knime.base_plugin/src/com/genericworkflownodes/knime/execution/.

Source file: AsynchronousToolExecutor.java

  31 
vote

/** 
 * C'tor.
 * @param executor The executor which should be handled asynchronously.
 */
public AsynchronousToolExecutor(final IToolExecutor executor){
  this.executor=executor;
  countdownLatch=new CountDownLatch(1);
  invokeAlreadyCalled=new AtomicBoolean(false);
  futureTask=new FutureTask<Integer>(new Callable<Integer>(){
    @Override public Integer call() throws Exception {
      return doCall();
    }
  }
);
}
 

Example 50

From project google-gson, under directory /src/test/java/com/google/gson/functional/.

Source file: ConcurrencyTest.java

  31 
vote

/** 
 * Source-code based on http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081
 */
public void testMultiThreadSerialization() throws InterruptedException {
  final CountDownLatch startLatch=new CountDownLatch(1);
  final CountDownLatch finishedLatch=new CountDownLatch(10);
  final AtomicBoolean failed=new AtomicBoolean(false);
  ExecutorService executor=Executors.newFixedThreadPool(10);
  for (int taskCount=0; taskCount < 10; taskCount++) {
    executor.execute(new Runnable(){
      public void run(){
        MyObject myObj=new MyObject();
        try {
          startLatch.await();
          for (int i=0; i < 10; i++) {
            gson.toJson(myObj);
          }
        }
 catch (        Throwable t) {
          failed.set(true);
        }
 finally {
          finishedLatch.countDown();
        }
      }
    }
);
  }
  startLatch.countDown();
  finishedLatch.await();
  assertFalse(failed.get());
}
 

Example 51

From project gson, under directory /gson/src/test/java/com/google/gson/functional/.

Source file: ConcurrencyTest.java

  31 
vote

/** 
 * Source-code based on http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081
 */
public void testMultiThreadSerialization() throws InterruptedException {
  final CountDownLatch startLatch=new CountDownLatch(1);
  final CountDownLatch finishedLatch=new CountDownLatch(10);
  final AtomicBoolean failed=new AtomicBoolean(false);
  ExecutorService executor=Executors.newFixedThreadPool(10);
  for (int taskCount=0; taskCount < 10; taskCount++) {
    executor.execute(new Runnable(){
      public void run(){
        MyObject myObj=new MyObject();
        try {
          startLatch.await();
          for (int i=0; i < 10; i++) {
            gson.toJson(myObj);
          }
        }
 catch (        Throwable t) {
          failed.set(true);
        }
 finally {
          finishedLatch.countDown();
        }
      }
    }
);
  }
  startLatch.countDown();
  finishedLatch.await();
  assertFalse(failed.get());
}
 

Example 52

From project hank, under directory /test/java/com/rapleaf/hank/.

Source file: ZkTestCase.java

  31 
vote

@Override protected void setUp() throws Exception {
  super.setUp();
  Logger.getLogger("org.apache.zookeeper").setLevel(Level.WARN);
  setupZkServer();
  final Object lock=new Object();
  final AtomicBoolean connected=new AtomicBoolean(false);
  zk=new ZooKeeperPlus("127.0.0.1:" + zkClientPort,1000000,new Watcher(){
    @Override public void process(    WatchedEvent event){
switch (event.getType()) {
case None:
        if (event.getState() == KeeperState.SyncConnected) {
          connected.set(true);
synchronized (lock) {
            lock.notifyAll();
          }
        }
    }
    LOG.debug(event.toString());
  }
}
);
synchronized (lock) {
  lock.wait(2000);
}
if (!connected.get()) {
  fail("timed out waiting for the zk client connection to come online!");
}
LOG.debug("session timeout: " + zk.getSessionTimeout());
zk.deleteNodeRecursively(zkRoot);
createNodeRecursively(zkRoot);
}
 

Example 53

From project hoop, under directory /hoop-server/src/test/java/com/cloudera/lib/servlet/.

Source file: TestHostnameFilter.java

  31 
vote

@Test public void hostname() throws Exception {
  ServletRequest request=Mockito.mock(ServletRequest.class);
  Mockito.when(request.getRemoteAddr()).thenReturn("localhost");
  ServletResponse response=Mockito.mock(ServletResponse.class);
  final AtomicBoolean invoked=new AtomicBoolean();
  FilterChain chain=new FilterChain(){
    @Override public void doFilter(    ServletRequest servletRequest,    ServletResponse servletResponse) throws IOException, ServletException {
      Assert.assertEquals(HostnameFilter.get(),"localhost");
      invoked.set(true);
    }
  }
;
  Filter filter=new HostnameFilter();
  filter.init(null);
  Assert.assertNull(HostnameFilter.get());
  filter.doFilter(request,response,chain);
  Assert.assertTrue(invoked.get());
  Assert.assertNull(HostnameFilter.get());
  filter.destroy();
}
 

Example 54

From project hotpotato, under directory /src/main/java/com/biasedbit/hotpotato/request/.

Source file: ConcurrentHttpRequestFuture.java

  31 
vote

public ConcurrentHttpRequestFuture(boolean cancellable){
  this.cancellable=cancellable;
  this.creation=System.nanoTime();
  this.executionStart=-1;
  this.done=new AtomicBoolean(false);
  this.listeners=new ArrayList<HttpRequestFutureListener<T>>(2);
  this.waitLatch=new CountDownLatch(1);
}
 

Example 55

From project hs4j, under directory /src/test/java/com/google/code/hs4j/impl/.

Source file: HSClientImplUnitTest.java

  31 
vote

@Test public void testStateListener() throws Exception {
  final AtomicBoolean started=new AtomicBoolean();
  final AtomicBoolean stopped=new AtomicBoolean();
  final AtomicInteger connectedCount=new AtomicInteger(0);
  HSClientStateListener listener=new HSClientStateListener(){
    public void onStarted(    HSClient client){
      started.set(true);
    }
    public void onShutDown(    HSClient client){
      stopped.set(true);
    }
    public void onException(    HSClient client,    Throwable throwable){
    }
    public void onDisconnected(    HSClient client,    InetSocketAddress inetSocketAddress){
    }
    public void onConnected(    HSClient client,    InetSocketAddress inetSocketAddress){
      connectedCount.incrementAndGet();
    }
  }
;
  this.hsClient.shutdown();
  assertFalse(started.get());
  assertFalse(stopped.get());
  assertEquals(0,connectedCount.get());
  HSClientBuilder builder=new HSClientBuilderImpl();
  builder.setServerAddress(this.hostName,9999);
  builder.addStateListeners(listener);
  builder.setConnectionPoolSize(10);
  this.hsClient=builder.build();
  assertTrue(started.get());
  assertFalse(stopped.get());
  assertEquals(10,connectedCount.get());
  this.hsClient.shutdown();
  assertTrue(stopped.get());
}
 

Example 56

From project httptunnel, under directory /src/main/java/com/yammer/httptunnel/server/.

Source file: HttpTunnelServerChannel.java

  31 
vote

protected HttpTunnelServerChannel(ChannelFactory factory,ChannelPipeline pipeline,ChannelSink sink,ServerSocketChannelFactory inboundFactory,ChannelGroup realConnections){
  super(factory,pipeline,sink);
  tunnelIdPrefix=Long.toHexString(random.nextLong());
  tunnels=new ConcurrentHashMap<String,HttpTunnelAcceptedChannel>();
  config=new HttpTunnelServerChannelConfig();
  realChannel=inboundFactory.newChannel(this.createRealPipeline(realConnections));
  config.setRealChannel(realChannel);
  opened=new AtomicBoolean(true);
  bindState=new AtomicReference<BindState>(BindState.UNBOUND);
  realConnections.add(realChannel);
  Channels.fireChannelOpen(this);
}
 

Example 57

From project ib-ruby, under directory /misc/IBController 2-9-0/src/ibcontroller/.

Source file: LoginFrameHandler.java

  31 
vote

private boolean setFieldsAndClick(final Window window){
  if (!Utils.setTextField(window,0,TwsListener.getUserName()))   return false;
  if (!Utils.setTextField(window,1,TwsListener.getPassword()))   return false;
  if (!Utils.setCheckBoxSelected(window,"Use/store settings on server",Settings.getBoolean("StoreSettingsOnServer",false)))   return false;
  if (TwsListener.getUserName().length() == 0) {
    Utils.findTextField(window,0).requestFocus();
    return true;
  }
  if (TwsListener.getPassword().length() == 0) {
    Utils.findTextField(window,1).requestFocus();
    return true;
  }
  if (Utils.findButton(window,"Login") == null)   return false;
  final Timer timer=new Timer(true);
  timer.schedule(new TimerTask(){
    public void run(){
      final AtomicBoolean done=new AtomicBoolean(false);
      do {
        GuiSynchronousExecutor.instance().execute(new Runnable(){
          public void run(){
            Utils.clickButton(window,"Login");
            done.set(!Utils.isButtonEnabled(window,"Login"));
          }
        }
);
        Utils.pause(500);
      }
 while (!done.get());
    }
  }
,10);
  return true;
}
 

Example 58

From project iPage, under directory /src/main/java/com/github/zhongl/api/.

Source file: Ephemerons.java

  31 
vote

protected Ephemerons(){
  id=new AtomicLong(0L);
  map=new ConcurrentHashMap<Key,Record>();
  flowControl=new Semaphore(0,true);
  flushing=new AtomicBoolean(false);
  asyncRemovingService=Executors.newCachedThreadPool(new ThreadFactory(){
    @Override public Thread newThread(    Runnable r){
      Thread thread=new Thread(r,"async-removing");
      thread.setDaemon(true);
      return thread;
    }
  }
);
}
 

Example 59

From project jagger, under directory /chassis/core/src/main/java/com/griddynamics/jagger/master/configuration/.

Source file: UserTaskGenerator.java

  31 
vote

public List<Task> generate(){
  List<Task> result=new LinkedList<Task>();
  int number=0;
  HashSet<String> names=new HashSet<String>();
  for (  ProcessingConfig.Test testConfig : config.tests) {
    ++number;
    CompositeTask compositeTask=new CompositeTask();
    compositeTask.setLeading(new ArrayList<CompositableTask>(testConfig.tasks.size()));
    for (    ProcessingConfig.Test.Task taskConfig : testConfig.tasks) {
      String name=String.format("%s [%s]",testConfig.name,taskConfig.name);
      if (!names.contains(name)) {
        names.add(name);
        AtomicBoolean shutdown=new AtomicBoolean(false);
        WorkloadTask prototype=applicationContext.getBean(taskConfig.bean,WorkloadTask.class);
        WorkloadTask workloadTask=prototype.copy();
        workloadTask.setNumber(number);
        workloadTask.setName(name);
        workloadTask.setTerminateStrategyConfiguration(new UserTerminateStrategyConfiguration(testConfig,taskConfig,shutdown));
        workloadTask.setClockConfiguration(new UserClockConfiguration(1000,taskConfig,shutdown));
        compositeTask.getLeading().add(workloadTask);
      }
 else {
        throw new IllegalArgumentException(String.format("Task with name '%s' already exists",name));
      }
    }
    if (monitoringEnable) {
      MonitoringTask attendantMonitoring=new MonitoringTask(number,testConfig.name + " --- monitoring",compositeTask.getTaskName(),new InfiniteDuration());
      compositeTask.setAttendant(ImmutableList.<CompositableTask>of(attendantMonitoring));
    }
    result.add(compositeTask);
  }
  return result;
}
 

Example 60

From project janus-plugin, under directory /janus-plugin/src/main/java/de/codecentric/janus/plugin/bootstrap/.

Source file: BootstrapExecutor.java

  31 
vote

BootstrapExecutor(ParsedFormData data){
  this.data=data;
  this.logger=new BootstrapLogger(data.toString());
  atomicBoolean=new AtomicBoolean();
  steps=new AbstractBootstrapStep[]{new RepositoryCreationStep(data,logger),new RepositoryCheckoutStep(data,logger),new SourceCodeGenerationStep(data,logger),new RepositoryCommitStep(data,logger),new JenkinsJobCreationStep(data,logger),new JiraConfigurationStep(data,logger)};
}
 

Example 61

From project Japid, under directory /tests/cn/bran/play/.

Source file: RenderResultCacheTest.java

  31 
vote

@Test public void testIgnoreCacheSetting() throws ShouldRefreshException {
  assertFalse(RenderResultCache.shouldIgnoreCache());
  RenderResultCache.setIgnoreCache(true);
  assertTrue(RenderResultCache.shouldIgnoreCache());
  final AtomicBoolean b=new AtomicBoolean(false);
  Thread t=new Thread(new Runnable(){
    @Override public void run(){
      b.set(!RenderResultCache.shouldIgnoreCache());
    }
  }
);
  t.start();
  waitfor(120);
  assertTrue(b.get());
  RenderResultCache.setIgnoreCache(false);
}
 

Example 62

From project AndroidLab, under directory /libs/unboundid/docs/examples/.

Source file: AuthRateThread.java

  30 
vote

/** 
 * Creates a new auth rate thread with the provided information.
 * @param threadNumber      The thread number for this thread.
 * @param searchConnection  The connection to use for the searches.
 * @param bindConnection    The connection to use for the  binds.
 * @param baseDN            The value pattern to use for the base DNs.
 * @param scope             The scope to use for the searches.
 * @param filter            The value pattern for the filters.
 * @param attributes        The set of attributes to return.
 * @param userPassword      The password to use for the bind operations.
 * @param authType          The type of authentication to perform.
 * @param startBarrier      A barrier used to coordinate starting between allof the threads.
 * @param authCounter       A value that will be used to keep track of thetotal number of authentications performed.
 * @param authDurations     A value that will be used to keep track of thetotal duration for all authentications.
 * @param errorCounter      A value that will be used to keep track of thenumber of errors encountered while searching.
 * @param rcCounter         The result code counter to use for keeping trackof the result codes for failed operations.
 * @param rateBarrier       The barrier to use for controlling the rate ofauthorizations.   {@code null} if no rate-limitingshould be used.
 */
AuthRateThread(final int threadNumber,final LDAPConnection searchConnection,final LDAPConnection bindConnection,final ValuePattern baseDN,final SearchScope scope,final ValuePattern filter,final String[] attributes,final String userPassword,final String authType,final CyclicBarrier startBarrier,final AtomicLong authCounter,final AtomicLong authDurations,final AtomicLong errorCounter,final ResultCodeCounter rcCounter,final FixedRateBarrier rateBarrier){
  setName("AuthRate Thread " + threadNumber);
  setDaemon(true);
  this.searchConnection=searchConnection;
  this.bindConnection=bindConnection;
  this.baseDN=baseDN;
  this.filter=filter;
  this.userPassword=userPassword;
  this.authCounter=authCounter;
  this.authDurations=authDurations;
  this.errorCounter=errorCounter;
  this.rcCounter=rcCounter;
  this.startBarrier=startBarrier;
  fixedRateBarrier=rateBarrier;
  searchConnection.setConnectionName("search-" + threadNumber);
  bindConnection.setConnectionName("bind-" + threadNumber);
  if (authType.equalsIgnoreCase("cram-md5")) {
    this.authType=AUTH_TYPE_CRAM_MD5;
  }
 else   if (authType.equalsIgnoreCase("digest-md5")) {
    this.authType=AUTH_TYPE_DIGEST_MD5;
  }
 else   if (authType.equalsIgnoreCase("plain")) {
    this.authType=AUTH_TYPE_PLAIN;
  }
 else {
    this.authType=AUTH_TYPE_SIMPLE;
  }
  resultCode=new AtomicReference<ResultCode>(null);
  authThread=new AtomicReference<Thread>(null);
  stopRequested=new AtomicBoolean(false);
  searchRequest=new SearchRequest("",scope,Filter.createPresenceFilter("objectClass"),attributes);
}
 

Example 63

From project cloudhopper-commons-util, under directory /src/main/java/com/cloudhopper/commons/util/windowing/.

Source file: DefaultWindowFuture.java

  30 
vote

/** 
 * Creates a new DefaultWindowFuture.
 * @param window The window that created this future.  Saved as a weakreference to prevent circular references.
 * @param windowLock The shared lock from the window
 * @param completedCondition The shared condition to wait on
 * @param key The key of the future
 * @param request The request of the future
 * @param callerStateHint The initial state of the caller hint
 * @param originalOfferTimeoutMillis
 * @param windowSize Size of the window after this request was added. Usefulfor calculating an estimated response time for this request rather than all requests ahead of it in the window.
 * @param offerTimestamp The timestamp when the request was offered
 * @param acceptTimestamp The timestamp when the request was accepted
 * @param expireTimestamp The timestamp when the request will expire or -1if no expiration is set
 */
protected DefaultWindowFuture(Window window,ReentrantLock windowLock,Condition completedCondition,K key,R request,int callerStateHint,long originalOfferTimeoutMillis,int windowSize,long offerTimestamp,long acceptTimestamp,long expireTimestamp){
  this.window=new WeakReference<Window>(window);
  this.windowLock=windowLock;
  this.completedCondition=completedCondition;
  this.key=key;
  this.request=request;
  this.response=new AtomicReference<P>();
  this.cause=new AtomicReference<Throwable>();
  this.callerStateHint=new AtomicInteger(callerStateHint);
  this.done=new AtomicBoolean(false);
  this.originalOfferTimeoutMillis=originalOfferTimeoutMillis;
  this.windowSize=windowSize;
  this.offerTimestamp=offerTimestamp;
  this.acceptTimestamp=acceptTimestamp;
  this.expireTimestamp=expireTimestamp;
  this.doneTimestamp=new AtomicLong(0);
}
 

Example 64

From project commons-j, under directory /src/main/java/nerds/antelax/commons/net/pubsub/.

Source file: RoundRobinReconnectHandler.java

  30 
vote

RoundRobinReconnectHandler(final ClientBootstrap bootstrap,final int retryDelay,final TimeUnit retryUnits,final PubSubClient.NetworkConnectionLifecycleCallback callback,final Collection<InetSocketAddress> servers){
  Preconditions.checkNotNull(bootstrap);
  Preconditions.checkNotNull(servers);
  Preconditions.checkArgument(!servers.isEmpty());
  Preconditions.checkArgument(retryDelay > 0);
  Preconditions.checkNotNull(retryUnits);
  this.bootstrap=bootstrap;
  this.callback=callback;
  this.retryDelay=retryDelay;
  this.retryUnits=retryUnits;
  availableServers=new ArrayList<InetSocketAddress>(servers.size());
  failedServers=new LinkedList<InetSocketAddress>();
  for (  final InetSocketAddress isa : servers)   if (isa != null)   availableServers.add(isa);
  Preconditions.checkArgument(!availableServers.isEmpty(),"Server list was empty or had null values");
  enabled=new AtomicBoolean(false);
  lock=new ReentrantLock();
  timer=new HashedWheelTimer();
  currentChannel=new AtomicReference<Channel>(null);
  currentRemoteAddress=new AtomicReference<InetSocketAddress>(null);
}
 

Example 65

From project hbase-rdf_1, under directory /src/main/java/com/talis/hbase/rdf/layout/.

Source file: LoaderTuplesNodes.java

  30 
vote

private void init(){
  if (initialized)   return;
  tupleLoaders=new HashMap<TableDesc[],TupleLoader>();
  currentLoader=null;
  count=0;
  if (threading) {
    queue=new ArrayBlockingQueue<TupleChange>(chunkSize);
    threadException=new AtomicReference<Throwable>();
    threadFlushing=new AtomicBoolean();
    commitThread=new Thread(new Commiter());
    commitThread.setDaemon(true);
    commitThread.start();
    LOG.debug("Threading started");
  }
  initialized=true;
}
 

Example 66

From project incubator-s4, under directory /subprojects/s4-comm/src/main/java/org/apache/s4/comm/topology/.

Source file: AssignmentFromZK.java

  30 
vote

@Inject public AssignmentFromZK(@Named("s4.cluster.name") String clusterName,@Named("s4.cluster.zk_address") String zookeeperAddress,@Named("s4.cluster.zk_session_timeout") int sessionTimeout,@Named("s4.cluster.zk_connection_timeout") int connectionTimeout) throws Exception {
  this.clusterName=clusterName;
  this.connectionTimeout=connectionTimeout;
  taskPath="/s4/clusters/" + clusterName + "/tasks";
  processPath="/s4/clusters/" + clusterName + "/process";
  lock=new ReentrantLock();
  clusterNodeRef=new AtomicReference<ClusterNode>();
  taskAcquired=lock.newCondition();
  currentlyOwningTask=new AtomicBoolean(false);
  try {
    machineId=InetAddress.getLocalHost().getCanonicalHostName();
  }
 catch (  UnknownHostException e) {
    logger.warn("Unable to get hostname",e);
    machineId="UNKNOWN";
  }
  zkClient=new ZkClient(zookeeperAddress,sessionTimeout,connectionTimeout);
  ZkSerializer serializer=new ZNRecordSerializer();
  zkClient.setZkSerializer(serializer);
}
 

Example 67

From project IronCount, under directory /src/main/java/com/jointhegrid/ironcount/manager/.

Source file: WorkloadManager.java

  30 
vote

public WorkloadManager(Properties p){
  this.active=new AtomicBoolean(false);
  props=p;
  myId=UUID.randomUUID();
  workerThreads=new HashMap<WorkerThread,Object>();
  if (p.contains(IC_THREAD_POOL_SIZE)) {
    this.threadPoolSize=Integer.parseInt(IC_THREAD_POOL_SIZE);
  }
  MBeanServer mbs=ManagementFactory.getPlatformMBeanServer();
  try {
    mbs.registerMBean(this,new ObjectName(MBEAN_OBJECT_NAME + ",uuid=" + myId));
  }
 catch (  Exception ex) {
    throw new RuntimeException(ex);
  }
}
 

Example 68

From project ardverk-commons, under directory /src/main/java/org/ardverk/lang/.

Source file: NumberUtils.java

  29 
vote

/** 
 * Returns the  {@code boolean} value of the given {@link Object}.
 */
private static boolean getBoolean(Object value,boolean defaultValue,boolean hasDefault){
  if (value instanceof Boolean) {
    return ((Boolean)value).booleanValue();
  }
 else   if (value instanceof AtomicBoolean) {
    return ((AtomicBoolean)value).get();
  }
  if (hasDefault) {
    return defaultValue;
  }
  throw new IllegalArgumentException("value=" + value);
}
 

Example 69

From project community-plugins, under directory /deployit-udm-plugins/utility-plugins/change-mgmt-plugin/src/test/java/ext/deployit/community/plugin/changemgmt/.

Source file: OverrideTestSynthetics.java

  29 
vote

@SuppressWarnings("unchecked") private static void forcePluginReboot() throws IllegalArgumentException {
  try {
    Field isBooted=getAccessibleField(PluginBooter.class,"isBooted");
    ((AtomicBoolean)isBooted.get(null)).set(false);
    Field descriptors=getAccessibleField(DescriptorRegistry.class,"descriptors");
    ((Map<Type,Descriptor>)descriptors.get(null)).clear();
    Field subtypes=getAccessibleField(DescriptorRegistry.class,"subtypes");
    ((Multimap<Type,Type>)subtypes.get(null)).clear();
  }
 catch (  Exception exception) {
    throw new IllegalArgumentException("Unable to reset plugin booter",exception);
  }
}
 

Example 70

From project core_1, under directory /tools/maven/plugins/switchyard/src/main/java/org/switchyard/tools/maven/plugins/switchyard/.

Source file: SetVersionMojo.java

  29 
vote

private void setVersion(Configuration config,String newVersion,AtomicBoolean modified){
  if (config != null) {
    String oldVersion=config.getValue();
    if (newVersion.equals(oldVersion)) {
      getLog().info(String.format("old version already matches new version: %s - skipping...",newVersion));
      return;
    }
    config.setValue(newVersion);
    modified.set(true);
  }
}
 

Example 71

From project eventtracker, under directory /common/src/test/java/com/ning/metrics/eventtracker/.

Source file: MockCollectorControllerModule.java

  29 
vote

@Override protected void configure(){
  final EventTrackerConfig config=new ConfigurationObjectFactory(System.getProperties()).build(EventTrackerConfig.class);
  bind(EventTrackerConfig.class).toInstance(config);
  final EventSender eventSender=new MockCollectorSender();
  bind(EventSender.class).toInstance(eventSender);
  final ScheduledExecutorService executor=new StubScheduledExecutorService(){
    public AtomicBoolean isShutdown=new AtomicBoolean(false);
    @Override public boolean awaitTermination(    final long timeout,    final TimeUnit unit) throws InterruptedException {
      return true;
    }
    @Override public void shutdown(){
      isShutdown.set(true);
    }
    @Override public List<Runnable> shutdownNow(){
      isShutdown.set(true);
      return new ArrayList<Runnable>();
    }
    @Override public boolean isShutdown(){
      return isShutdown.get();
    }
    @Override public boolean isTerminated(){
      return isShutdown.get();
    }
  }
;
  bind(ScheduledExecutorService.class).toInstance(executor);
  bind(CollectorController.class).toProvider(CollectorControllerProvider.class).asEagerSingleton();
  bind(DiskSpoolEventWriter.class).toInstance(new DiskSpoolEventWriter(new EventHandler(){
    @Override public void handle(    final File file,    final CallbackHandler handler){
      eventSender.send(file,handler);
    }
  }
,config.getSpoolDirectoryName(),config.isFlushEnabled(),config.getFlushIntervalInSeconds(),executor,SyncType.valueOf(config.getSyncType()),config.getSyncBatchSize()));
  bind(EventWriter.class).toProvider(ThresholdEventWriterProvider.class);
}
 

Example 72

From project jafka, under directory /src/main/java/com/sohu/jafka/log/.

Source file: Log.java

  29 
vote

private SegmentList loadSegments() throws IOException {
  List<LogSegment> accum=new ArrayList<LogSegment>();
  File[] ls=dir.listFiles(new FileFilter(){
    public boolean accept(    File f){
      return f.isFile() && f.getName().endsWith(FileSuffix);
    }
  }
);
  logger.info("loadSegments files from [" + dir.getAbsolutePath() + "]: "+ ls.length);
  int n=0;
  for (  File f : ls) {
    n++;
    String filename=f.getName();
    long start=Long.parseLong(filename.substring(0,filename.length() - FileSuffix.length()));
    final String logFormat="LOADING_LOG_FILE[%2d], start(offset)=%d, size=%d, path=%s";
    logger.info(String.format(logFormat,n,start,f.length(),f.getAbsolutePath()));
    FileMessageSet messageSet=new FileMessageSet(f,false);
    accum.add(new LogSegment(f,messageSet,start));
  }
  if (accum.size() == 0) {
    File newFile=new File(dir,Log.nameFromOffset(0));
    FileMessageSet fileMessageSet=new FileMessageSet(newFile,true);
    accum.add(new LogSegment(newFile,fileMessageSet,0));
  }
 else {
    Collections.sort(accum);
    validateSegments(accum);
  }
  LogSegment last=accum.remove(accum.size() - 1);
  last.getMessageSet().close();
  logger.info("Loading the last segment " + last.getFile().getAbsolutePath() + " in mutable mode, recovery "+ needRecovery);
  LogSegment mutable=new LogSegment(last.getFile(),new FileMessageSet(last.getFile(),true,new AtomicBoolean(needRecovery)),last.start());
  accum.add(mutable);
  return new SegmentList(name,accum);
}