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

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 airlift, under directory /bootstrap/src/main/java/io/airlift/bootstrap/.

Source file: ColumnPrinter.java

  20 
vote

private List<AtomicInteger> getColumnWidths(){
  List<AtomicInteger> columnWidths=Lists.newArrayList();
  for (  String columnName : columnNames) {
    columnWidths.add(new AtomicInteger(columnName.length()));
  }
  int columnIndex=0;
  for (  List<String> valueList : data) {
    AtomicInteger width=columnWidths.get(columnIndex++);
    for (    String value : valueList) {
      width.set(Math.max(value.length(),width.intValue()));
    }
  }
  return columnWidths;
}
 

Example 2

From project android_external_guava, under directory /src/com/google/common/collect/.

Source file: AbstractMapBasedMultiset.java

  18 
vote

@Override public boolean remove(Object o){
  if (contains(o)) {
    Entry<?> entry=(Entry<?>)o;
    AtomicInteger frequency=backingMap.remove(entry.getElement());
    int numberRemoved=frequency.getAndSet(0);
    size-=numberRemoved;
    return true;
  }
  return false;
}
 

Example 3

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

Source file: NetworkCounter.java

  18 
vote

/** 
 * Adds the given address and returns the number of addresses in the same Network
 */
private synchronized int addKey(byte[] key){
  AtomicInteger value=map.get(key);
  if (value == null) {
    value=new AtomicInteger();
    map.put(key,value);
  }
  return value.incrementAndGet();
}
 

Example 4

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

Source file: UsingAtomicTest.java

  18 
vote

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

Example 5

From project cascading, under directory /src/hadoop/cascading/tap/hadoop/util/.

Source file: Hadoop18TapUtil.java

  18 
vote

public static synchronized void setupTask(JobConf conf) throws IOException {
  String workpath=conf.get("mapred.work.output.dir");
  if (workpath == null)   return;
  FileSystem fs=getFSSafe(conf,new Path(workpath));
  if (fs == null)   return;
  String taskId=conf.get("mapred.task.id");
  LOG.info("setting up task: '{}' - {}",taskId,workpath);
  AtomicInteger integer=pathCounts.get(workpath);
  if (integer == null) {
    integer=new AtomicInteger();
    pathCounts.put(workpath,integer);
  }
  integer.incrementAndGet();
}
 

Example 6

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

Source file: ConcurrentCommandStatusCounter.java

  18 
vote

public int get(int commandStatus){
  Integer key=new Integer(commandStatus);
  AtomicInteger val=map.get(key);
  if (val == null) {
    return -1;
  }
 else {
    return val.get();
  }
}
 

Example 7

From project cometd, under directory /cometd-java/cometd-java-examples/src/main/java/org/cometd/benchmark/.

Source file: BayeuxLoadClient.java

  18 
vote

public void init(String channel,int room){
  if (latencyListener != null)   getChannel(channel + "/" + room).subscribe(latencyListener);
  AtomicInteger clientsPerRoom=rooms.get(room);
  if (clientsPerRoom == null) {
    clientsPerRoom=new AtomicInteger();
    AtomicInteger existing=rooms.putIfAbsent(room,clientsPerRoom);
    if (existing != null)     clientsPerRoom=existing;
  }
  clientsPerRoom.incrementAndGet();
  subscriptions.add(room);
}
 

Example 8

From project erjang, under directory /src/main/java/erjang/.

Source file: EAbstractNode.java

  18 
vote

public void monitor_node(EHandle caller,boolean on){
  node_monitors.putIfAbsent(caller,new AtomicInteger());
  AtomicInteger ami=node_monitors.get(caller);
  if (on) {
    ami.incrementAndGet();
  }
 else {
    ami.decrementAndGet();
  }
}
 

Example 9

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

Source file: EventQueueBackingStoreFile.java

  18 
vote

@Override protected void incrementFileID(int fileID){
  AtomicInteger counter=logFileIDReferenceCounts.get(fileID);
  if (counter == null) {
    counter=new AtomicInteger(0);
    logFileIDReferenceCounts.put(fileID,counter);
  }
  counter.incrementAndGet();
}
 

Example 10

From project genobyte, under directory /genobyte/src/main/java/org/obiba/bitwise/.

Source file: BitwiseStoreUtil.java

  18 
vote

AtomicInteger getThreadCount(){
  AtomicInteger ai=threadRefCount_.get();
  if (ai == null) {
    threadRefCount_.set(ai=new AtomicInteger());
  }
  return ai;
}
 

Example 11

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

Source file: GsonTypeAdapterTest.java

  18 
vote

public void testTypeAdapterProperlyConvertsTypes() throws Exception {
  int intialValue=1;
  AtomicInteger atomicInt=new AtomicInteger(intialValue);
  String json=gson.toJson(atomicInt);
  assertEquals(intialValue + 1,Integer.parseInt(json));
  atomicInt=gson.fromJson(json,AtomicInteger.class);
  assertEquals(intialValue,atomicInt.get());
}
 

Example 12

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

Source file: GsonTypeAdapterTest.java

  18 
vote

public void testTypeAdapterProperlyConvertsTypes() throws Exception {
  int intialValue=1;
  AtomicInteger atomicInt=new AtomicInteger(intialValue);
  String json=gson.toJson(atomicInt);
  assertEquals(intialValue + 1,Integer.parseInt(json));
  atomicInt=gson.fromJson(json,AtomicInteger.class);
  assertEquals(intialValue,atomicInt.get());
}
 

Example 13

From project ha-jdbc, under directory /src/main/java/net/sf/hajdbc/balancer/load/.

Source file: LoadBalancer.java

  18 
vote

/** 
 * {@inheritDoc}
 * @see net.sf.hajdbc.balancer.Balancer#invoke(net.sf.hajdbc.invocation.Invoker,net.sf.hajdbc.Database,java.lang.Object)
 */
@Override public <T,R,E extends Exception>R invoke(Invoker<Z,D,T,R,E> invoker,D database,T object) throws E {
  AtomicInteger load=this.databaseMap.get(database);
  if (load != null) {
    load.incrementAndGet();
  }
  try {
    return invoker.invoke(database,object);
  }
  finally {
    if (load != null) {
      load.decrementAndGet();
    }
  }
}
 

Example 14

From project hdfs-nfs-proxy, under directory /src/test/java/com/cloudera/hadoop/hdfs/nfs/.

Source file: TestUtils.java

  18 
vote

public static void deepEquals(MessageBase base,MessageBase copy){
  AtomicInteger count=new AtomicInteger(0);
  deepEquals(base,copy,count);
  if (count.get() <= 0) {
    LOGGER.error("Did not test any methods for " + base.getClass().getName());
  }
}
 

Example 15

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

Source file: JMSConsumerTest.java

  17 
vote

