Java Code Examples for java.util.Queue

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 Jetwick, under directory /src/test/java/de/jetwick/tw/.

Source file: TweetProducerViaSearchTest.java

  32 
vote

@Test public void testFIFO(){
  Queue q=new LinkedBlockingDeque();
  q.add("test");
  q.add("pest");
  assertEquals("test",q.poll());
  q=new LinkedBlockingQueue();
  q.add("test");
  q.add("pest");
  assertEquals("test",q.poll());
  Stack v=new Stack();
  v.add("test");
  v.add("pest");
  assertEquals("pest",v.pop());
}
 

Example 2

From project activiti-explorer, under directory /src/main/java/org/activiti/explorer/cache/.

Source file: RadixTreeImpl.java

  29 
vote

private void getNodes(RadixTreeNode<T> parent,ArrayList<T> keys,int limit){
  Queue<RadixTreeNode<T>> queue=new LinkedList<RadixTreeNode<T>>();
  queue.addAll(parent.getChildern());
  while (!queue.isEmpty()) {
    RadixTreeNode<T> node=queue.remove();
    if (node.isReal() == true) {
      keys.add(node.getValue());
    }
    if (keys.size() == limit) {
      break;
    }
    queue.addAll(node.getChildern());
  }
}
 

Example 3

From project AeminiumRuntime, under directory /src/aeminium/runtime/implementations/implicitworkstealing/scheduler/stealing/.

Source file: Revenge.java

  29 
vote

@Override public final void init(WorkStealingThread[] threads,Queue<ImplicitTask> submissionQueue){
  this.threads=threads;
  this.thiefes=new WorkStealingThread[threads.length];
  this.parkedThreads=new ConcurrentLinkedQueue<WorkStealingThread>();
  this.submissionQueue=submissionQueue;
}
 

Example 4

From project aether-core, under directory /aether-test-util/src/main/java/org/eclipse/aether/internal/test/util/connector/suite/.

Source file: TransferEventTester.java

  29 
vote

private static void checkEvents(Queue<TransferEvent> events,long expectedBytes){
  TransferEvent currentEvent=events.poll();
  String msg="initiate event is missing";
  assertNotNull(msg,currentEvent);
  assertEquals(msg,INITIATED,currentEvent.getType());
  checkProperties(currentEvent);
  TransferResource expectedResource=currentEvent.getResource();
  currentEvent=events.poll();
  msg="start event is missing";
  assertNotNull(msg,currentEvent);
  assertEquals(msg,TransferEvent.EventType.STARTED,currentEvent.getType());
  assertEquals("bad content length",expectedBytes,currentEvent.getResource().getContentLength());
  checkProperties(currentEvent);
  assertResourceEquals(expectedResource,currentEvent.getResource());
  EventType progressed=TransferEvent.EventType.PROGRESSED;
  EventType succeeded=TransferEvent.EventType.SUCCEEDED;
  TransferEvent succeedEvent=null;
  int dataLength=0;
  long transferredBytes=0;
  while ((currentEvent=events.poll()) != null) {
    EventType currentType=currentEvent.getType();
    assertResourceEquals(expectedResource,currentEvent.getResource());
    if (succeeded.equals(currentType)) {
      succeedEvent=currentEvent;
      checkProperties(currentEvent);
      break;
    }
 else {
      assertTrue("event is not 'succeeded' and not 'progressed'",progressed.equals(currentType));
      assertTrue("wrong order of progressed events, transferredSize got smaller, last = " + transferredBytes + ", current = "+ currentEvent.getTransferredBytes(),currentEvent.getTransferredBytes() >= transferredBytes);
      assertEquals("bad content length",expectedBytes,currentEvent.getResource().getContentLength());
      transferredBytes=currentEvent.getTransferredBytes();
      dataLength+=currentEvent.getDataBuffer().remaining();
      checkProperties(currentEvent);
    }
  }
  assertEquals("too many events left: " + events.toString(),0,events.size());
  assertEquals("progress events transferred bytes don't match: data length does not add up",expectedBytes,dataLength);
  assertEquals("succeed event transferred bytes don't match",expectedBytes,succeedEvent.getTransferredBytes());
}
 

Example 5

From project android-aac-enc, under directory /src/com/googlecode/mp4parser/authoring/builder/.

Source file: SyncSampleIntersectFinderImpl.java

  29 
vote

private static long[] getTimes(Movie m,Track track){
  long[] syncSamples=track.getSyncSamples();
  long[] syncSampleTimes=new long[syncSamples.length];
  Queue<TimeToSampleBox.Entry> timeQueue=new LinkedList<TimeToSampleBox.Entry>(track.getDecodingTimeEntries());
  int currentSample=1;
  long currentDuration=0;
  long currentDelta=0;
  int currentSyncSampleIndex=0;
  long left=0;
  long timeScale=1;
  for (  Track track1 : m.getTracks()) {
    if (track1.getTrackMetaData().getTimescale() != track.getTrackMetaData().getTimescale()) {
      timeScale=lcm(timeScale,track1.getTrackMetaData().getTimescale());
    }
  }
  while (currentSample <= syncSamples[syncSamples.length - 1]) {
    if (currentSample++ == syncSamples[currentSyncSampleIndex]) {
      syncSampleTimes[currentSyncSampleIndex++]=currentDuration * timeScale;
    }
    if (left-- == 0) {
      TimeToSampleBox.Entry entry=timeQueue.poll();
      left=entry.getCount();
      currentDelta=entry.getDelta();
    }
    currentDuration+=currentDelta;
  }
  return syncSampleTimes;
}
 

Example 6

From project android_8, under directory /src/com/google/gson/.

Source file: DefaultTypeAdapters.java

  29 
vote

@SuppressWarnings({"rawtypes"}) private static ParameterizedTypeHandlerMap<InstanceCreator<?>> createDefaultInstanceCreators(){
  ParameterizedTypeHandlerMap<InstanceCreator<?>> map=new ParameterizedTypeHandlerMap<InstanceCreator<?>>();
  DefaultConstructorAllocator allocator=new DefaultConstructorAllocator(50);
  map.registerForTypeHierarchy(Map.class,new DefaultConstructorCreator<Map>(LinkedHashMap.class,allocator));
  DefaultConstructorCreator<List> listCreator=new DefaultConstructorCreator<List>(ArrayList.class,allocator);
  DefaultConstructorCreator<Queue> queueCreator=new DefaultConstructorCreator<Queue>(LinkedList.class,allocator);
  DefaultConstructorCreator<Set> setCreator=new DefaultConstructorCreator<Set>(HashSet.class,allocator);
  DefaultConstructorCreator<SortedSet> sortedSetCreator=new DefaultConstructorCreator<SortedSet>(TreeSet.class,allocator);
  map.registerForTypeHierarchy(Collection.class,listCreator);
  map.registerForTypeHierarchy(Queue.class,queueCreator);
  map.registerForTypeHierarchy(Set.class,setCreator);
  map.registerForTypeHierarchy(SortedSet.class,sortedSetCreator);
  map.makeUnmodifiable();
  return map;
}
 

Example 7

From project annotare2, under directory /app/magetab/src/test/java/uk/ac/ebi/fg/annotare2/magetab/base/operation/.

Source file: MoveColumnOperationTest.java

  29 
vote

@Test public void testHandleOperation(){
  final Queue<Operation> operations=new ArrayDeque<Operation>();
  Table table=new Table();
  table.addRow(asList(ROW_TAG_1.getName(),"","1"));
  table.addRow(asList(ROW_TAG_2.getName(),"2",""));
  RowSet rowSet=new RowSet(ROW_TAG_1,ROW_TAG_2);
  rowSet.addAll(table);
  table.addChangeListener(new ChangeListener(){
    @Override public void onChange(    Operation operation){
      operations.offer(operation);
    }
  }
);
  rowSet.moveColumn(0,1);
  assertFalse(operations.isEmpty());
  Operation op=operations.poll();
  assertTrue(op instanceof MoveColumnOperation);
  MoveColumnOperation moveOp=(MoveColumnOperation)op;
  assertEquals(1,moveOp.getFromIndex());
  assertEquals(2,moveOp.getToIndex());
  assertEquals(2,moveOp.getRowIndices().size());
  assertTrue(moveOp.getRowIndices().contains(0));
  assertTrue(moveOp.getRowIndices().contains(1));
}
 

Example 8

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

Source file: FixedSizeQueueSet.java

  29 
vote

/** 
 * Creates a  {@link FixedSizeQueueSet} with the given {@link Queue}, {@link Set} and max size.<p>NOTE: The  {@link FixedSizeQueueSet} does not check if theinitial state of the given arguments is correct.
 */