public void testMessageListenerWithConsumerCanBeStopped() throws Exception {
  final AtomicInteger counter=new AtomicInteger(0);
  final CountDownLatch done1=new CountDownLatch(1);
  final CountDownLatch done2=new CountDownLatch(1);
  connection.start();
  Session session=connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
  destination=createDestination(session,destinationType);
  MessageConsumer consumer=session.createConsumer(destination);
  consumer.setMessageListener(new MessageListener(){
    public void onMessage(    Message m){
      counter.incrementAndGet();
      if (counter.get() == 1) {
        done1.countDown();
      }
      if (counter.get() == 2) {
        done2.countDown();
      }
    }
  }
);
  sendMessages(session,destination,1);
  assertTrue(done1.await(1,TimeUnit.SECONDS));
  assertEquals(1,counter.get());
  connection.stop();
  sendMessages(session,destination,1);
  assertFalse(done2.await(1,TimeUnit.SECONDS));
  assertEquals(1,counter.get());
  connection.start();
  assertTrue(done2.await(1,TimeUnit.SECONDS));
  assertEquals(2,counter.get());
}
 

Example 16

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

Source file: BlockingTaskTests.java

  17 
vote

@Test public void manyTasks(){
  Runtime rt=getRuntime();
  rt.init();
  final int TASK_COUNT=200;
  final AtomicInteger counter=new AtomicInteger();
  for (int i=0; i < TASK_COUNT; i++) {
    Task task=rt.createBlockingTask(new Body(){
      @Override public void execute(      Runtime rt,      Task current) throws Exception {
        counter.incrementAndGet();
      }
    }
,Runtime.NO_HINTS);
    rt.schedule(task,Runtime.NO_PARENT,Runtime.NO_DEPS);
  }
  rt.shutdown();
  assertTrue(counter.get() == TASK_COUNT);
}
 

Example 17

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

Source file: DefaultFileProcessorTest.java

  17 
vote

@Test public void testProgressingChannel() throws IOException {
  File file=TestFileUtils.createTempFile("test");
  File target=new File(targetDir,"testProgressingChannel");
  target.delete();
  final AtomicInteger progressed=new AtomicInteger();
  ProgressListener listener=new ProgressListener(){
    public void progressed(    ByteBuffer buffer) throws IOException {
      progressed.addAndGet(buffer.remaining());
    }
  }
;
  fileProcessor.copy(file,target,listener);
  assertTrue("file was not created",target.isFile());
  assertEquals("file was not fully copied",4,target.length());
  assertEquals("listener not called",4,progressed.intValue());
  target.delete();
}
 

Example 18

From project almira-sample, under directory /almira-sample-webapp/src/main/java/almira/sample/web/.

Source file: AdminPage.java

  17 
vote

/** 
 * Constructor.
 */
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value={"SE_INNER_CLASS","SIC_INNER_SHOULD_BE_STATIC_ANON"},justification="This is the Wicket way") public AdminPage(){
  super();
  final Label counterLabel=new Label(COUNTER_LABEL_ID,"0");
  add(counterLabel);
  final Label feedbackLabel=new Label(FEEDBACK_LABEL_ID);
  add(feedbackLabel);
  add(new Link<String>("increment_counter_link"){
    @Override public void onClick(){
      final Session session=AdminPage.this.getSession();
      int counterValue=0;
synchronized (session) {
        AtomicInteger counter=(AtomicInteger)session.getAttribute(COUNTER_LABEL_ID);
        if (counter == null) {
          counter=new AtomicInteger();
        }
        counterValue=counter.incrementAndGet();
        session.setAttribute(COUNTER_LABEL_ID,counter);
      }
      counterLabel.setDefaultModel(new Model<Integer>(counterValue));
      LOG.fine("*** Catapult counter value=" + counterValue + " ***");
      feedbackLabel.setDefaultModel(new Model<String>());
    }
  }
);
  add(new Link<String>("rebuild_index"){
    @Override public void onClick(){
      try {
        indexService.rebuildIndex();
        feedbackLabel.setDefaultModel(new Model<String>("Rebuilding index."));
      }
 catch (      Exception e) {
        feedbackLabel.setDefaultModel(new Model<String>("Error rebuilding index!"));
        LOG.log(Level.SEVERE,"Error rebuilding",e);
      }
    }
  }
);
}
 

Example 19

From project amplafi-sworddance, under directory /src/main/java/com/sworddance/taskcontrol/.

Source file: TaskControl.java

  17 
vote

@SuppressWarnings("unchecked") public TaskControl(Comparator<PrioritizedTask> activeComparator,int maxThreads,ThreadFactory threadFactory,Log log){
  this.log=log;
  ApplicationIllegalArgumentException.notNull(activeComparator,"activeComparator");
  this.eligibleTasks=new PriorityBlockingQueue<PrioritizedTask>(20,activeComparator);
  this.stateChangeNotificator=new ReentrantLock();
  this.newTasks=this.stateChangeNotificator.newCondition();
  this.runningTasks=new AtomicInteger(0);
  this.threadFactory=threadFactory;
  int keepAliveTime=10;
  int corePoolSize=1;
  this.executor=new ThreadPoolExecutor(corePoolSize,Math.max(corePoolSize,maxThreads),keepAliveTime,MICROSECONDS,(BlockingQueue)this.eligibleTasks,threadFactory);
  this.stayActive=true;
}
 

Example 20

From project AndroidDevWeekendDub-BookLibrary, under directory /src/org/curiouscreature/android/shelves/activity/.

Source file: ShelvesActivity.java

  17 
vote

public Integer doInBackground(Void... params){
  int imported=0;
  try {
    if (mBooks == null)     mBooks=ImportUtilities.loadItems();
    final List<String> list=mBooks;
    final BooksStore booksStore=BookStoreFactory.get(ShelvesActivity.this);
    final int count=list.size();
    final ContentResolver resolver=mResolver;
    final AtomicInteger importCount=mImportCount;
    for (int i=importCount.get(); i < count; i++) {
      publishProgress(i,count);
      if (isCancelled())       return null;
      final String id=list.get(i);
      if (!BooksManager.bookExists(mResolver,id)) {
        if (isCancelled())         return null;
        BooksStore.Book book=BooksManager.loadAndAddBook(resolver,id,booksStore);
        if (book != null) {
          if (Config.LOGD) {
            android.util.Log.d(LOG_TAG,book.toString());
          }
          imported++;
        }
      }
      importCount.incrementAndGet();
    }
  }
 catch (  IOException e) {
    return null;
  }
  return imported;
}
 

Example 21

From project Arecibo, under directory /util/src/test/java/com/ning/arecibo/util/timeline/samples/.

Source file: TestSampleCoder.java

  17 
vote

@Test(groups="fast") public void testTimeRangeSampleProcessor() throws Exception {
  final DateTime startTime=new DateTime(dateFormatter.parseDateTime("2012-03-23T17:35:11.000Z"));
  final DateTime endTime=new DateTime(dateFormatter.parseDateTime("2012-03-23T17:35:17.000Z"));
  final int sampleCount=2;
  final List<DateTime> dateTimes=ImmutableList.<DateTime>of(startTime,endTime);
  final byte[] compressedTimes=timelineCoder.compressDateTimes(dateTimes);
  final TimelineCursorImpl cursor=new TimelineCursorImpl(compressedTimes,sampleCount);
  Assert.assertEquals(cursor.getNextTime(),startTime);
  Assert.assertEquals(cursor.getNextTime(),endTime);
  final byte[] samples=new byte[]{(byte)0xff,2,2,0,12};
  final AtomicInteger samplesCount=new AtomicInteger(0);
  sampleCoder.scan(samples,compressedTimes,sampleCount,new TimeRangeSampleProcessor(startTime,endTime){
    @Override public void processOneSample(    final DateTime time,    final SampleOpcode opcode,    final Object value){
      if (samplesCount.get() == 0) {
        Assert.assertEquals(DateTimeUtils.unixSeconds(time),DateTimeUtils.unixSeconds(startTime));
      }
 else {
        Assert.assertEquals(DateTimeUtils.unixSeconds(time),DateTimeUtils.unixSeconds(endTime));
      }
      samplesCount.incrementAndGet();
    }
  }
);
  Assert.assertEquals(samplesCount.get(),sampleCount);
}
 

Example 22

From project asterisk-java, under directory /src/integrationtest/org/asteriskjava/manager/.

Source file: TestConcurrentUseOfDefaultManagerConnection.java

  17 
vote

@Override protected void setUp() throws Exception {
  dmc=new DefaultManagerConnection();
  dmc.setUsername("manager");
  dmc.setPassword("obelisk");
  dmc.setHostname("pbx0");
  succeeded=new AtomicInteger(0);
  failed=new AtomicInteger(0);
  total=new AtomicInteger(0);
  dmc.login();
}
 

Example 23

From project atlas, under directory /src/test/java/com/ning/atlas/tree/.

Source file: TestMagicVisitor.java

  17 
vote

@Test public void testOnNoBaton() throws Exception {
  final AtomicInteger waffles=new AtomicInteger(0);
  final AtomicInteger pancakes=new AtomicInteger(0);
  Trees.visit(root,new ArrayList<Pancake>(),new MagicVisitor<Waffle,List<Pancake>>(){
    @SuppressWarnings("unused") void on(    Waffle waffle){
      waffles.incrementAndGet();
    }
    @SuppressWarnings("unused") void on(    Pancake pancake){
      pancakes.incrementAndGet();
    }
  }
);
  assertThat(waffles.get(),equalTo(2));
  assertThat(pancakes.get(),equalTo(3));
}
 

Example 24

From project beam-meris-icol, under directory /src/main/java/org/esa/beam/meris/icol/common/.

Source file: CoastDistanceOp.java

  17 
vote

ZmaxPixelVisitor(int numDistances,final Tile[] masks){
  this.masks=masks;
  this.maskRect=masks[0].getRectangle();
  this.results=new PixelPos[numDistances];
  this.index=new AtomicInteger(0);
}
 

Example 25

From project Blitz, under directory /src/com/laxser/blitz/interceptors/.

Source file: ServiceCutterInterceptor.java

  17 
vote

@Override public Object before(Invocation inv) throws Exception {
  ServiceCutter cutter=inv.getMethod().getAnnotation(ServiceCutter.class);
  if (cutter == null) {
    cutter=inv.getControllerClass().getAnnotation(ServiceCutter.class);
  }
  if (cutter != null) {
    final String methodName=getControllerMethodName(inv);
    inv.setAttribute(BLOCK_SERVICE_CUTTER,BlockService.setEnabledAndTimeout(cutter.enabled(),cutter.timeout()));
    int maxCount=ConfigCenter.getInteger(methodName,cutter.maxConcurrent());
    if (maxCount > 0) {
      AtomicInteger count=map.get(methodName);
      AtomicInteger maxHistoryCount=map.get(methodName + "__max");
      if (count == null) {
        count=new AtomicInteger(0);
        maxHistoryCount=new AtomicInteger(0);
        map.putIfAbsent(methodName,count);
        map.putIfAbsent(methodName + "__max",maxHistoryCount);
      }
      if (count.get() >= maxCount) {
        log.error(methodName + " --> controller reaches at the max concurrent " + maxCount);
        return cutter.instruction();
      }
      int currentCount=count.incrementAndGet();
      if (maxHistoryCount.get() < currentCount) {
        maxHistoryCount.set(currentCount);
      }
      inv.setAttribute(KEY_SERVICECUTTER,count);
    }
    if (log.isDebugEnabled()) {
      log.debug(String.format("%s:ServiceCutter|%s#%s|%s:%s",Thread.currentThread().getName(),inv.getControllerClass().getSimpleName(),methodName,cutter.enabled(),cutter.timeout()));
    }
  }
  return Boolean.TRUE;
}
 

Example 26

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

Source file: TestAcquireFailConfig.java

  17 
vote

/** 
 * Test getters/setters for acquireFail class.
 */
@SuppressWarnings("deprecation") @Test public void testGettersSetters(){
  Object obj=new Object();
  AcquireFailConfig config=new AcquireFailConfig();
  config.setAcquireRetryAttempts(new AtomicInteger(1));
  config.setAcquireRetryDelayInMs(123);
  config.setAcquireRetryDelay(123);
  config.setLogMessage("test");
  config.setDebugHandle(obj);
  assertEquals(1,config.getAcquireRetryAttempts().get());
  assertEquals(123,config.getAcquireRetryDelayInMs());
  assertEquals(123,config.getAcquireRetryDelay());
  assertEquals("test",config.getLogMessage());
  assertEquals(obj,config.getDebugHandle());
}
 

Example 27

From project BoneJ, under directory /src/org/doube/bonej/.

Source file: Connectivity.java

  17 
vote

/** 
 * Calculate the Euler characteristic of the foreground in a binary stack
 * @param imp Binary ImagePlus
 * @return Euler characteristic of the foreground particles
 */
public double getSumEuler(ImagePlus imp){
  setDimensions(imp);
  final ImageStack stack=imp.getImageStack();
  final int eulerLUT[]=new int[256];
  fillEulerLUT(eulerLUT);
  final int[] sumEulerInt=new int[depth + 1];
  final AtomicInteger ai=new AtomicInteger(0);
  Thread[] threads=Multithreader.newThreads();
  for (int thread=0; thread < threads.length; thread++) {
    threads[thread]=new Thread(new Runnable(){
      public void run(){
        long deltaEuler=0;
        for (int z=ai.getAndIncrement(); z <= depth; z=ai.getAndIncrement()) {
          for (int y=0; y <= height; y++) {
            for (int x=0; x <= width; x++) {
              final byte[] octant=getOctant(stack,x,y,z);
              if (octant[0] > 0) {
                deltaEuler=getDeltaEuler(octant,eulerLUT);
                sumEulerInt[z]+=deltaEuler;
              }
            }
          }
        }
      }
    }
);
  }
  Multithreader.startAndJoin(threads);
  double sumEuler=0;
  for (int i=0; i < sumEulerInt.length; i++) {
    sumEuler+=sumEulerInt[i];
  }
  sumEuler/=8;
  return sumEuler;
}
 

Example 28

From project bson4jackson, under directory /src/test/java/de/undercouch/bson4jackson/.

Source file: BsonParserTest.java

  17 
vote

/** 
 * Tests reading a very large string using multiple threads. Refers issue #19. Does not fail reproducibly, but with very high probability. You may have to run unit tests several times though to really rule out multi-threading issues.
 * @throws Exception if something went wrong
 * @author endasb
 */