public FixedSizeQueueSet(Queue<E> q,Set<E> s,int maxSize){
  super(q,s);
  if (maxSize < 0 && maxSize != -1) {
    throw new IllegalArgumentException("maxSize=" + maxSize);
  }
  this.maxSize=maxSize;
}
 

Example 9

From project arquillian-graphene, under directory /graphene-selenium/graphene-selenium-impl/src/main/java/org/jboss/arquillian/ajocado/framework/internal/.

Source file: WaitingProxy.java

  29 
vote

private static Class<?>[] getInterfaces(Class<?> waitingClass){
  Set<Class<?>> set=new HashSet<Class<?>>();
  Queue<Class<?>> queue=new LinkedList<Class<?>>();
  List<Class<?>> interfaces=new LinkedList<Class<?>>();
  queue.add(waitingClass);
  while (!queue.isEmpty()) {
    Class<?> clazz=queue.poll();
    if (set.contains(clazz)) {
      continue;
    }
    set.add(clazz);
    queue.addAll(Arrays.asList(clazz.getInterfaces()));
    if (clazz.getSuperclass() != null) {
      queue.add(clazz.getSuperclass());
    }
  }
  for (  Class<?> clazz : set) {
    if (clazz.isInterface()) {
      interfaces.add(clazz);
    }
  }
  return interfaces.toArray(new Class<?>[interfaces.size()]);
}
 

Example 10

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

Source file: CollectionRecipe.java

  29 
vote

public static Class getCollection(Class type){
  if (ReflectionUtils.hasDefaultConstructor(type)) {
    return type;
  }
 else   if (SortedSet.class.isAssignableFrom(type)) {
    return TreeSet.class;
  }
 else   if (Set.class.isAssignableFrom(type)) {
    return LinkedHashSet.class;
  }
 else   if (List.class.isAssignableFrom(type)) {
    return ArrayList.class;
  }
 else   if (Queue.class.isAssignableFrom(type)) {
    return LinkedList.class;
  }
 else {
    return ArrayList.class;
  }
}
 

Example 11

From project brut.apktool.smali, under directory /util/src/main/java/ds/tree/.

Source file: RadixTreeImpl.java

  29 
vote

private void getNodes(RadixTreeNode<T> parent,ArrayList<T> keys,int limit){
  Queue<RadixTreeNode<T>> queue=new LinkedList<RadixTreeNode<T>>();
  queue.addAll(parent.getChildern());
  while (!queue.isEmpty()) {
    RadixTreeNode<T> node=queue.remove();
    if (node.isReal() == true) {
      keys.add(node.getValue());
    }
    if (keys.size() == limit) {
      break;
    }
    queue.addAll(node.getChildern());
  }
}
 

Example 12

From project C-Cat, under directory /core/src/main/java/gov/llnl/ontology/mapreduce/stats/.

Source file: WordOccurrenceCountMR.java

  29 
vote

/** 
 * {@inheritDoc}
 */
public void map(ImmutableBytesWritable key,Result row,Context context) throws IOException, InterruptedException {
  List<Iterator<Annotation>> tokenIters=Lists.newArrayList();
  for (  Sentence sentence : table.sentences(row))   tokenIters.add(sentence.iterator());
  Iterator<Annotation> tokens=new CombinedIterator<Annotation>(tokenIters);
  Map<String,StringCounter> wocCounts=Maps.newHashMap();
  Queue<Annotation> prev=new ArrayDeque<Annotation>();
  Queue<Annotation> next=new ArrayDeque<Annotation>();
  while (tokens.hasNext() && next.size() < windowSize)   next.offer(tokens.next());
  while (!next.isEmpty()) {
    Annotation focus=next.remove();
    if (tokens.hasNext())     next.offer(tokens.next());
    String focusWord=AnnotationUtil.word(focus);
    if (focusWord == null)     continue;
    focusWord=focusWord.toLowerCase();
    if (wordList.isEmpty() || wordList.contains(focusWord)) {
      context.getCounter(MR_NAME,"Focus Word").increment(1);
      StringCounter counts=wocCounts.get(focusWord);
      if (counts == null) {
        counts=new StringCounter();
        wocCounts.put(focusWord,counts);
      }
      StringCounter occurrences=wocCounts.get(" ");
      if (occurrences == null) {
        occurrences=new StringCounter();
        wocCounts.put(" ",occurrences);
      }
      occurrences.count(focusWord,prev.size() + next.size());
      addContextTerms(counts,prev,-1 * prev.size());
      addContextTerms(counts,next,1);
    }
    prev.offer(focus);
    if (prev.size() > windowSize)     prev.remove();
  }
  WordCountSumReducer.emitCounts(wocCounts,context);
  context.getCounter(MR_NAME,"Documents").increment(1);
}
 

Example 13

From project Chess_1, under directory /src/main/java/jcpi/standardio/.

Source file: AbstractStandardIoProtocol.java

  29 
vote

/** 
 * Creates a new AbstractStandardIoProtocol.
 * @param writer the standard output.
 * @param queue the engine command queue.
 */
public AbstractStandardIoProtocol(PrintStream writer,Queue<IEngineCommand> queue){
  if (writer == null)   throw new IllegalArgumentException();
  if (queue == null)   throw new IllegalArgumentException();
  this.writer=writer;
  this.queue=queue;
}
 

Example 14

From project cidb, under directory /solr-access-service/src/main/java/edu/toronto/cs/cidb/solr/.

Source file: SolrScriptService.java

  29 
vote

/** 
 * Get the HPO IDs of the specified phenotype and all its ancestors.
 * @param id the HPO identifier to search for, in the {@code HP:1234567} format
 * @return the full set of ancestors-or-self IDs, or an empty set if the requested ID was not found in the index
 */
public Set<String> getAllAncestorsAndSelfIDs(final String id){
  Set<String> results=new HashSet<String>();
  Queue<SolrDocument> nodes=new LinkedList<SolrDocument>();
  SolrDocument crt=this.get(id);
  if (crt == null) {
    return results;
  }
  nodes.add(crt);
  while (!nodes.isEmpty()) {
    crt=nodes.poll();
    results.add(String.valueOf(crt.get(ID_FIELD_NAME)));
    @SuppressWarnings("unchecked") List<String> parents=(List<String>)crt.get("is_a");
    if (parents == null) {
      continue;
    }
    for (    String pid : parents) {
      nodes.add(this.get(StringUtils.substringBefore(pid," ")));
    }
  }
  return results;
}
 

Example 15

From project CircDesigNA, under directory /src/circdesigna/util/.

Source file: NupackReader.java

  29 
vote

private String toCDNAMolecule(String molName,String structure,String domains,DomainDefinitions dsd){
  structure=structure.trim();
  domains=domains.trim();
  StringBuffer cdna=new StringBuffer();
  Queue<String> structureTerms=new LinkedList();
  Queue<String> domainTerms=new LinkedList();
{
    Scanner in=new Scanner(structure);
    while (in.hasNext()) {
      structureTerms.add(in.next());
    }
    in=new Scanner(domains);
    while (in.hasNext()) {
      domainTerms.add(in.next());
    }
  }
  while (!structureTerms.isEmpty()) {
    toCDNAMolecule_(structureTerms,domainTerms,dsd,cdna);
  }
  if (!domainTerms.isEmpty()) {
    throw new RuntimeException("Invalid DU+ notation: ");
  }
  return molName + " [" + cdna.toString()+ "}";
}
 

Example 16

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

Source file: TimeExtensionsTest.java

  29 
vote

@Test public void testTimeStamp() throws Exception {
  bayeux.addExtension(new TimestampExtension());
  final BayeuxClient client=newBayeuxClient();
  client.addExtension(new TimestampClientExtension());
  final Queue<Message> messages=new ConcurrentLinkedQueue<>();
  client.getChannel(Channel.META_HANDSHAKE).addListener(new ClientSessionChannel.MessageListener(){
    public void onMessage(    ClientSessionChannel channel,    Message message){
      messages.add(message);
    }
  }
);
  client.handshake();
  Assert.assertTrue(client.waitFor(5000,BayeuxClient.State.CONNECTED));
  Assert.assertTrue(client.disconnect(5000));
  Assert.assertTrue(messages.size() > 0);
  for (  Message message : messages)   Assert.assertTrue(message.get(Message.TIMESTAMP_FIELD) != null);
  disconnectBayeuxClient(client);
}
 

Example 17

From project Core_2, under directory /shell/src/main/java/org/jboss/forge/shell/command/fshparser/.

Source file: LogicalStatement.java

  29 
vote