@Test public void parseBigStringInThreads() throws Exception {
  final BSONObject o=new BasicBSONObject();
  final AtomicInteger fails=new AtomicInteger(0);
  StringBuilder bigStr=new StringBuilder();
  for (int i=0; i < 80000; i++) {
    bigStr.append("abc");
  }
  o.put("String",bigStr.toString());
  ArrayList<Thread> threads=new ArrayList<Thread>();
  for (int i=0; i < 50; i++) {
    threads.add(new Thread(new Runnable(){
      @Override public void run(){
        try {
          Map<?,?> data=parseBsonObject(o);
          data=parseBsonObject(o);
          assertNotNull(data);
        }
 catch (        Exception e) {
          fail("Threading issue " + fails.incrementAndGet());
        }
      }
    }
));
  }
  for (  Thread thread : threads) {
    thread.start();
  }
  for (  Thread thread : threads) {
    thread.join();
  }
  assertEquals(0,fails.get());
}
 

Example 29

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

Source file: DelayEnhancement.java

  17 
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 30

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

Source file: Ref.java

  17 
vote

public Ref(Object initVal,IPersistentMap meta){
  super(meta);
  this.id=ids.getAndIncrement();
  this.faults=new AtomicInteger();
  this.lock=new ReentrantReadWriteLock();
  tvals=new TVal(initVal,0,System.currentTimeMillis());
}
 

Example 31

From project clustermeister, under directory /provisioning/src/main/java/com/github/nethad/clustermeister/provisioning/torque/.

Source file: TorqueJPPFNodeDeployer.java

  17 
vote

public TorqueJPPFNodeDeployer(TorqueConfiguration configuration,SSHClient sshClient){
  this.configuration=configuration;
  isInfrastructureDeployed=false;
  currentNodeNumber=new AtomicInteger(0);
  sessionId=System.currentTimeMillis();
  loadConfiguration();
  this.sshClient=sshClient;
  publicIpListener=new ArrayList<Observer>();
}
 

Example 32

From project cogroo4, under directory /cogroo-eval/GramEval/src/main/java/cogroo/uima/eval/.

Source file: Stats.java

  17 
vote

public void addTarget(String type){
  if (!targetForOutcome.containsKey(type)) {
    targetForOutcome.put(type,new AtomicInteger());
  }
  targetForOutcome.get(type).incrementAndGet();
}
 

Example 33

From project Core_2, under directory /shell-api/src/test/java/org/jboss/forge/project/dependencies/.

Source file: CompositeDependencyFilterTest.java

  17 
vote

@Test public void testAccept(){
  final AtomicInteger counter=new AtomicInteger();
  DependencyFilter first=new DependencyFilter(){
    @Override public boolean accept(    Dependency dependency){
      return false;
    }
  }
;
  DependencyFilter second=new DependencyFilter(){
    @Override public boolean accept(    Dependency dependency){
      counter.incrementAndGet();
      return true;
    }
  }
;
  CompositeDependencyFilter filter=new CompositeDependencyFilter(first,second);
  boolean returnedValue=filter.accept(DependencyBuilder.create("org.jboss.forge:forge-api"));
  assertFalse(returnedValue);
  assertEquals("Second Filter should not have been called",0,counter.get());
}
 

Example 34

From project crash, under directory /shell/core/src/test/java/org/crsh/shell/impl/async/.

Source file: FailureTestCase.java

  17 
vote

public void testEvaluating() throws Exception {
  final AtomicReference<Throwable> failure=new AtomicReference<Throwable>();
  final AtomicInteger cancelCount=new AtomicInteger(0);
  BaseProcessFactory factory=new BaseProcessFactory(){
    @Override public BaseProcess create(    String request){
      return new BaseProcess(request){
        @Override protected ShellResponse execute(        String request){
          throw new RuntimeException();
        }
        @Override public void cancel(){
          failure.set(failure("Was expecting no cancel callback"));
        }
      }
;
    }
  }
;
  Shell shell=new BaseShell(factory);
  CommandQueue commands=new CommandQueue();
  AsyncShell asyncShell=new AsyncShell(commands,shell);
  BaseProcessContext ctx=BaseProcessContext.create(asyncShell,"foo").execute();
  assertEquals(Status.QUEUED,((AsyncProcess)ctx.getProcess()).getStatus());
  assertEquals(0,cancelCount.get());
  assertEquals(1,commands.getSize());
  Future<?> future=commands.executeAsync();
  future.get();
  assertEquals(ShellResponse.Error.class,ctx.getResponse().getClass());
}
 

Example 35

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

Source file: TestCompression.java

  17 
vote

@Test public void testCompressionProvider() throws Exception {
  final byte[] data="here's a string".getBytes();
  final AtomicInteger compressCounter=new AtomicInteger();
  final AtomicInteger decompressCounter=new AtomicInteger();
  CompressionProvider compressionProvider=new CompressionProvider(){
    @Override public byte[] compress(    String path,    byte[] data) throws Exception {
      compressCounter.incrementAndGet();
      byte[] bytes=new byte[data.length * 2];
      System.arraycopy(data,0,bytes,0,data.length);
      System.arraycopy(data,0,bytes,data.length,data.length);
      return bytes;
    }
    @Override public byte[] decompress(    String path,    byte[] compressedData) throws Exception {
      decompressCounter.incrementAndGet();
      byte[] bytes=new byte[compressedData.length / 2];
      System.arraycopy(compressedData,0,bytes,0,bytes.length);
      return bytes;
    }
  }
;
  CuratorFramework client=CuratorFrameworkFactory.builder().compressionProvider(compressionProvider).connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build();
  try {
    client.start();
    client.create().compressed().creatingParentsIfNeeded().forPath("/a/b/c",data);
    Assert.assertNotEquals(data,client.getData().forPath("/a/b/c"));
    Assert.assertEquals(data.length,client.getData().decompressed().forPath("/a/b/c").length);
  }
  finally {
    Closeables.closeQuietly(client);
  }
  Assert.assertEquals(compressCounter.get(),1);
  Assert.assertEquals(decompressCounter.get(),1);
}
 

Example 36

From project datasalt-utils, under directory /src/main/java/com/datasalt/utils/commons/flow/.

Source file: BarrierExecutable.java

  17 
vote

public static void main(String args[]) throws Exception {
  final AtomicInteger count=new AtomicInteger();
  Executable<Object> e=new Executable(){
    @Override public void execute(    Object config) throws Exception {
      log.info("Yeah " + count.addAndGet(1));
    }
  }
;
  ChainableExecutable r=new ChainableExecutable("u1",null,null,e);
  BarrierExecutable b=new BarrierExecutable("u.2",null,r);
  ChainableExecutable c=new ChainableExecutable("u1.1",null,b,e);
  c=new ChainableExecutable("u1.1.1",null,c,e);
  c=new ChainableExecutable("u1.2",null,b,e);
  r.execute(null);
}
 

Example 37

From project DeuceSTM, under directory /src/java/org/deuce/transaction/lsacm/.

Source file: Context.java

  17 
vote

public Context(){
  id=threadID.incrementAndGet();
  threads.put(id,this);
  attempts=0;
  vr=false;
  startTime=new AtomicLong(0L);
  status=new AtomicInteger(TX_IDLE);
}
 

Example 38