public Queue<String> getTokens(final FSHRuntime runtime){
  Queue<String> newQueue=new LinkedList<String>();
  Node n=nest;
  do {
    if (n instanceof TokenNode) {
      newQueue.add(((TokenNode)n).getValue());
    }
 else     if (n instanceof LogicalStatement) {
      newQueue.add("(");
      newQueue.addAll(((LogicalStatement)n).getTokens(runtime));
      newQueue.add(")");
    }
 else {
      throw new RuntimeException("uh-oh");
    }
  }
 while ((n=n.next) != null);
  return newQueue;
}
 

Example 18

From project core_4, under directory /impl/src/main/java/org/richfaces/application/push/impl/.

Source file: SessionImpl.java

  29 
vote

public void clearBroadcastedMessages(long sequenceNumber){
  Queue<MessageData> queue=messagesQueue;
  while (true) {
    MessageData message=queue.peek();
    if (message == null || sequenceNumber < message.getSequenceNumber()) {
      break;
    }
    queue.remove();
  }
}
 

Example 19

From project crammer, under directory /src/main/java/uk/ac/ebi/ena/sra/cram/bam/.

Source file: BAMFileQueryQueues.java

  29 
vote

public void stop(Queue<SAMRecord> queue){
  SAMRecordIteratorJob job=queues.get(queue);
  if (job != null) {
    job.abort();
    queues.remove(queue);
  }
}
 

Example 20

From project crest, under directory /core/src/test/java/org/codegist/crest/serializer/jaxb/.

Source file: PooledJaxbText.java

  29 
vote

@Test(expected=CRestException.class) public void shouldTryToBorrowForUnmarshallAndFailWithTimeout() throws Exception {
  Queue<Jaxb> queue=getQueue();
  assertQueueState(queue);
  queue.poll();
  queue.poll();
  toTest.unmarshal(null,null,null);
}
 

Example 21

From project engine, under directory /main/com/midtro/platform/.

Source file: State.java

  29 
vote

/** 
 * Runs the input events that have been queued since the last frame.
 * @param queue The queue of input events to handle.
 * @param app The application.
 */
public final void handleInput(Queue<InputEvent> queue,Application app){
  entry:   while (!queue.isEmpty()) {
    final InputEvent event=queue.poll();
    if (event instanceof MouseEvent) {
      final MouseEvent mouseEvent=(MouseEvent)event;
      for (      final MouseInjector injector : app.getMouseInjectors()) {
        if (injector.handleMouseEvent(mouseEvent)) {
          continue entry;
        }
      }
      handleMouseEvent(mouseEvent,app);
    }
    if (event instanceof KeyEvent) {
      final KeyEvent keyEvent=(KeyEvent)event;
      for (      final KeyInjector injector : app.getKeyInjectors()) {
        if (injector.handleKeyEvent(keyEvent)) {
          continue entry;
        }
      }
      handleKeyEvent(keyEvent,app);
    }
  }
}
 

Example 22

From project eoit, under directory /EOITCommons/src/main/java/fr/eoit/xml/.

Source file: AbstractDefaultXmlParser.java

  29 
vote

/** 
 * @param parser
 * @param path an XPath query
 * @return
 * @throws XmlPullParserException
 * @throws IOException
 */
public static boolean accessPath(XmlPullParser parser,String path) throws XmlPullParserException, IOException {
  String[] pathElements=path.split("/");
  Queue<String> pathQueue=new ArrayBlockingQueue<String>(pathElements.length);
  for (  String pathElement : pathElements) {
    pathQueue.offer(pathElement);
  }
  return accessPath(parser,pathQueue);
}
 

Example 23

From project ExperienceMod, under directory /ExperienceMod/src/com/comphenix/xp/parser/primitives/.

Source file: BooleanParser.java

  29 
vote

/** 
 * Transforms and returns the first non-null element from the left into an object. That element is removed.
 * @param tokens - queue of items.
 * @return List containing the removed object, OR an empty list if no object was removed.
 */
public List<Boolean> parseAny(Queue<String> tokens) throws ParsingException {
  String toRemove=null;
  List<Boolean> result=null;
  for (  String current : tokens) {
    result=parse(current);
    if (result != null) {
      toRemove=current;
      break;
    }
  }
  if (result != null) {
    tokens.remove(toRemove);
    if (result.size() == 1)     return result;
 else     return emptyList;
  }
 else {
    return emptyList;
  }
}
 

Example 24

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

Source file: DeviceManagerImpl.java

  29 
vote

/** 
 * Send update notifications to listeners
 * @param updates the updates to process.
 */
protected void processUpdates(Queue<DeviceUpdate> updates){
  if (updates == null)   return;
  DeviceUpdate update=null;
  while (null != (update=updates.poll())) {
    if (logger.isTraceEnabled()) {
      logger.trace("Dispatching device update: {}",update);
    }
    for (    IDeviceListener listener : deviceListeners) {
switch (update.change) {
case ADD:
        listener.deviceAdded(update.device);
      break;
case DELETE:
    listener.deviceRemoved(update.device);
  break;
case CHANGE:
for (DeviceField field : update.fieldsChanged) {
switch (field) {
case IPV4:
    listener.deviceIPV4AddrChanged(update.device);
  break;
case SWITCH:
case PORT:
break;
case VLAN:
listener.deviceVlanChanged(update.device);
break;
default :
logger.debug("Unknown device field changed {}",update.fieldsChanged.toString());
break;
}
}
break;
}
}
}
}
 

Example 25

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

Source file: TestTagger.java

  29 
vote

/** 
 * This checks to make sure that tags are always get lexographically larger over time. A ProcessTagger actually uses thread id # as part of its sort and this verifies that it is the least significant. A Roller can call the new tag method in either of its threads, so we need to take this into account.
 */