From project droolsjbpm-integration, under directory /drools-grid/drools-grid-impl/src/main/java/org/drools/grid/io/impl/.

Source file: ConversationImpl.java

  17 
vote

public ConversationImpl(Connector conn,String conversationId,String senderId,String recipientId,RequestResponseDispatchListener dispathListener,Message receivedMessage,IoWriter writer,ConversationManager conversationManager){
  this.conn=conn;
  this.conversationId=conversationId;
  this.senderId=senderId;
  this.recipientId=recipientId;
  this.dispathListener=dispathListener;
  this.writer=writer;
  this.requestId=new AtomicInteger();
  this.receivedMessage=receivedMessage;
  this.conversationManager=conversationManager;
}
 

Example 39

From project efflux, under directory /src/functionaltest/java/com/biasedbit/efflux/session/.

Source file: MultiParticipantSessionFunctionalTest.java

  17 
vote

@Test public void testDeliveryToAllParticipants() throws Exception {
  this.sessions=new MultiParticipantSession[N];
  final AtomicInteger[] counters=new AtomicInteger[N];
  final CountDownLatch latch=new CountDownLatch(N);
  for (byte i=0; i < N; i++) {
    RtpParticipant participant=RtpParticipant.createReceiver(new RtpParticipantInfo(i),"127.0.0.1",10000 + (i * 2),20001 + (i * 2));
    this.sessions[i]=new MultiParticipantSession("session" + i,8,participant);
    assertTrue(this.sessions[i].init());
    final AtomicInteger counter=new AtomicInteger();
    counters[i]=counter;
    this.sessions[i].addDataListener(new RtpSessionDataListener(){
      @Override public void dataPacketReceived(      RtpSession session,      RtpParticipantInfo participant,      DataPacket packet){
        System.err.println(session.getId() + " received data from " + participant+ ": "+ packet);
        if (counter.incrementAndGet() == ((N - 1) * 2)) {
          latch.countDown();
        }
      }
    }
);
  }
  for (byte i=0; i < N; i++) {
    for (byte j=0; j < N; j++) {
      if (j == i) {
        continue;
      }
      RtpParticipant participant=RtpParticipant.createReceiver(new RtpParticipantInfo(j),"127.0.0.1",10000 + (j * 2),20001 + (j * 2));
      System.err.println("Adding " + participant + " to session "+ this.sessions[i].getId());
      assertTrue(this.sessions[i].addReceiver(participant));
    }
  }
  byte[] deadbeef={(byte)0xde,(byte)0xad,(byte)0xbe,(byte)0xef};
  for (byte i=0; i < N; i++) {
    assertTrue(this.sessions[i].sendData(deadbeef,0x45,false));
    assertTrue(this.sessions[i].sendData(deadbeef,0x45,false));
  }
  latch.await(5000L,TimeUnit.MILLISECONDS);
  for (byte i=0; i < N; i++) {
    assertEquals(((N - 1) * 2),counters[i].get());
  }
}
 

Example 40

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

Source file: TestHttpSenderWorkers.java

  17 
vote

@Test(groups="slow") public void testSuccess() throws Exception {
  final CountDownLatch latch=new CountDownLatch(1);
  final AtomicInteger successes=new AtomicInteger(0);
  final AtomicInteger failures=new AtomicInteger(0);
  final File file=Mockito.mock(File.class);
  final CallbackHandler handler=new CallbackHandler(){
    @Override public void onError(    final Throwable t,    final File file){
      failures.incrementAndGet();
      latch.countDown();
    }
    @Override public void onSuccess(    final File obj){
      successes.incrementAndGet();
      latch.countDown();
    }
  }
;
  final AtomicInteger recreations=new AtomicInteger(0);
  final ThreadSafeWithMockedAsyncHttpClient client=new ThreadSafeWithMockedAsyncHttpClient(recreations,false,false);
  final HttpSender sender=new HttpSender(client,System.currentTimeMillis(),Mockito.mock(Timer.class),10);
  Assert.assertEquals(successes.get(),0);
  Assert.assertEquals(failures.get(),0);
  Assert.assertEquals(recreations.get(),0);
  sender.send(file,handler);
  latch.await();
  Assert.assertEquals(successes.get(),1);
  Assert.assertEquals(failures.get(),0);
  Assert.assertEquals(recreations.get(),1);
  Mockito.verify(client.getClient(),Mockito.times(0)).close();
  sender.close();
  Mockito.verify(client.getClient(),Mockito.times(1)).close();
}
 

Example 41

From project fed4j, under directory /src/main/java/com/jute/fed4j/engine/.

Source file: Workflow.java

  17 
vote

WorkflowNode(Component component){
  this.name=component.name;
  this.component=component;
  if (this.component.type == ComponentType.JOIN) {
    count=new AtomicInteger(0);
    parents=new LinkedList();
  }
 else   if (this.component.type == ComponentType.FORK) {
    children=new LinkedList();
  }
}
 

Example 42

From project Flapi, under directory /src/main/java/unquietcode/tools/flapi/graph/processors/.

Source file: ReturnValueProcessor.java

  17 
vote

public JExpression computeReturnValue(Transition transition,final JMethod method){
  final List<JVar> helpers=new ArrayList<JVar>();
  for (  StateClass sequenceState : transition.getStateChain()) {
    JType wrappedType=ref(ObjectWrapper.class).narrow(HELPER_INTERFACE_STRATEGY.createType(ctx,sequenceState));
    JVar _helper=method.body().decl(wrappedType,"helper" + (helpers.size() + 1),JExpr._new(wrappedType));
    helpers.add(_helper);
  }
  final JVar helperResult=addHelperCall(transition,method,helpers);
  final ObjectWrapper<JExpression> initialValue=new ObjectWrapper<JExpression>();
  final AtomicInteger counter=new AtomicInteger(1);
  transition.accept(new TransitionVisitor(){
    @Override public void visit(    AscendingTransition transition){
      initialValue.set(JExpr.ref(Constants.RETURN_VALUE_NAME));
    }
    @Override public void visit(    LateralTransition transition){
      JDefinedClass cTargetBuilder=BUILDER_CLASS_STRATEGY.createType(ctx,transition.getSibling());
      initialValue.set(method.body().decl(cTargetBuilder,"step" + counter.getAndIncrement(),JExpr._new(cTargetBuilder).arg(JExpr.ref(Constants.HELPER_VALUE_NAME)).arg(JExpr.ref(Constants.RETURN_VALUE_NAME))));
    }
    @Override public void visit(    RecursiveTransition transition){
      initialValue.set(JExpr._this());
    }
    @Override public void visit(    TerminalTransition transition){
      if (helperResult != null) {
        initialValue.set(helperResult);
      }
 else {
        initialValue.set(JExpr._null());
      }
    }
  }
);
  JExpression returnValue=initialValue.get();
  for (int i=transition.getStateChain().size() - 1; i >= 0; --i) {
    StateClass sequentialState=transition.getStateChain().get(i);
    JDefinedClass cTargetBuilder=BUILDER_CLASS_STRATEGY.createType(ctx,sequentialState);
    returnValue=method.body().decl(cTargetBuilder,"step" + counter.getAndIncrement(),JExpr._new(cTargetBuilder).arg(helpers.get(i).invoke("get")).arg(returnValue));
  }
  return returnValue;
}
 

Example 43

From project Flume-Hive, under directory /src/java/com/cloudera/flume/handlers/debug/.

Source file: LatchedDecorator.java

  17 
vote

public LatchedDecorator(S s,int pre,int count){
  super(s);
  this.latch=new CountDownLatch(count);
  this.pre=pre;
  this.precount=new AtomicInteger(pre);
}
 

Example 44

From project flume_1, under directory /flume-core/src/main/java/com/cloudera/flume/handlers/debug/.

Source file: LatchedDecorator.java

  17 
vote

public LatchedDecorator(S s,int pre,int count){
  super(s);
  this.latch=new CountDownLatch(count);
  this.pre=pre;
  this.precount=new AtomicInteger(pre);
}
 

Example 45

From project gecko, under directory /src/test/java/com/taobao/gecko/core/nio/impl/.

Source file: SelectorManagerUnitTest.java

  17 
vote

@Test public void testInsertMoreTimers() throws Exception {
  final AtomicInteger count=new AtomicInteger(0);
  long start=System.currentTimeMillis();
  for (int i=0; i < 100000; i++) {
    this.selectorManager.insertTimer(new TimerRef(2000,new Runnable(){
      long start=System.currentTimeMillis();
      public void run(){
        long duration=System.currentTimeMillis() - this.start;
        Assert.assertEquals(2000,duration,500);
        count.incrementAndGet();
      }
    }
));
  }
  System.out.println(System.currentTimeMillis() - start);
  Thread.sleep(5000);
  Assert.assertEquals(100000,count.get());
}
 

Example 46

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

Source file: AsynchronousToolExecutorTest.java

  17 
vote

@Test public void testSeveralThreadsWaitingForNormalExecution() throws Exception {
  final int nThreads=10;
  Thread[] threads=new Thread[nThreads];
  final AtomicInteger completedThreads=new AtomicInteger(0);
  for (int i=0; i < nThreads; i++) {
    threads[i]=new Thread(){
      @Override public void run(){
        asyncExecutor.waitUntilFinished();
        completedThreads.incrementAndGet();
      }
    }
;
  }
  asyncExecutor.invoke();
  for (int i=0; i < nThreads; i++) {
    threads[i].start();
  }
  for (int i=0; i < nThreads; i++) {
    try {
      threads[i].join();
    }
 catch (    InterruptedException e) {
    }
  }
  assertTrue("The underlying task did not complete",dummyTask.isCompleted());
  assertEquals("Some of the threads did not complete",nThreads,completedThreads.get());
}
 

Example 47

From project giraph, under directory /src/main/java/org/apache/giraph/comm/messages/.

Source file: DiskBackedMessageStore.java

  17 
vote

/** 
 * @param combiner         Combiner for messages
 * @param config           Hadoop configuration
 * @param fileStoreFactory Factory for creating file stores when flushing
 */
public DiskBackedMessageStore(VertexCombiner<I,M> combiner,ImmutableClassesGiraphConfiguration<I,?,?,M> config,MessageStoreFactory<I,M,BasicMessageStore<I,M>> fileStoreFactory){
  inMemoryMessages=new ConcurrentSkipListMap<I,Collection<M>>();
  this.config=config;
  this.combiner=combiner;
  numberOfMessagesInMemory=new AtomicInteger(0);
  destinationVertices=Collections.newSetFromMap(Maps.<I,Boolean>newConcurrentMap());
  fileStores=Lists.newArrayList();
  this.fileStoreFactory=fileStoreFactory;
}
 

Example 48

From project gitblit, under directory /src/com/gitblit/wicket/panels/.

Source file: CommitLegendPanel.java

  17 
vote

protected Map<ChangeType,AtomicInteger> getChangedPathsStats(List<PathChangeModel> paths){
  Map<ChangeType,AtomicInteger> stats=new HashMap<ChangeType,AtomicInteger>();
  for (  PathChangeModel path : paths) {
    if (!stats.containsKey(path.changeType)) {
      stats.put(path.changeType,new AtomicInteger(0));
    }
    stats.get(path.changeType).incrementAndGet();
  }
  return stats;
}
 

Example 49

From project gnip4j, under directory /core/src/test/java/com/zaubersoftware/gnip4j/http/.

Source file: LocalhostTestDriver.java

  17 
vote

@Test public void test() throws Exception {
  try {
    final UriStrategy uriStrategy=new UriStrategy(){
      @Override public URI createStreamUri(      final String domain,      final String streamName){
        return URI.create("http://localhost:8080");
      }
      @Override public URI createRulesUri(      final String domain,      final String streamName){
        return null;
      }
    }
;
    final JRERemoteResourceProvider resourceProvider=new JRERemoteResourceProvider(new ImmutableGnipAuthentication("foo","bar"));
    final GnipFacade gnip=new DefaultGnipFacade(resourceProvider,uriStrategy);
    System.out.println("-- Creating stream");
    final AtomicInteger counter=new AtomicInteger();
    final StreamNotificationAdapter n=new StreamNotificationAdapter(){
      @Override public void notify(      final Activity activity,      final GnipStream stream){
        final int i=counter.getAndIncrement();
        if (i >= 100000) {
          System.out.println("-- Closing stream.");
          stream.close();
        }
        System.out.println(i + "-" + activity.getBody()+ " "+ activity.getGnip().getMatchingRules());
      }
    }
;
    final GnipStream stream=gnip.createStream("test-account","test-stream",n);
    System.out.println("-- Awaiting for stream to terminate");
    stream.await();
    System.out.println("-- Shutting down");
  }
 catch (  final Throwable t) {
    System.out.println(t.getMessage());
    t.printStackTrace();
  }
}
 

Example 50

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

Source file: BindingTest.java

  17 
vote

public void testToConstructorAndMethodInterceptors() throws NoSuchMethodException {
  final Constructor<D> constructor=D.class.getConstructor(Stage.class);
  final AtomicInteger count=new AtomicInteger();
  final MethodInterceptor countingInterceptor=new MethodInterceptor(){
    public Object invoke(    MethodInvocation methodInvocation) throws Throwable {
      count.incrementAndGet();
      return methodInvocation.proceed();
    }
  }
;
  Injector injector=Guice.createInjector(new AbstractModule(){
    protected void configure(){
      bind(Object.class).toConstructor(constructor);
      bindInterceptor(Matchers.any(),Matchers.any(),countingInterceptor);
    }
  }
);
  D d=(D)injector.getInstance(Object.class);
  d.hashCode();
  d.hashCode();
  assertEquals(2,count.get());
}
 

Example 51

From project hama, under directory /core/src/test/java/org/apache/hama/monitor/.

Source file: TestFederator.java

  17 
vote

public void testExecutionFlow() throws Exception {
  LOG.info("Value before submitted: " + expected);
  final AtomicInteger finalResult=new AtomicInteger(0);
  final Act act=new Act(new DummyCollector(expected),new CollectorHandler(){
    public void handle(    Future future){
      try {
        finalResult.set(((Integer)future.get()).intValue());
        LOG.info("Value after submitted: " + finalResult);
      }
 catch (      ExecutionException ee) {
        LOG.error(ee);
      }
catch (      InterruptedException ie) {
        LOG.error(ie);
        Thread.currentThread().interrupt();
      }
    }
  }
);
  this.federator.register(act);
  Thread.sleep(3 * 1000);
  assertEquals("Result should be " + (expected + 1) + ".",finalResult.get(),(expected + 1));
}
 