@Test public void testThreadedTaggerNameMonotonic() throws InterruptedException {
  final Tagger t=new ProcessTagger();
  final Queue<String> tags=new ArrayBlockingQueue<String>(1000);
  final Object lock=new Object();
  final CountDownLatch start=new CountDownLatch(10);
  final CountDownLatch done=new CountDownLatch(10);
class TagThread extends Thread {
    public void run(){
      start.countDown();
      try {
        start.await();
        while (true) {
synchronized (lock) {
            String s=t.newTag();
            boolean accepted=tags.offer(s);
            if (!accepted) {
              done.countDown();
              return;
            }
            LOG.info("added tag: {}",s);
          }
        }
      }
 catch (      InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
  TagThread[] thds=new TagThread[10];
  for (int i=0; i < thds.length; i++) {
    thds[i]=new TagThread();
    thds[i].start();
  }
  done.await();
  String[] aTags=tags.toArray(new String[0]);
  for (int i=1; i < aTags.length; i++) {
    assertTrue(aTags[i - 1].compareTo(aTags[i]) < 0);
  }
}
 

Example 26

From project galaxy, under directory /src/co/paralleluniverse/galaxy/core/.

Source file: Cache.java

  29 
vote

@Override public void receive(Message message){
  if (recursive.get() != Boolean.TRUE) {
    recursive.set(Boolean.TRUE);
    try {
      LOG.debug("Received: {}",message);
      receive1(message);
      receiveShortCircuit();
    }
  finally {
      recursive.remove();
    }
  }
 else {
    LOG.debug("Received short-circuit: {}",message);
    Queue<Message> ms=shortCircuitMessage.get();
    if (ms == null) {
      ms=new ArrayDeque<Message>();
      shortCircuitMessage.set(ms);
    }
    ms.add(message);
  }
}
 

Example 27

From project gecko, under directory /src/main/java/com/taobao/gecko/core/buffer/.

Source file: CachedBufferAllocator.java

  29 
vote

/** 
 * Creates a new instance.
 * @param maxPoolSize the maximum number of buffers with the same capacity per thread. <tt>0</tt> disables this limitation.
 * @param maxCachedBufferSize the maximum capacity of a cached buffer. A buffer whose capacity is bigger than this value is not pooled. <tt>0</tt> disables this limitation.
 */
public CachedBufferAllocator(final int maxPoolSize,final int maxCachedBufferSize){
  if (maxPoolSize < 0) {
    throw new IllegalArgumentException("maxPoolSize: " + maxPoolSize);
  }
  if (maxCachedBufferSize < 0) {
    throw new IllegalArgumentException("maxCachedBufferSize: " + maxCachedBufferSize);
  }
  this.maxPoolSize=maxPoolSize;
  this.maxCachedBufferSize=maxCachedBufferSize;
  this.heapBuffers=new ThreadLocal<Map<Integer,Queue<CachedBuffer>>>(){
    @Override protected Map<Integer,Queue<CachedBuffer>> initialValue(){
      return CachedBufferAllocator.this.newPoolMap();
    }
  }
;
  this.directBuffers=new ThreadLocal<Map<Integer,Queue<CachedBuffer>>>(){
    @Override protected Map<Integer,Queue<CachedBuffer>> initialValue(){
      return CachedBufferAllocator.this.newPoolMap();
    }
  }
;
}
 

Example 28

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

Source file: BlueprintEditorRegistrar.java

  29 
vote

public void registerCustomEditors(PropertyEditorRegistry registry){
  registry.registerCustomEditor(Date.class,new DateEditor());
  registry.registerCustomEditor(Stack.class,new BlueprintCustomCollectionEditor(Stack.class));
  registry.registerCustomEditor(Vector.class,new BlueprintCustomCollectionEditor(Vector.class));
  registry.registerCustomEditor(Collection.class,new BlueprintCustomCollectionEditor(Collection.class));
  registry.registerCustomEditor(Set.class,new BlueprintCustomCollectionEditor(Set.class));
  registry.registerCustomEditor(SortedSet.class,new BlueprintCustomCollectionEditor(SortedSet.class));
  registry.registerCustomEditor(List.class,new BlueprintCustomCollectionEditor(List.class));
  registry.registerCustomEditor(SortedMap.class,new CustomMapEditor(SortedMap.class));
  registry.registerCustomEditor(HashSet.class,new BlueprintCustomCollectionEditor(HashSet.class));
  registry.registerCustomEditor(LinkedHashSet.class,new BlueprintCustomCollectionEditor(LinkedHashSet.class));
  registry.registerCustomEditor(TreeSet.class,new BlueprintCustomCollectionEditor(TreeSet.class));
  registry.registerCustomEditor(ArrayList.class,new BlueprintCustomCollectionEditor(ArrayList.class));
  registry.registerCustomEditor(LinkedList.class,new BlueprintCustomCollectionEditor(LinkedList.class));
  registry.registerCustomEditor(HashMap.class,new CustomMapEditor(HashMap.class));
  registry.registerCustomEditor(LinkedHashMap.class,new CustomMapEditor(LinkedHashMap.class));
  registry.registerCustomEditor(Hashtable.class,new CustomMapEditor(Hashtable.class));
  registry.registerCustomEditor(TreeMap.class,new CustomMapEditor(TreeMap.class));
  registry.registerCustomEditor(Properties.class,new PropertiesEditor());
  registry.registerCustomEditor(ConcurrentMap.class,new CustomMapEditor(ConcurrentHashMap.class));
  registry.registerCustomEditor(ConcurrentHashMap.class,new CustomMapEditor(ConcurrentHashMap.class));
  registry.registerCustomEditor(Queue.class,new BlueprintCustomCollectionEditor(LinkedList.class));
  registry.registerCustomEditor(Dictionary.class,new CustomMapEditor(Hashtable.class));
}
 

Example 29

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

Source file: DefaultTypeAdapters.java

  29 
vote

@SuppressWarnings("unchecked") private static ParameterizedTypeHandlerMap<InstanceCreator<?>> createDefaultInstanceCreators(){
  ParameterizedTypeHandlerMap<InstanceCreator<?>> map=new ParameterizedTypeHandlerMap<InstanceCreator<?>>();
  DefaultConstructorAllocator allocator=new DefaultConstructorAllocator(50);
  map.registerForTypeHierarchy(Map.class,new DefaultConstructorCreator<Map>(LinkedHashMap.class,allocator),true);
  DefaultConstructorCreator<List> listCreator=new DefaultConstructorCreator<List>(ArrayList.class,allocator);
  DefaultConstructorCreator<Queue> queueCreator=new DefaultConstructorCreator<Queue>(LinkedList.class,allocator);
  DefaultConstructorCreator<Set> setCreator=new DefaultConstructorCreator<Set>(HashSet.class,allocator);
  DefaultConstructorCreator<SortedSet> sortedSetCreator=new DefaultConstructorCreator<SortedSet>(TreeSet.class,allocator);
  map.registerForTypeHierarchy(Collection.class,listCreator,true);
  map.registerForTypeHierarchy(Queue.class,queueCreator,true);
  map.registerForTypeHierarchy(Set.class,setCreator,true);
  map.registerForTypeHierarchy(SortedSet.class,sortedSetCreator,true);
  map.makeUnmodifiable();
  return map;
}
 

Example 30

From project grouperfish, under directory /tools/display/src/main/java/com/mozilla/grouperfish/mahout/clustering/display/lda/.

Source file: DisplayLDABase.java

  29 
vote

private static void enqueue(Queue<Pair<Double,String>> q,String word,double score,int numWordsToPrint){
  if (q.size() >= numWordsToPrint && score > q.peek().getFirst()) {
    q.poll();
  }
  if (q.size() < numWordsToPrint) {
    q.add(new Pair<Double,String>(score,word));
  }
}
 

Example 31

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

Source file: DefaultTypeAdapters.java

  29 
vote

@SuppressWarnings("unchecked") private static ParameterizedTypeHandlerMap<InstanceCreator<?>> createDefaultInstanceCreators(){
  ParameterizedTypeHandlerMap<InstanceCreator<?>> map=new ParameterizedTypeHandlerMap<InstanceCreator<?>>();
  DefaultConstructorAllocator allocator=new DefaultConstructorAllocator(50);
  map.registerForTypeHierarchy(Map.class,new DefaultConstructorCreator<Map>(LinkedHashMap.class,allocator),true);
  DefaultConstructorCreator<List> listCreator=new DefaultConstructorCreator<List>(ArrayList.class,allocator);
  DefaultConstructorCreator<Queue> queueCreator=new DefaultConstructorCreator<Queue>(LinkedList.class,allocator);
  DefaultConstructorCreator<Set> setCreator=new DefaultConstructorCreator<Set>(HashSet.class,allocator);
  DefaultConstructorCreator<SortedSet> sortedSetCreator=new DefaultConstructorCreator<SortedSet>(TreeSet.class,allocator);
  map.registerForTypeHierarchy(Collection.class,listCreator,true);
  map.registerForTypeHierarchy(Queue.class,queueCreator,true);
  map.registerForTypeHierarchy(Set.class,setCreator,true);
  map.registerForTypeHierarchy(SortedSet.class,sortedSetCreator,true);
  map.makeUnmodifiable();
  return map;
}
 

Example 32

From project GTNA, under directory /src/gtna/metrics/basic/.

Source file: ShortestPaths.java

  29 
vote

private long[] computeSPL(Node[] nodes,Node start,long[] SPL){
  Queue<Integer> queue=new LinkedList<Integer>();
  int[] spl=Util.initIntArray(nodes.length,-1);
  long sum=0;
  int found=0;
  queue.add(start.getIndex());
  spl[start.getIndex()]=0;
  while (!queue.isEmpty()) {
    Node current=nodes[queue.poll()];
    for (    int outIndex : current.getOutgoingEdges()) {
      if (spl[outIndex] != -1) {
        continue;
      }
      spl[outIndex]=spl[current.getIndex()] + 1;
      queue.add(outIndex);
      found++;
      sum+=spl[outIndex];
      SPL=this.inc(SPL,spl[outIndex]);
    }
  }
  this.localCharacteristicPathLength[start.getIndex()]=(double)sum / (double)found;
  return SPL;
}
 

Example 33

From project hbase-dsl, under directory /src/main/java/com/nearinfinity/hbase/dsl/.

Source file: HBase.java

  29 
vote

public void flush(byte[] tableName){
  LOG.debug("flush [" + tableName + "]");
  Queue<Put> puts=getPuts(tableName);
  if (puts != null) {
    flushPuts(tableName,puts);
  }
  Queue<Delete> deletes=getDeletes(tableName);
  if (deletes != null) {
    flushDeletes(tableName,deletes);
  }
}
 

Example 34

From project heritrix3, under directory /engine/src/main/java/org/archive/crawler/frontier/.

Source file: BdbFrontier.java

  29 
vote

@Override protected void initOtherQueues() throws DatabaseException {
  boolean recycle=(recoveryCheckpoint != null);
  readyClassQueues=new LinkedBlockingQueue<String>();
  inactiveQueuesByPrecedence=new ConcurrentSkipListMap<Integer,Queue<String>>();
  retiredQueues=bdb.getStoredQueue("retiredQueues",String.class,recycle);
  snoozedClassQueues=new DelayQueue<DelayedWorkQueue>();
  snoozedOverflow=bdb.getStoredMap("snoozedOverflow",Long.class,DelayedWorkQueue.class,true,false);
  this.futureUris=bdb.getStoredMap("futureUris",Long.class,CrawlURI.class,true,recoveryCheckpoint != null);
  this.pendingUris=createMultipleWorkQueues();
}
 

Example 35

From project hs4j, under directory /src/main/java/com/google/code/hs4j/network/buffer/.

Source file: CachedBufferAllocator.java

  29 
vote

/** 
 * Creates a new instance.
 * @param maxPoolSize the maximum number of buffers with the same capacity per thread. <tt>0</tt> disables this limitation.
 * @param maxCachedBufferSize the maximum capacity of a cached buffer. A buffer whose capacity is bigger than this value is not pooled. <tt>0</tt> disables this limitation.
 */
public CachedBufferAllocator(int maxPoolSize,int maxCachedBufferSize){
  if (maxPoolSize < 0) {
    throw new IllegalArgumentException("maxPoolSize: " + maxPoolSize);
  }
  if (maxCachedBufferSize < 0) {
    throw new IllegalArgumentException("maxCachedBufferSize: " + maxCachedBufferSize);
  }
  this.maxPoolSize=maxPoolSize;
  this.maxCachedBufferSize=maxCachedBufferSize;
  this.heapBuffers=new ThreadLocal<Map<Integer,Queue<CachedBuffer>>>(){
    @Override protected Map<Integer,Queue<CachedBuffer>> initialValue(){
      return newPoolMap();
    }
  }
;
  this.directBuffers=new ThreadLocal<Map<Integer,Queue<CachedBuffer>>>(){
    @Override protected Map<Integer,Queue<CachedBuffer>> initialValue(){
      return newPoolMap();
    }
  }
;
}
 

Example 36

From project httpClient, under directory /fluent-hc/src/examples/org/apache/http/client/fluent/.

Source file: FluentAsync.java

  29 
vote

public static void main(String[] args) throws Exception {
  ExecutorService threadpool=Executors.newFixedThreadPool(2);
  Async async=Async.newInstance().use(threadpool);
  Request[] requests=new Request[]{Request.Get("http://www.google.com/"),Request.Get("http://www.yahoo.com/"),Request.Get("http://www.apache.com/"),Request.Get("http://www.apple.com/")};
  Queue<Future<Content>> queue=new LinkedList<Future<Content>>();
  for (  final Request request : requests) {
    Future<Content> future=async.execute(request,new FutureCallback<Content>(){
      public void failed(      final Exception ex){
        System.out.println(ex.getMessage() + ": " + request);
      }
      public void completed(      final Content content){
        System.out.println("Request completed: " + request);
      }
      public void cancelled(){
      }
    }
);
    queue.add(future);
  }
  while (!queue.isEmpty()) {
    Future<Content> future=queue.remove();
    try {
      future.get();
    }
 catch (    ExecutionException ex) {
    }
  }
  System.out.println("Done");
  threadpool.shutdown();
}
 

Example 37

From project httpcore, under directory /httpcore-nio/src/test/java/org/apache/http/nio/integration/.

Source file: RequestExecutionHandler.java

  29 
vote

public HttpRequest submitRequest(final HttpContext context){
  @SuppressWarnings("unchecked") Queue<Job> queue=(Queue<Job>)context.getAttribute("queue");
  if (queue == null) {
    throw new IllegalStateException("Queue is null");
  }
  Job testjob=queue.poll();
  context.setAttribute("job",testjob);
  if (testjob != null) {
    return generateRequest(testjob);
  }
 else {
    return null;
  }
}
 

Example 38

From project jackrabbit-oak, under directory /oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/nodetype/.

Source file: NodeTypeImpl.java

  29 
vote

@Override public NodeType[] getSupertypes(){
  Collection<NodeType> types=new ArrayList<NodeType>();
  Set<String> added=new HashSet<String>();
  Queue<String> queue=new LinkedList<String>(Arrays.asList(getDeclaredSupertypeNames()));
  while (!queue.isEmpty()) {
    String name=queue.remove();
    if (added.add(name)) {
      try {
        NodeType type=manager.getNodeType(name);
        types.add(type);
        queue.addAll(Arrays.asList(type.getDeclaredSupertypeNames()));
      }
 catch (      RepositoryException e) {
        throw new IllegalStateException("Inconsistent node type: " + this,e);
      }
    }
  }
  return types.toArray(new NodeType[types.size()]);
}
 

Example 39

From project jagger, under directory /chassis/core/src/main/java/com/griddynamics/jagger/storage/fs/logging/.

Source file: BufferedLogReader.java

  29 
vote

private Queue<T> getBuffer(){
  if (buffer.isEmpty()) {
    update();
  }
  return buffer;
}
 

Example 40

From project jboss-marshalling, under directory /api/src/main/java/org/jboss/marshalling/cloner/.

Source file: SerializingCloner.java

  29 
vote

private StepObjectOutputStream(StepObjectOutput output,final Queue<Step> steps,final ClonerPutField clonerPutField,final Object subject) throws IOException {
  super(output);
  this.output=output;
  this.steps=steps;
  this.clonerPutField=clonerPutField;
  this.subject=subject;
}
 

Example 41

From project jboss-remoting, under directory /src/main/java/org/jboss/remoting3/.

Source file: LocalChannel.java

  29 
vote

public MessageOutputStream writeMessage() throws IOException {
  final LocalChannel otherSide=this.otherSide;
  final Queue<In> otherSideQueue=otherSide.messageQueue;
synchronized (otherSide.lock) {
    for (; ; ) {
      if (otherSide.closed) {
        throw new NotOpenException("Writes have been shut down");
      }
      final int size=otherSideQueue.size();
      if (size == queueLength) {
        try {
          otherSide.lock.wait();
        }
 catch (        InterruptedException e) {
          Thread.currentThread().interrupt();
          throw new InterruptedIOException();
        }
      }
 else {
        final Pipe pipe=new Pipe(bufferSize);
        In in=new In(pipe.getIn());
        if (size == 0) {
          final Receiver handler=otherSide.messageHandler;
          if (handler != null) {
            otherSide.messageHandler=null;
            otherSide.lock.notify();
            executeMessageTask(handler,in);
            return new Out(pipe.getOut(),in);
          }
        }
        otherSideQueue.add(in);
        otherSide.lock.notify();
        return new Out(pipe.getOut(),in);
      }
    }
  }
}
 

Example 42

From project jetty-project, under directory /example-async-rest-webapp/src/main/java/org/mortbay/demo/.

Source file: AbstractRestServlet.java

  29 
vote

protected String generateThumbs(Queue<Map<String,String>> results){
  StringBuilder thumbs=new StringBuilder();
  for (  Map<String,String> m : results) {
    if (!m.containsKey("GalleryURL"))     continue;
    thumbs.append("<a href=\"" + m.get("ViewItemURLForNaturalSearch") + "\">");
    thumbs.append("<img class='thumb' border='1px' height='25px'" + " src='" + m.get("GalleryURL") + "'"+ " title='"+ m.get("Title")+ "'"+ "/>");
    thumbs.append("</a>&nbsp;");
  }
  return thumbs.toString();
}
 

Example 43

From project jkernelmachines, under directory /src/fr/lip6/classifier/.

Source file: DoubleQNPKL.java

  29 
vote

/** 
 * calcul du gradient en chaque beta 
 */
private double[] computeGrad(GeneralizedDoubleGaussL2 kernel){
  debug.print(3,"++++++ g : ");
  final double grad[]=new double[dim];
  int nbcpu=Runtime.getRuntime().availableProcessors();
  ThreadPoolExecutor threadPool=new ThreadPoolExecutor(nbcpu,nbcpu,10,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());
  Queue<Future<?>> futures=new LinkedList<Future<?>>();
class GradRunnable implements Runnable {
    GeneralizedDoubleGaussL2 kernel;
    int i;
    public GradRunnable(    GeneralizedDoubleGaussL2 kernel,    int i){
      this.kernel=kernel;
      this.i=i;
    }
    public void run(){
      double[][] matrix=kernel.distanceMatrixUnthreaded(listOfExamples,i);
      double sum=0;
      for (int x=0; x < matrix.length; x++)       if (lambda_matrix[x] != null)       for (int y=0; y < matrix.length; y++)       sum+=matrix[x][y] * lambda_matrix[x][y];
      grad[i]+=0.5 * sum;
    }
  }
  for (int i=0; i < grad.length; i++) {
    Runnable r=new GradRunnable(kernel,i);
    futures.add(threadPool.submit(r));
  }
  while (!futures.isEmpty()) {
    try {
      futures.remove().get();
    }
 catch (    Exception e) {
      System.err.println("error with grad :");
      e.printStackTrace();
    }
  }
  threadPool.shutdownNow();
  for (int i=0; i < grad.length; i++)   if (Math.abs(grad[i]) < num_cleaning)   grad[i]=0.0;
  debug.println(3,Arrays.toString(grad));
  return grad;
}
 

Example 44

From project jobcreator-tool, under directory /src/main/java/dk/hlyh/hudson/tools/jobcreator/input/yaml/.

Source file: YamlLoader.java

  29 
vote

public Pipeline loadPipeline(){
  LogFacade.info("Loading pipeline definition using yaml version 1 format");
  dk.hlyh.hudson.tools.jobcreator.model.Group activeEnvironment=null;
  List<dk.hlyh.hudson.tools.jobcreator.model.Job> activeJobs=new ArrayList<dk.hlyh.hudson.tools.jobcreator.model.Job>();
  Deque<Map<String,Object>> loadedFiles=new ArrayDeque<Map<String,Object>>();
  Queue<File> filesToLoad=new ArrayDeque<File>();
  filesToLoad.add(arguments.getInput());
  while (!filesToLoad.isEmpty()) {
    File file=filesToLoad.poll();
    Map<String,Object> loadedFile=loadFile(file);
    loadedFiles.push(loadedFile);
    List<String> fileList=getListEntries(loadedFile,"imports","file");
    for (    String fileName : fileList) {
      filesToLoad.add(new File(fileName));
    }
  }
  while (!loadedFiles.isEmpty()) {
    Map<String,Object> loadedFile=loadedFiles.pop();
    parseFile(loadedFile);
    pipelineName=getPipelineName(loadedFile);
  }
  activeEnvironment=foundEnvironments.get(arguments.getEnvironment());
  if (activeEnvironment == null) {
    throw new ImportException("Could not find environment with name '" + arguments.getEnvironment() + "'");
  }
  return new Pipeline(pipelineName,activeEnvironment,activeJobs);
}
 

Example 45

From project jOOX, under directory /jOOX/src/test/java/org/joox/test/.

Source file: JOOXTest.java

  29 
vote

@Test public void testEachCallback(){
  final Queue<Integer> queue=new LinkedList<Integer>();
  queue.addAll(Arrays.asList(0));
  $.each(new Each(){
    @Override public void each(    Context context){
      assertEquals(context.element(),context.match());
      assertEquals(context.elementIndex(),context.matchIndex());
      assertEquals(context.elementSize(),context.matchSize());
      assertEquals((int)queue.poll(),context.matchIndex());
      assertEquals(1,context.matchSize());
      assertEquals("document",context.element().getTagName());
    }
  }
);
  assertTrue(queue.isEmpty());
  queue.addAll(Arrays.asList(0,1,2));
  $.children().each(new Each(){
    @Override public void each(    Context context){
      assertEquals(context.element(),context.match());
      assertEquals(context.elementIndex(),context.matchIndex());
      assertEquals(context.elementSize(),context.matchSize());
      assertEquals((int)queue.poll(),context.matchIndex());
      assertEquals(3,context.matchSize());
      assertEquals("library",context.element().getTagName());
    }
  }
);
  assertTrue(queue.isEmpty());
}
 

Example 46

From project joshua, under directory /src/joshua/tools/.

Source file: GrammarPacker.java

  29 
vote

/** 
 * Executes the packing.
 * @throws IOException
 */
public void pack() throws IOException {
  logger.info("Beginning exploration pass.");
  LineReader grammar_reader=null;
  LineReader alignment_reader=null;
  quantization.initialize();
  logger.info("Exploring: " + grammar);
  grammar_reader=new LineReader(grammar);
  explore(grammar_reader);
  logger.info("Exploration pass complete. Freezing vocabulary and " + "finalizing quantizers.");
  quantization.finalize();
  quantization.write(WORKING_DIRECTORY + File.separator + "quantization");
  Vocabulary.freeze();
  Vocabulary.write(WORKING_DIRECTORY + File.separator + "vocabulary");
  quantization.read(WORKING_DIRECTORY + File.separator + "quantization");
  logger.info("Beginning packing pass.");
  Queue<PackingFileTuple> slices=new PriorityQueue<PackingFileTuple>();
  grammar_reader=new LineReader(grammar);
  if (have_alignments)   alignment_reader=new LineReader(alignments);
  binarize(grammar_reader,alignment_reader,slices);
  logger.info("Packing complete.");
  logger.info("Packed grammar in: " + WORKING_DIRECTORY);
  logger.info("Done.");
}
 

Example 47

From project jSCSI, under directory /bundles/initiator/src/main/java/org/jscsi/initiator/connection/state/.

Source file: WriteFirstBurstState.java

  29 
vote

/** 
 * {@inheritDoc} 
 */
public final void execute() throws InternetSCSIException {
  final Queue<ProtocolDataUnit> protocolDataUnits=new LinkedList<ProtocolDataUnit>();
  ProtocolDataUnit protocolDataUnit;
  DataOutParser dataOut;
  IDataSegmentChunk dataSegmentChunk;
  boolean finalFlag=false;
  final int maxRecvDataSegmentLength=connection.getSettingAsInt(OperationalTextKey.MAX_RECV_DATA_SEGMENT_LENGTH);
  int bytes2Transfer=connection.getSettingAsInt(OperationalTextKey.FIRST_BURST_LENGTH) - bufferOffset;
  while (bytes2Transfer > 0 && iterator.hasNext()) {
    if (bytes2Transfer <= maxRecvDataSegmentLength) {
      dataSegmentChunk=iterator.next(bytes2Transfer);
      finalFlag=true;
    }
 else {
      dataSegmentChunk=iterator.next(maxRecvDataSegmentLength);
      finalFlag=false;
    }
    protocolDataUnit=protocolDataUnitFactory.create(false,finalFlag,OperationCode.SCSI_DATA_OUT,connection.getSetting(OperationalTextKey.HEADER_DIGEST),connection.getSetting(OperationalTextKey.DATA_DIGEST));
    protocolDataUnit.getBasicHeaderSegment().setInitiatorTaskTag(connection.getSession().getInitiatorTaskTag());
    dataOut=(DataOutParser)protocolDataUnit.getBasicHeaderSegment().getParser();
    dataOut.setTargetTransferTag(targetTransferTag);
    dataOut.setDataSequenceNumber(dataSequenceNumber++);
    dataOut.setBufferOffset(bufferOffset);
    bufferOffset+=maxRecvDataSegmentLength;
    protocolDataUnit.setDataSegment(dataSegmentChunk);
    protocolDataUnits.offer(protocolDataUnit);
    bytes2Transfer-=maxRecvDataSegmentLength;
  }
  connection.send(protocolDataUnits);
  connection.nextState(new WriteSecondResponseState(connection,iterator,dataSequenceNumber,bufferOffset));
  super.stateFollowing=true;
}
 

Example 48

From project JsTestDriver, under directory /JsTestDriver/src-test/com/google/jstestdriver/.

Source file: MockServer.java

  29 
vote

private String get(String request){
  Queue<String> response=expectations.get(request);
  if (response == null || response.size() == 0) {
    System.out.println("Unexpected request: " + request + "\n in "+ Lists.transform(Lists.newArrayList(expectations.keySet()),new Function<String,String>(){
      public String apply(      String arg){
        return "\n" + arg;
      }
    }
));
    throw new IllegalArgumentException("Unexpected request: " + request);
  }
  return response.remove();
}
 

Example 49

From project karaf, under directory /jaas/command/src/main/java/org/apache/karaf/jaas/command/.

Source file: JaasCommandSupport.java

  29 
vote

/** 
 * Add the command to the command queue.
 * @return
 * @throws Exception
 */
protected Object doExecute() throws Exception {
  JaasRealm realm=(JaasRealm)session.get(JAAS_REALM);
  AppConfigurationEntry entry=(AppConfigurationEntry)session.get(JAAS_ENTRY);
  @SuppressWarnings("unchecked") Queue<JaasCommandSupport> commandQueue=(Queue<JaasCommandSupport>)session.get(JAAS_CMDS);
  if (realm != null && entry != null) {
    if (commandQueue != null) {
      commandQueue.add(this);
    }
  }
 else {
    System.err.println("No JAAS Realm / Module has been selected");
  }
  return null;
}
 

Example 50

From project labs-paxexam-karaf, under directory /container/src/main/java/org/openengsb/labs/paxexam/karaf/container/internal/.

Source file: KarafTestContainer.java

  29 
vote

/** 
 * Since we might get quite deep use a simple breath first search algorithm
 */
private File searchKarafBase(File targetFolder){
  Queue<File> searchNext=new LinkedList<File>();
  searchNext.add(targetFolder);
  while (!searchNext.isEmpty()) {
    File head=searchNext.poll();
    if (!head.isDirectory()) {
      continue;
    }
    boolean system=false;
    boolean etc=false;
    for (    File file : head.listFiles()) {
      if (file.isDirectory() && file.getName().equals("system")) {
        system=true;
      }
      if (file.isDirectory() && file.getName().equals("etc")) {
        etc=true;
      }
    }
    if (system && etc) {
      return head;
    }
    searchNext.addAll(Arrays.asList(head.listFiles()));
  }
  throw new IllegalStateException("No karaf base dir found in extracted distribution.");
}
 

Example 51

From project lightweight_trie, under directory /src/java/com/rapleaf/lightweight_trie/.

Source file: EntrySetIterator.java

  29 
vote

public EntrySetIterator(AbstractNode<V> root){
  Queue<AbstractNode<V>> q=new LinkedList<AbstractNode<V>>();
  q.add(root);
  search.add(q);
  path.push(root);
  next();
}
 

Example 52

From project lyo.core, under directory /OSLC4JJenaProvider/src/org/eclipse/lyo/oslc4j/provider/jena/.

Source file: OslcRdfXmlCollectionProvider.java

  29 
vote

@Override public Collection<Object> readFrom(final Class<Collection<Object>> type,final Type genericType,final Annotation[] annotations,final MediaType mediaType,final MultivaluedMap<String,String> map,final InputStream inputStream) throws IOException, WebApplicationException {
  if (genericType instanceof ParameterizedType) {
    final ParameterizedType parameterizedType=(ParameterizedType)genericType;
    final Type[] actualTypeArguments=parameterizedType.getActualTypeArguments();
    if (actualTypeArguments.length == 1) {
      final Type actualTypeArgument=actualTypeArguments[0];
      if (actualTypeArgument instanceof Class) {
        final Object[] objects=readFrom((Class<?>)actualTypeArgument,mediaType,map,inputStream);
        final Collection<Object> collection;
        if ((Collection.class.equals(type)) || (List.class.equals(type)) || (Deque.class.equals(type))|| (Queue.class.equals(type))|| (AbstractCollection.class.equals(type))|| (AbstractList.class.equals(type))|| (AbstractSequentialList.class.equals(type))) {
          collection=new LinkedList<Object>();
        }
 else         if ((Set.class.equals(type)) || (AbstractSet.class.equals(type))) {
          collection=new HashSet<Object>();
        }
 else         if ((SortedSet.class.equals(type)) || (NavigableSet.class.equals(type))) {
          collection=new TreeSet<Object>();
        }
 else {
          try {
            @SuppressWarnings("cast") final Collection<Object> tempCollection=((Collection<Object>)type.newInstance());
            collection=tempCollection;
          }
 catch (          final Exception exception) {
            throw new WebApplicationException(exception,buildBadRequestResponse(exception,mediaType,map));
          }
        }
        collection.addAll(Arrays.asList(objects));
        return collection;
      }
    }
  }
  return null;
}
 

Example 53

From project MachinaCraft, under directory /MachinaFactory/src/me/lyneira/MachinaFactory/.

Source file: Pipeline.java

  29 
vote

/** 
 * Simplified implementation of Dijkstra's algorithm for finding the shortest path to a suitable target. This implementation leaves out alternative distance-checking and infinite distance checks because all distances are uniform and the graph is discovered on the fly. * <b>Important:</b> Setting <b>anchor</b> incorrectly or null will allow a machina to potentially hook up with itself and cause an endless loop!
 * @param anchor The anchor of the machina creating this pipeline.
 * @param player The player activating this machina.
 */
private void findRoute(BlockLocation anchor,Player player){
  Set<PipelineNode> graph=new HashSet<PipelineNode>(25);
  Queue<PipelineNode> q=new ArrayDeque<PipelineNode>();
  PipelineNode start=new PipelineNode(source);
  PipelineNode endnode=null;
  graph.add(start);
  q.add(start);
  for (PipelineNode node=q.poll(); node != null && graph.size() < maxSize; node=q.poll()) {
    endpoint=node.target(anchor,player);
    if (endpoint != null) {
      endnode=node;
      break;
    }
    for (    PipelineNode i : node.neighbors(ComponentBlueprint.pipelineMaterial)) {
      if (!graph.contains(i)) {
        graph.add(i);
        q.add(i);
      }
    }
  }
  if (endpoint == null)   return;
  destination=endnode.location;
  route=new ArrayDeque<PipelineNode>(endnode.distance - 1);
  for (PipelineNode node=endnode.previous; node.previous != null; node=node.previous) {
    route.addFirst(node);
  }
}
 

Example 54

From project managed-ledger, under directory /src/test/java/org/apache/bookkeeper/client/.

Source file: MockLedgerHandle.java

  29 
vote

@Override public void asyncReadEntries(long firstEntry,long lastEntry,ReadCallback cb,Object ctx){
  if (bk.isStopped()) {
    log.debug("Bookkeeper is closed!");
    cb.readComplete(-1,this,null,ctx);
    return;
  }
  log.debug("readEntries: first={} last={} total={}",va(firstEntry,lastEntry,entries.size()));
  final Queue<LedgerEntry> seq=new ArrayDeque<LedgerEntry>();
  long entryId=firstEntry;
  while (entryId <= lastEntry && entryId < entries.size()) {
    seq.add(entries.get((int)entryId++));
  }
  log.debug("Entries read: {}",seq);
  cb.readComplete(0,this,new Enumeration<LedgerEntry>(){
    public boolean hasMoreElements(){
      return !seq.isEmpty();
    }
    public LedgerEntry nextElement(){
      return seq.remove();
    }
  }
,ctx);
}
 

Example 55

From project maven-extensions, under directory /connectors/modules/scm/plugin/src/org/objectledge/maven/connectors/scm/.

Source file: ScmBuildParticipant.java

  29 
vote

/** 
 * Record directory layout as a string composed of newline-separated absolute paths of directories inside given directory, or empty string if the top level directory does not exist.
 * @param dir top level directory.
 * @return string describing directory layout.
 */
private static String directoryLayout(File dir){
  StringBuilder buff=new StringBuilder();
  if (dir.exists()) {
    Queue<File> stack=new LinkedList<File>();
    stack.add(dir);
    while (!stack.isEmpty()) {
      File cur=stack.remove();
      buff.append(cur.getAbsolutePath()).append('\n');
      File[] children=cur.listFiles();
      for (      File child : children) {
        if (child.isDirectory()) {
          stack.add(child);
        }
      }
    }
    return buff.toString();
  }
 else {
    return "";
  }
}
 

Example 56

From project mdk, under directory /service/core/src/main/java/uk/ac/ebi/mdk/service/.

Source file: DefaultServiceManager.java

  29 
vote

/** 
 * Class traversal algorithm adapted from: <a href="http://today.java.net/pub/a/today/2008/08/21/complex-table-cell-rendering.html">Article</a>
 * @param c
 * @return
 */
private Collection<Class<? extends QueryService>> getImplementingInterfaces(Class<?> c){
  if (interfaceMap.containsKey(c)) {
    return interfaceMap.get(c);
  }
  Queue<Class<?>> queue=new LinkedList<Class<?>>();
  Set<Class<?>> visited=new HashSet<Class<?>>();
  Set<Class<? extends QueryService>> implementations=new HashSet<Class<? extends QueryService>>();
  queue.add(c);
  visited.add(c);
  while (!queue.isEmpty()) {
    Class<?> curClass=queue.remove();
    List<Class<?>> supers=new LinkedList<Class<?>>();
    for (    Class<?> itrfce : curClass.getInterfaces()) {
      supers.add(itrfce);
    }
    Class<?> superClass=curClass.getSuperclass();
    if (superClass != null) {
      supers.add(superClass);
    }
    for (    Class<?> ifs : supers) {
      if (QueryService.class.isAssignableFrom(ifs) && ifs.isInterface() && !QueryService.class.equals(ifs)) {
        implementations.add((Class<? extends QueryService>)ifs);
      }
      implementations.addAll(getImplementingInterfaces(ifs));
    }
  }
  interfaceMap.putAll(c,implementations);
  return implementations;
}
 

Example 57

From project Metamorphosis, under directory /metamorphosis-server/src/main/java/com/taobao/metamorphosis/server/transaction/store/.

Source file: JournalTransactionStore.java

  29 
vote

public void add(final MessageStore store,final long msgId,final PutCommand putCmd){
  final AddMsgOperation addMsgOperation=new AddMsgOperation(store,msgId,putCmd);
  Queue<TxOperation> ops=this.operations.get(store);
  if (ops == null) {
    ops=new ConcurrentLinkedQueue<TxOperation>();
    final Queue<TxOperation> oldOps=this.operations.putIfAbsent(store,ops);
    if (oldOps != null) {
      ops=oldOps;
    }
  }
  ops.add(addMsgOperation);
}
 

Example 58

From project mina, under directory /core/src/main/java/org/apache/mina/session/.

Source file: SslHelper.java

  29 
vote

/** 
 * No qualifier 
 */
WriteRequest processWrite(IoSession session,Object message,Queue<WriteRequest> writeQueue){
  ByteBuffer buf=(ByteBuffer)message;
  ByteBuffer appBuffer=ByteBuffer.allocate(sslEngine.getSession().getPacketBufferSize());
  try {
    while (true) {
      SSLEngineResult result=sslEngine.wrap(buf,appBuffer);
switch (result.getStatus()) {
case BUFFER_OVERFLOW:
        appBuffer=ByteBuffer.allocate(appBuffer.capacity() + 4096);
      break;
case BUFFER_UNDERFLOW:
case CLOSED:
    break;
case OK:
  appBuffer.flip();
WriteRequest request=new DefaultWriteRequest(appBuffer);
writeQueue.add(request);
return request;
}
}
}
 catch (SSLException se) {
throw new IllegalStateException(se.getMessage());
}
}
 

Example 59

From project miso-lims, under directory /miso-web/src/main/java/uk/ac/bbsrc/tgac/miso/webapp/util/.

Source file: SessionConversationAttributeStore.java

  29 
vote

/** 
 * gets the conversations holder or creates one if it does not exist.
 * @param request
 * @param attributeName
 * @return
 */
@SuppressWarnings("unchecked") private Map<String,Queue<String>> getConversationsMap(WebRequest request){
  Map<String,Queue<String>> conversationQueueMap=(Map<String,Queue<String>>)request.getAttribute("_sessionConversations",WebRequest.SCOPE_SESSION);
  if (conversationQueueMap == null) {
    conversationQueueMap=new HashMap<String,Queue<String>>();
    request.setAttribute("_sessionConversations",conversationQueueMap,WebRequest.SCOPE_SESSION);
  }
  return conversationQueueMap;
}
 

Example 60

From project moho, under directory /moho-impl/src/main/java/com/voxeo/moho/queue/.

Source file: SimpleQueue.java

  29 
vote

/** 
 * Construct a Simple Queue
 * @param ctx the application context
 * @param queue the queue implementation
 * @param res the audio to be rendered
 * @param shared whether audio streams are shared or not
 */
public SimpleQueue(final ApplicationContext ctx,final Queue<Call> queue,final AudibleResource res,final boolean shared){
  super((ExecutionContext)ctx);
  _queue=queue;
  _output=new OutputCommand(res);
  _output.setRepeatInterval(Integer.MAX_VALUE);
  _shared=shared;
}
 

Example 61

From project morphia, under directory /morphia/src/test/java/com/google/code/morphia/issue345/.

Source file: ConcurrentJunitRunner.java

  29 
vote

public ConcurrentJunitRunner(final Class<?> klass) throws InitializationError {
  super(klass);
  setScheduler(new RunnerScheduler(){
    ExecutorService executorService=Executors.newFixedThreadPool(klass.isAnnotationPresent(Concurrent.class) ? klass.getAnnotation(Concurrent.class).threads() : (int)(Runtime.getRuntime().availableProcessors() * 1.5),new NamedThreadFactory(klass.getSimpleName()));
    CompletionService<Void> completionService=new ExecutorCompletionService<Void>(executorService);
    Queue<Future<Void>> tasks=new LinkedList<Future<Void>>();
    public void schedule(    Runnable childStatement){
      tasks.offer(completionService.submit(childStatement,null));
    }
    public void finished(){
      try {
        while (!tasks.isEmpty())         tasks.remove(completionService.take());
      }
 catch (      InterruptedException e) {
        Thread.currentThread().interrupt();
      }
 finally {
        while (!tasks.isEmpty())         tasks.poll().cancel(true);
        executorService.shutdownNow();
      }
    }
  }
);
}
 

Example 62

From project netty, under directory /buffer/src/main/java/io/netty/buffer/.

Source file: QueueBackedMessageBuf.java

  29 
vote

public QueueBackedMessageBuf(Queue<T> queue){
  if (queue == null) {
    throw new NullPointerException("queue");
  }
  this.queue=queue;
}
 

Example 63

From project netty-socketio, under directory /src/main/java/com/corundumstudio/socketio/namespace/.

Source file: Namespace.java

  29 
vote

@SuppressWarnings({"rawtypes","unchecked"}) public void onEvent(SocketIOClient client,String eventName,Object data,AckRequest ackRequest){
  EventEntry entry=eventListeners.get(eventName);
  if (entry == null) {
    return;
  }
  Queue<DataListener> listeners=entry.getListeners();
  for (  DataListener dataListener : listeners) {
    dataListener.onData(client,data,ackRequest);
  }
}
 

Example 64

From project nuxeo-tycho-osgi, under directory /nuxeo-core/nuxeo-core-api/src/main/java/org/nuxeo/ecm/core/api/model/impl/osm/.

Source file: TypeAnnotationRegistry.java

  29 
vote

protected Annotation lookup(Class<?> type,Queue<Class<?>> queue){
  Annotation anno=registry.get(type);
  if (anno != null) {
    return anno;
  }
  queue.add(type);
  Class<?> superClass=type.getSuperclass();
  if (superClass != null) {
    anno=lookup(superClass,queue);
  }
  if (anno == null) {
    anno=new Annotation(type,null,null);
  }
  registry.put(type,anno);
  return anno;
}
 

Example 65

From project onebusaway-uk, under directory /onebusaway-uk-network-rail-gtfs-realtime/src/main/java/org/onebusaway/uk/network_rail/gtfs_realtime/graph/.

Source file: RawGraph.java

  29 
vote

public BerthPath getShortestPath(RawBerthNode nodeFrom,RawBerthNode nodeTo,double maxTime){
  Queue<OrderedRawBerthNode> queue=new PriorityQueue<OrderedRawBerthNode>();
  queue.add(new OrderedRawBerthNode(nodeFrom,null,0.0));
  Map<RawBerthNode,RawBerthNode> parents=new HashMap<RawBerthNode,RawBerthNode>();
  Set<RawBerthNode> visited=new HashSet<RawBerthNode>();
  while (!queue.isEmpty()) {
    OrderedRawBerthNode currentNode=queue.poll();
    RawBerthNode node=currentNode.getNode();
    if (!visited.add(node)) {
      continue;
    }
    if (currentNode.getDistance() > maxTime) {
      break;
    }
    parents.put(node,currentNode.getParent());
    if (node == nodeTo) {
      List<RawBerthNode> path=new ArrayList<RawBerthNode>();
      RawBerthNode last=node;
      while (last != null) {
        path.add(last);
        last=parents.get(last);
      }
      Collections.reverse(path);
      return new BerthPath(path,currentNode.getDistance());
    }
    for (    Map.Entry<RawBerthNode,List<Integer>> entry : node.getOutgoing().entrySet()) {
      RawBerthNode outgoing=entry.getKey();
      int avgDuration=RawNode.average(entry.getValue());
      queue.add(new OrderedRawBerthNode(outgoing,node,currentNode.getDistance() + avgDuration));
    }
  }
  return null;
}
 

Example 66

From project OpenTripPlanner, under directory /opentripplanner-gui/src/main/java/org/opentripplanner/gui/.

Source file: VizGui.java

  29 
vote

protected void traceOld(){
  HashSet<Vertex> seenVertices=new HashSet<Vertex>();
  DisplayVertex selected=(DisplayVertex)nearbyVertices.getSelectedValue();
  if (selected == null) {
    System.out.println("no vertex selected");
    return;
  }
  Vertex v=selected.vertex;
  System.out.println("initial vertex: " + v);
  Queue<Vertex> toExplore=new LinkedList<Vertex>();
  toExplore.add(v);
  seenVertices.add(v);
  while (!toExplore.isEmpty()) {
    Vertex src=toExplore.poll();
    for (    Edge e : src.getOutgoing()) {
      Vertex tov=e.getToVertex();
      if (!seenVertices.contains(tov)) {
        seenVertices.add(tov);
        toExplore.add(tov);
      }
    }
  }
  showGraph.setHighlightedVertices(seenVertices);
}