Example 52

From project hawtdispatch, under directory /hawtdispatch/src/main/java/org/fusesource/hawtdispatch/internal/util/.

Source file: RunnableSupport.java

  17 
vote

public static Task runOnceAfter(final Task runnable,int count){
  if (runnable == null) {
    return NO_OP;
  }
  if (count == 0) {
    runnable.run();
    return NO_OP;
  }
  if (count == 1) {
    return runnable;
  }
  final AtomicInteger counter=new AtomicInteger(count);
  return new Task(){
    public void run(){
      if (counter.decrementAndGet() == 0) {
        runnable.run();
      }
    }
    public String toString(){
      return "{" + runnable + "}";
    }
  }
;
}
 

Example 53

From project hawtjournal, under directory /src/test/java/org/fusesource/hawtjournal/api/.

Source file: JournalTest.java

  17 
vote

@Test public void testConcurrentWriteAndRead() throws Exception {
  final AtomicInteger counter=new AtomicInteger(0);
  ExecutorService executor=Executors.newFixedThreadPool(25);
  int iterations=1000;
  for (int i=0; i < iterations; i++) {
    final int index=i;
    executor.submit(new Runnable(){
      public void run(){
        try {
          boolean sync=index % 2 == 0 ? true : false;
          String write=new String("DATA" + index);
          Location location=journal.write(ByteBuffer.wrap(write.getBytes("UTF-8")),sync);
          String read=new String(journal.read(location).array(),"UTF-8");
          if (read.equals("DATA" + index)) {
            counter.incrementAndGet();
          }
 else {
            System.out.println(write);
            System.out.println(read);
          }
        }
 catch (        Exception ex) {
          ex.printStackTrace();
        }
      }
    }
);
  }
  executor.shutdown();
  assertTrue(executor.awaitTermination(1,TimeUnit.MINUTES));
  assertEquals(iterations,counter.get());
}
 

Example 54

From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/.

Source file: AggregateConverter.java

  16 
vote

public Object convertToNumber(Number value,Class toType) throws Exception {
  toType=unwrap(toType);
  if (AtomicInteger.class == toType) {
    return new AtomicInteger((Integer)convertToNumber(value,Integer.class));
  }
 else   if (AtomicLong.class == toType) {
    return new AtomicLong((Long)convertToNumber(value,Long.class));
  }
 else   if (Integer.class == toType) {
    return value.intValue();
  }
 else   if (Short.class == toType) {
    return value.shortValue();
  }
 else   if (Long.class == toType) {
    return value.longValue();
  }
 else   if (Float.class == toType) {
    return value.floatValue();
  }
 else   if (Double.class == toType) {
    return value.doubleValue();
  }
 else   if (Byte.class == toType) {
    return value.byteValue();
  }
 else   if (BigInteger.class == toType) {
    return new BigInteger(value.toString());
  }
 else   if (BigDecimal.class == toType) {
    return new BigDecimal(value.toString());
  }
 else {
    throw new Exception("Unable to convert number " + value + " to "+ toType);
  }
}
 

Example 55

From project capedwarf-blue, under directory /datastore/src/main/java/org/jboss/capedwarf/datastore/query/.

Source file: JBossCursorHelper.java

  16 
vote

static Cursor createListCursor(FetchOptions fetchOptions){
  if (fetchOptions == null)   return null;
  final Cursor end=fetchOptions.getEndCursor();
  if (end != null)   return end;
  final Integer limit=fetchOptions.getLimit();
  if (limit != null) {
    int offset=0;
    final Cursor start=fetchOptions.getStartCursor();
    if (start != null) {
      offset=readIndex(start);
    }
 else {
      final Integer x=fetchOptions.getOffset();
      if (x != null) {
        offset=x;
      }
    }
    return createCursor(new AtomicInteger(offset + limit));
  }
 else {
    return null;
  }
}
 

Example 56

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

Source file: DefaultWindowFuture.java

  16 
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 57

From project Dempsy, under directory /lib-dempsyimpl/src/main/java/com/nokia/dempsy/monitoring/coda/.

Source file: StatsCollectorCoda.java

  16 
vote

public StatsCollectorCoda(ClusterId clusterId){
  scope=clusterId.getApplicationName() + "." + clusterId.getMpClusterName();
  messagesReceived=Metrics.newMeter(Dempsy.class,MN_MSG_RCVD,scope,"messages",TimeUnit.SECONDS);
  bytesReceived=Metrics.newMeter(Dempsy.class,MN_BYTES_RCVD,scope,"bytes",TimeUnit.SECONDS);
  messagesDiscarded=Metrics.newMeter(Dempsy.class,MN_MSG_DISCARD,scope,"messages",TimeUnit.SECONDS);
  messagesDispatched=Metrics.newMeter(Dempsy.class,MN_MSG_DISPATCH,scope,"messages",TimeUnit.SECONDS);
  messagesFwFailed=Metrics.newMeter(Dempsy.class,MN_MSG_FWFAIL,scope,"messages",TimeUnit.SECONDS);
  messagesMpFailed=Metrics.newMeter(Dempsy.class,MN_MSG_MPFAIL,scope,"messages",TimeUnit.SECONDS);
  messagesProcessed=Metrics.newMeter(Dempsy.class,MN_MSG_PROC,scope,"messages",TimeUnit.SECONDS);
  messagesSent=Metrics.newMeter(Dempsy.class,MN_MSG_SENT,scope,"messages",TimeUnit.SECONDS);
  bytesSent=Metrics.newMeter(Dempsy.class,MN_BYTES_SENT,scope,"bytes",TimeUnit.SECONDS);
  messagesUnsent=Metrics.newMeter(Dempsy.class,MN_MSG_UNSENT,scope,"messsages",TimeUnit.SECONDS);
  inProcessMessages=new AtomicInteger();
  messagesInProcess=Metrics.newGauge(Dempsy.class,GAGE_MPS_IN_PROCESS,scope,new Gauge<Integer>(){
    @Override public Integer value(){
      return inProcessMessages.get();
    }
  }
);
  numberOfMPs=new AtomicLong();
  mpsCreated=Metrics.newMeter(Dempsy.class,MN_MP_CREATE,scope,"instances",TimeUnit.SECONDS);
  mpsDeleted=Metrics.newMeter(Dempsy.class,MN_MP_DELETE,scope,"instances",TimeUnit.SECONDS);
  messageProcessors=Metrics.newGauge(Dempsy.class,"message-processors",scope,new Gauge<Long>(){
    @Override public Long value(){
      return numberOfMPs.get();
    }
  }
);
  preInstantiationDuration=Metrics.newTimer(Dempsy.class,TM_MP_PREIN,scope,TimeUnit.MILLISECONDS,TimeUnit.SECONDS);
  mpHandleMessageDuration=Metrics.newTimer(Dempsy.class,TM_MP_HANDLE,scope,TimeUnit.MILLISECONDS,TimeUnit.SECONDS);
  outputInvokeDuration=Metrics.newTimer(Dempsy.class,TM_MP_OUTPUT,scope,TimeUnit.MILLISECONDS,TimeUnit.SECONDS);
  evictionInvokeDuration=Metrics.newTimer(Dempsy.class,TM_MP_EVIC,scope,TimeUnit.MILLISECONDS,TimeUnit.SECONDS);
}
 

Example 58

From project floodlight, under directory /src/main/java/net/floodlightcontroller/core/internal/.

Source file: OFSwitchImpl.java

  16 
vote

public OFSwitchImpl(){
  this.attributes=new ConcurrentHashMap<Object,Object>();
  this.connectedSince=new Date();
  this.transactionIdSource=new AtomicInteger();
  this.portLock=new Object();
  this.portsByNumber=new ConcurrentHashMap<Short,OFPhysicalPort>();
  this.portsByName=new ConcurrentHashMap<String,OFPhysicalPort>();
  this.connected=true;
  this.statsFutureMap=new ConcurrentHashMap<Integer,OFStatisticsFuture>();
  this.iofMsgListenersMap=new ConcurrentHashMap<Integer,IOFMessageListener>();
  this.role=null;
  this.timedCache=new TimedCache<Long>(100,5 * 1000);
  this.listenerLock=new ReentrantReadWriteLock();
  this.portBroadcastCacheHitMap=new ConcurrentHashMap<Short,Long>();
  this.pendingRoleRequests=new LinkedList<OFSwitchImpl.PendingRoleRequestEntry>();
  this.setAttribute(PROP_FASTWILDCARDS,OFMatch.OFPFW_ALL);
  this.setAttribute(PROP_SUPPORTS_OFPP_FLOOD,new Boolean(true));
  this.setAttribute(PROP_SUPPORTS_OFPP_TABLE,new Boolean(true));
}
 

Example 59

From project griffon, under directory /subprojects/griffon-shell/src/main/groovy/org/apache/felix/gogo/commands/converter/.

Source file: GriffonDefaultConverter.java

  16 
vote

public Object convertToNumber(Number value,Class toType) throws Exception {
  toType=unwrap(toType);
  if (AtomicInteger.class == toType) {
    return new AtomicInteger((Integer)convertToNumber(value,Integer.class));
  }
 else   if (AtomicLong.class == toType) {
    return new AtomicLong((Long)convertToNumber(value,Long.class));
  }
 else   if (Integer.class == toType) {
    return value.intValue();
  }
 else   if (Short.class == toType) {
    return value.shortValue();
  }
 else   if (Long.class == toType) {
    return value.longValue();
  }
 else   if (Float.class == toType) {
    return value.floatValue();
  }
 else   if (Double.class == toType) {
    return value.doubleValue();
  }
 else   if (Byte.class == toType) {
    return value.byteValue();
  }
 else   if (BigInteger.class == toType) {
    return new BigInteger(value.toString());
  }
 else   if (BigDecimal.class == toType) {
    return new BigDecimal(value.toString());
  }
 else {
    throw new Exception("Unable to convert number " + value + " to "+ toType);
  }
}
 

Example 60

From project Activiti-KickStart, under directory /activiti-kickstart-java/src/main/java/org/activiti/kickstart/service/.

Source file: MarshallingServiceImpl.java

  15 
vote

protected void convertTaskBlockToBpmn20(Process process,AtomicInteger flowIndex,AtomicInteger gatewayIndex,List<FlowElement> taskBlock,List<FlowElement> lastFlowElementOfBlockStack){
  SequenceFlow sequenceFlow=createSequenceFlow(process,flowIndex,getLast(lastFlowElementOfBlockStack),null);
  if (taskBlock.size() == 1) {
    FlowElement userTask=taskBlock.get(0);
    sequenceFlow.setTargetRef(userTask);
    lastFlowElementOfBlockStack.add(userTask);
    process.getFlowElement().add(userTask);
  }
 else {
    ParallelGateway fork=new ParallelGateway();
    fork.setId("parallel_gateway_fork_" + gatewayIndex.getAndIncrement());
    process.getFlowElement().add(fork);
    sequenceFlow.setTargetRef(fork);
    ParallelGateway join=new ParallelGateway();
    join.setId("parallel_gateway_join" + gatewayIndex.getAndIncrement());
    for (    FlowElement taskInBlock : taskBlock) {
      createSequenceFlow(process,flowIndex,fork,taskInBlock);
      createSequenceFlow(process,flowIndex,taskInBlock,join);
      process.getFlowElement().add(taskInBlock);
    }
    process.getFlowElement().add(join);
    lastFlowElementOfBlockStack.add(join);
  }
}
 

Example 61

From project aws-tasks, under directory /src/it/java/datameer/awstasks/ssh/.

Source file: SshIntegTest.java

  15 
vote

private void countFiles(File folder,AtomicInteger count){
  File[] files=folder.listFiles();
  for (  File file : files) {
    if (file.isDirectory()) {
      countFiles(file,count);
    }
 else {
      count.incrementAndGet();
    }
  }
}
 

Example 62

From project enterprise, under directory /consistency-check/src/main/java/org/neo4j/consistency/report/.

Source file: ConsistencySummaryStatistics.java

  15 
vote

@Override public String toString(){
  StringBuilder result=new StringBuilder(getClass().getSimpleName()).append('{');
  result.append("\n\tNumber of errors: ").append(errorCount);
  result.append("\n\tNumber of warnings: ").append(warningCount);
  for (  Map.Entry<RecordType,AtomicInteger> entry : inconsistentRecordCount.entrySet()) {
    if (entry.getValue().get() != 0) {
      result.append("\n\tNumber of inconsistent ").append(entry.getKey()).append(" records: ").append(entry.getValue());
    }
  }
  return result.append("\n}").toString();
}
 

Example 63

From project heritrix3, under directory /commons/src/main/java/org/archive/io/arc/.

Source file: ARCReader.java

  15 
vote

public void dump(final boolean compress) throws IOException, java.text.ParseException {
  setDigest(false);
  boolean firstRecord=true;
  ARCWriter writer=null;
  for (Iterator<ArchiveRecord> ii=iterator(); ii.hasNext(); ) {
    ARCRecord r=(ARCRecord)ii.next();
    ARCRecordMetaData meta=r.getMetaData();
    if (firstRecord) {
      firstRecord=false;
      ByteArrayOutputStream baos=new ByteArrayOutputStream(r.available());
      while (r.available() > 0) {
        baos.write(r.read());
      }
      List<String> listOfMetadata=new ArrayList<String>();
      listOfMetadata.add(baos.toString(WriterPoolMember.UTF8));
      List<File> outDirs=new ArrayList<File>();
      WriterPoolSettingsData settings=new WriterPoolSettingsData("","",-1L,compress,outDirs,listOfMetadata);
      writer=new ARCWriter(new AtomicInteger(),System.out,new File(meta.getArc()),settings);
      continue;
    }
    writer.write(meta.getUrl(),meta.getMimetype(),meta.getIp(),ArchiveUtils.parse14DigitDate(meta.getDate()).getTime(),(int)meta.getLength(),r);
  }
}