Java Code Examples for java.util.Deque

The following are top voted examples for showing how to use java.util.Deque. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: hadoop   File: TestAnd.java   Source Code and License 6 votes vote down vote up
@Test(timeout = 1000)
public void testPrepare() throws IOException {
  And and = new And();
  Expression first = mock(Expression.class);
  Expression second = mock(Expression.class);

  Deque<Expression> children = new LinkedList<Expression>();
  children.add(second);
  children.add(first);
  and.addChildren(children);

  and.prepare();
  verify(first).prepare();
  verify(second).prepare();
  verifyNoMoreInteractions(first);
  verifyNoMoreInteractions(second);
}
 
Example 2
Project: Reer   File: NativeDependentBinariesResolutionStrategy.java   Source Code and License 6 votes vote down vote up
private List<DependentBinariesResolvedResult> doBuildResolvedResult(final NativeBinarySpecInternal target, State state, Deque<NativeBinarySpecInternal> stack) {
    if (stack.contains(target)) {
        onCircularDependencies(state, stack, target);
    }
    List<DependentBinariesResolvedResult> result = resultsCache.getIfPresent(target);
    if (result != null) {
        return result;
    }
    stack.push(target);
    result = Lists.newArrayList();
    List<NativeBinarySpecInternal> dependents = state.getDependents(target);
    for (NativeBinarySpecInternal dependent : dependents) {
        List<DependentBinariesResolvedResult> children = doBuildResolvedResult(dependent, state, stack);
        result.add(new DefaultDependentBinariesResolvedResult(dependent.getId(), dependent.getProjectScopedName(), dependent.isBuildable(), isTestSuite(dependent), children));
    }
    stack.pop();
    resultsCache.put(target, result);
    return result;
}
 
Example 3
Project: jdk8u-jdk   File: Nodes.java   Source Code and License 6 votes vote down vote up
/**
 * Depth first search, in left-to-right order, of the node tree, using
 * an explicit stack, to find the next non-empty leaf node.
 */
@SuppressWarnings("unchecked")
protected final N findNextLeafNode(Deque<N> stack) {
    N n = null;
    while ((n = stack.pollFirst()) != null) {
        if (n.getChildCount() == 0) {
            if (n.count() > 0)
                return n;
        } else {
            for (int i = n.getChildCount() - 1; i >= 0; i--)
                stack.addFirst((N) n.getChild(i));
        }
    }

    return null;
}
 
Example 4
Project: incubator-netbeans   File: SourcePrefetcherTest.java   Source Code and License 6 votes vote down vote up
public void testSeqPref() throws Exception {
    JavaIndexerWorker.TEST_DO_PREFETCH = false;
    final LogHandler handler = new LogHandler();
    handler.expect("Using sequential iterator");    //NOI18N
    final Logger log = Logger.getLogger(JavaIndexerWorker.class.getName());
    log.setLevel(Level.FINE);
    log.addHandler(handler);
    try {
        SourcePrefetcher pf = SourcePrefetcher.create(files, SuspendSupport.NOP);
        assertTrue(handler.isFound());
        final Deque<CompileTuple> got = new ArrayDeque<CompileTuple>(FILE_COUNT);
        while (pf.hasNext()) {
            final CompileTuple ct = pf.next();
            assertNull(getCache(ct.jfo));
            got.offer(ct);
            pf.remove();
        }
        assertCollectionsEqual(files,got);
    } finally {
        log.removeHandler(handler);
    }
}
 
Example 5
Project: javaide   File: DimensionHelpers.java   Source Code and License 6 votes vote down vote up
/**
 * Accumulates a flattened list of array dimensions specifiers with type annotations, and returns
 * the base type.
 * <p>
 * <p>Given {@code int @A @B [][] @C []}, adds {@code [[@A, @B], [@C]]} to dims and returns {@code
 * int}.
 */
private static Tree extractDims(Deque<List<AnnotationTree>> dims, Tree node) {
    switch (node.getKind()) {
        case ARRAY_TYPE:
            return extractDims(dims, ((ArrayTypeTree) node).getType());
        // TODO: 22-Jul-17 missing type
       /* case ANNOTATED_TYPE:
            AnnotatedTypeTree annotatedTypeTree = (AnnotatedTypeTree) node;
            if (annotatedTypeTree.getUnderlyingType().getKind() != Tree.Kind.ARRAY_TYPE) {
                return node;
            }
            node = extractDims(dims, annotatedTypeTree.getUnderlyingType());
            dims.addFirst(ImmutableList.<AnnotationTree>copyOf(annotatedTypeTree.getAnnotations()));
            return node;*/
        default:
            return node;
    }
}
 
Example 6
Project: Java-SE-9-Road-to-Concurrent-and-High-Performance-Programming   File: Main.java   Source Code and License 6 votes vote down vote up
/**
 * Main method of the example. Creates three WriterTasks and a CleanerTask
 * 
 * @param args
 */
public static void main(String[] args) {

	// Creates the Event data structure
	Deque<Event> deque = new ConcurrentLinkedDeque<>();

	// Creates the three WriterTask and starts them
	WriterTask writer = new WriterTask(deque);
	for (int i = 0; i < Runtime.getRuntime().availableProcessors(); i++) {
		Thread thread = new Thread(writer);
		thread.start();
	}

	// Creates a cleaner task and starts them
	CleanerTask cleaner = new CleanerTask(deque);
	cleaner.start();

}
 
Example 7
Project: hashsdn-controller   File: LocalSnapshotStore.java   Source Code and License 6 votes vote down vote up
private Optional<SelectedSnapshot> doLoad(final Deque<SnapshotMetadata> metadatas) throws IOException {
    SnapshotMetadata metadata = metadatas.removeFirst();
    File file = toSnapshotFile(metadata);

    LOG.debug("doLoad {}", file);

    try {
        Object data = deserialize(file);

        LOG.debug("deserialized data: {}", data);

        return Optional.of(new SelectedSnapshot(metadata, data));
    } catch (IOException e) {
        LOG.error("Error loading snapshot file {}, remaining attempts: {}", file, metadatas.size(), e);

        if (metadatas.isEmpty()) {
            throw e;
        }

        return doLoad(metadatas);
    }
}
 
Example 8
Project: pgcodekeeper   File: DbStorePicker.java   Source Code and License 6 votes vote down vote up
public static File chooseDbSource(Shell shell, IPreferenceStore prefStore, boolean dir) {
    String pathToDump = dir ? getDirPath(shell, prefStore) : getFilePath(shell, prefStore);
    if (pathToDump == null) {
        return null;
    }

    File dumpFile = new File(pathToDump);
    Deque<File> dumpHistory = stringToDumpFileHistory(prefStore.getString(PREF.DB_STORE_FILES));
    dumpHistory.addFirst(dumpFile);
    while (dumpHistory.size() > MAX_FILES_HISTORY) {
        dumpHistory.removeLast();
    }
    prefStore.setValue(PREF.DB_STORE_FILES, dumpFileHistoryToPreference(dumpHistory));
    prefStore.setValue(PREF.LAST_OPENED_LOCATION,
            dir ? dumpFile.getAbsolutePath() : dumpFile.getParent());
    return dumpFile;
}
 
Example 9
Project: openjdk-jdk10   File: Nodes.java   Source Code and License 6 votes vote down vote up
@Override
public void forEachRemaining(Consumer<? super T> consumer) {
    if (curNode == null)
        return;

    if (tryAdvanceSpliterator == null) {
        if (lastNodeSpliterator == null) {
            Deque<Node<T>> stack = initStack();
            Node<T> leaf;
            while ((leaf = findNextLeafNode(stack)) != null) {
                leaf.forEach(consumer);
            }
            curNode = null;
        }
        else
            lastNodeSpliterator.forEachRemaining(consumer);
    }
    else
        while(tryAdvance(consumer)) { }
}
 
Example 10
Project: magellan   File: NavigatorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void rewriteHistory() {
  navigator.onCreate(activity, null);
  navigator.goTo(screen);

  assertThat(navigator.currentScreen()).isEqualTo(screen);

  navigator.onDestroy(activity);

  navigator.rewriteHistory(activity, new HistoryRewriter() {
    @Override
    public void rewriteHistory(Deque<Screen> history) {
      history.pop();
    }
  });

  assertThat(navigator.currentScreen()).isEqualTo(root);
}
 
Example 11
Project: magellan   File: NavigatorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void navigate() {
  when(screen.shouldShowActionBar()).thenReturn(false);
  when(screen2.shouldShowActionBar()).thenReturn(true);

  navigator.onCreate(activity, null);
  navigator.goTo(screen);

  navigator.navigate(new HistoryRewriter() {
    @Override
    public void rewriteHistory(Deque<Screen> history) {
      history.clear();
      history.push(root);
      history.push(screen2);
    }
  });

  verify(screen).onHide(activity);
  verify(screen2).onShow(activity);
  assertThat(navigator.currentScreen()).isEqualTo(screen2);
}
 
Example 12
Project: plugin-bt-jira   File: JiraExportPluginResourceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void toStyleProcessorOverThreshold() {
	final Deque<Object> contextData = new ArrayDeque<>();
	contextData.add(1); // Index
	final SlaData data = new SlaData();
	data.setDuration(13L); // Duration;
	contextData.add(data);
	final JiraSlaComputations slaComputations = new JiraSlaComputations();
	final SlaConfiguration slaConfiguration0 = new SlaConfiguration();
	slaConfiguration0.setThreshold(14);
	final SlaConfiguration slaConfiguration1 = new SlaConfiguration();
	slaConfiguration1.setThreshold(12);
	slaComputations.setSlaConfigurations(Arrays.asList(slaConfiguration0, slaConfiguration1));
	Assert.assertEquals("invalid", resource.toStyleProcessor(slaComputations, "normal", "invalid").getValue(contextData));

}
 
Example 13
Project: jdk8u-jdk   File: Nodes.java   Source Code and License 6 votes vote down vote up
@Override
public void forEachRemaining(T_CONS consumer) {
    if (curNode == null)
        return;

    if (tryAdvanceSpliterator == null) {
        if (lastNodeSpliterator == null) {
            Deque<N> stack = initStack();
            N leaf;
            while ((leaf = findNextLeafNode(stack)) != null) {
                leaf.forEach(consumer);
            }
            curNode = null;
        }
        else
            lastNodeSpliterator.forEachRemaining(consumer);
    }
    else
        while(tryAdvance(consumer)) { }
}
 
Example 14
Project: lams   File: NodeTraverser.java   Source Code and License 6 votes vote down vote up
private void visitDepthFirst(AST ast) {
	if ( ast == null ) {
		return;
	}
	Deque<AST> stack = new ArrayDeque<AST>();
	stack.addLast( ast );
	while ( !stack.isEmpty() ) {
		ast = stack.removeLast();
		strategy.visit( ast );
		if ( ast.getNextSibling() != null ) {
			stack.addLast( ast.getNextSibling() );
		}
		if ( ast.getFirstChild() != null ) {
			stack.addLast( ast.getFirstChild() );
		}
	}
}
 
Example 15
Project: brick-pop-solver   File: Board.java   Source Code and License 6 votes vote down vote up
private Set<Coordinate> floodIndices(final Coordinate coordinate) {
    final Set<Coordinate> flood = new LinkedHashSet<>();
    final Color floodColor = getColor(coordinate);
    final Deque<Coordinate> queue = new LinkedList<>();
    queue.add(coordinate);

    while (!queue.isEmpty()) {
        final Coordinate location = queue.pop();
        flood.add(location);

        queue.addAll(getNeighbors(location).stream()
            .filter(neighbor -> floodColor.equals(getColor(neighbor)) && !flood.contains(neighbor))
            .collect(Collectors.toList()));
    }

    return flood;
}
 
Example 16
Project: hadoop-oss   File: TestAnd.java   Source Code and License 6 votes vote down vote up
@Test(timeout = 1000)
public void testFailBoth() throws IOException {
  And and = new And();

  PathData pathData = mock(PathData.class);

  Expression first = mock(Expression.class);
  when(first.apply(pathData, -1)).thenReturn(Result.FAIL);

  Expression second = mock(Expression.class);
  when(second.apply(pathData, -1)).thenReturn(Result.FAIL);

  Deque<Expression> children = new LinkedList<Expression>();
  children.add(second);
  children.add(first);
  and.addChildren(children);

  assertEquals(Result.FAIL, and.apply(pathData, -1));
  verify(first).apply(pathData, -1);
  verifyNoMoreInteractions(first);
  verifyNoMoreInteractions(second);
}
 
Example 17
Project: hadoop-oss   File: TestAnd.java   Source Code and License 6 votes vote down vote up
@Test(timeout = 1000)
public void testSetOptions() throws IOException {
  And and = new And();
  Expression first = mock(Expression.class);
  Expression second = mock(Expression.class);

  Deque<Expression> children = new LinkedList<Expression>();
  children.add(second);
  children.add(first);
  and.addChildren(children);

  FindOptions options = mock(FindOptions.class);
  and.setOptions(options);
  verify(first).setOptions(options);
  verify(second).setOptions(options);
  verifyNoMoreInteractions(first);
  verifyNoMoreInteractions(second);
}
 
Example 18
Project: hadoop-oss   File: TestAnd.java   Source Code and License 6 votes vote down vote up
@Test(timeout = 1000)
public void testPrepare() throws IOException {
  And and = new And();
  Expression first = mock(Expression.class);
  Expression second = mock(Expression.class);

  Deque<Expression> children = new LinkedList<Expression>();
  children.add(second);
  children.add(first);
  and.addChildren(children);

  and.prepare();
  verify(first).prepare();
  verify(second).prepare();
  verifyNoMoreInteractions(first);
  verifyNoMoreInteractions(second);
}
 
Example 19
Project: plugin-bt-jira   File: JiraExportPluginResource.java   Source Code and License 6 votes vote down vote up
/**
 * Return the style corresponding to the threshold value.
 */
protected Processor<SlaData> toStyleProcessor(final JiraSlaComputations slaComputations, final String styleNormal,
		final String styleOver) {
	return new Processor<SlaData>() {
		@Override
		public Object getValue(final Deque<Object> contextData) {
			// Get the context
			final Object[] context = contextData.toArray();
			final SlaData data = (SlaData) contextData.getLast();
			final int index = (Integer) context[context.length - 2];
			final long threshold = slaComputations.getSlaConfigurations().get(index).getThreshold();

			// Check the threshold
			if (data != null && threshold != 0 && data.getDuration() > threshold) {
				// Out of time
				return styleOver;
			}
			return styleNormal;
		}
	};
}
 
Example 20
Project: openjdk-jdk10   File: ChorusLine.java   Source Code and License 5 votes vote down vote up
public void run(Deque<Integer> deq) {
    while (deq.size() > 1) {
        Iterator<Integer> it = deq.iterator();
        it.next(); it.remove();
        it = deq.descendingIterator();
        it.next(); it.remove();
    }
    System.out.println(deq);
}
 
Example 21
Project: Reer   File: DefaultLenientConfiguration.java   Source Code and License 5 votes vote down vote up
public Set<ResolvedDependency> getAllModuleDependencies() {
    Set<ResolvedDependency> resolvedElements = new LinkedHashSet<ResolvedDependency>();
    Deque<ResolvedDependency> workQueue = new LinkedList<ResolvedDependency>();
    workQueue.addAll(loadTransientGraphResults(selectedArtifacts).getRootNode().getPublicView().getChildren());
    while (!workQueue.isEmpty()) {
        ResolvedDependency item = workQueue.removeFirst();
        if (resolvedElements.add(item)) {
            final Set<ResolvedDependency> children = item.getChildren();
            if (children != null) {
                workQueue.addAll(children);
            }
        }
    }
    return resolvedElements;
}
 
Example 22
Project: plugin-bt-jira   File: JiraExportPluginResourceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void toStyleProcessorDistanceLate() {
	final Deque<Object> contextData = new ArrayDeque<>();
	final SlaData data = new SlaData();
	data.setRevisedDueDateDistance(-1L); // Negative distance, late
	contextData.add(data);
	Assert.assertEquals("invalid", resource.toStyleProcessorDistance("normal", "invalid").getValue(contextData));
}
 
Example 23
Project: openjdk-jdk10   File: ModuleHashesBuilder.java   Source Code and License 5 votes vote down vote up
private void visit(T node, Deque<T> visited, Deque<T> done) {
    if (visited.contains(node)) {
        if (!done.contains(node)) {
            throw new IllegalArgumentException("Cyclic detected: " +
                node + " " + graph.edges().get(node));
        }
        return;
    }
    visited.add(node);
    graph.edges().get(node).stream()
        .forEach(x -> visit(x, visited, done));
    done.add(node);
    result.addLast(node);
}
 
Example 24
Project: q-mail   File: MockPop3Server.java   Source Code and License 5 votes vote down vote up
public MockServerThread(ServerSocket serverSocket, Deque<ImapInteraction> interactions,
        CountDownLatch waitForConnectionClosed, CountDownLatch waitForAllExpectedCommands, Logger logger,
        KeyStoreProvider keyStoreProvider) {
    super("MockImapServer");
    this.serverSocket = serverSocket;
    this.interactions = interactions;
    this.waitForConnectionClosed = waitForConnectionClosed;
    this.waitForAllExpectedCommands = waitForAllExpectedCommands;
    this.logger = logger;
    this.keyStoreProvider = keyStoreProvider;
}
 
Example 25
Project: bootstrap   File: MapProcessorTest.java   Source Code and License 5 votes vote down vote up
/**
 * Simple test of a valid property and a not null value.
 */
@Test
public void testGetValue() {
	final Deque<Object> contextData = new LinkedList<>();
	final SystemUser systemUser = new SystemUser();
	systemUser.setLogin("any");
	contextData.add(systemUser);
	final Map<String, String> map = new HashMap<>();
	map.put("any", "value");
	Assert.assertEquals("value", new MapProcessor<>(map, SystemUser.class, "login").getValue(contextData));
}
 
Example 26
Project: CodeKatas   File: EclipseCollectionsDeckOfCardsAsListTest.java   Source Code and License 5 votes vote down vote up
@Test
public void deal()
{
    MutableStack<Card> ecShuffle = this.ecDeck.shuffle(new Random(1));
    Deque<Card> jdkShuffle = this.jdkDeck.shuffle(new Random(1));

    MutableSet<Card> ecHand = this.ecDeck.deal(ecShuffle, 5);
    Set<Card> jdkHand = this.jdkDeck.deal(jdkShuffle, 5);
    Assert.assertEquals(jdkHand, ecHand);
}
 
Example 27
Project: CodeKatas   File: JDKImperativeDeckOfCardsAsSortedSetTest.java   Source Code and License 5 votes vote down vote up
@Test
public void dealHands()
{
    Deque<Card> jdkShuffled = this.jdkDeck.shuffle(new Random(1));
    List<Set<Card>> jdkHands = this.jdkDeck.dealHands(jdkShuffled, 5, 5);
    Assert.assertEquals(5, jdkHands.size());
    Assert.assertTrue(Iterate.allSatisfy(jdkHands, each -> each.size() == 5));
    Assert.assertEquals(27, jdkShuffled.size());
}
 
Example 28
Project: boohee_v5.6   File: CertificateChainCleaner.java   Source Code and License 5 votes vote down vote up
public List<Certificate> clean(List<Certificate> chain) throws SSLPeerUnverifiedException {
    Deque<Certificate> queue = new ArrayDeque(chain);
    List<Certificate> result = new ArrayList();
    result.add(queue.removeFirst());
    boolean foundTrustedCertificate = false;
    int c = 0;
    while (c < 9) {
        X509Certificate toVerify = (X509Certificate) result.get(result.size() - 1);
        X509Certificate trustedCert = this.trustRootIndex.findByIssuerAndSignature(toVerify);
        if (trustedCert != null) {
            if (result.size() > 1 || !toVerify.equals(trustedCert)) {
                result.add(trustedCert);
            }
            if (!verifySignature(trustedCert, trustedCert)) {
                foundTrustedCertificate = true;
                c++;
            }
        } else {
            Iterator<Certificate> i = queue.iterator();
            while (i.hasNext()) {
                X509Certificate signingCert = (X509Certificate) i.next();
                if (verifySignature(toVerify, signingCert)) {
                    i.remove();
                    result.add(signingCert);
                    c++;
                }
            }
            if (!foundTrustedCertificate) {
                throw new SSLPeerUnverifiedException("Failed to find a trusted cert that " +
                        "signed " + toVerify);
            }
        }
        return result;
    }
    throw new SSLPeerUnverifiedException("Certificate chain too long: " + result);
}
 
Example 29
Project: GitHub   File: ReflectionUtils.java   Source Code and License 5 votes vote down vote up
public static Set<Class<?>> getImplementedInterfaces(Class<?> cl){
    Set<Class<?>> interfaces = new HashSet<Class<?>>();
    Deque<Class<?>> classes = new ArrayDeque<Class<?>>();
    classes.add(cl);
    while (!classes.isEmpty()) {
        Class<?> c = classes.pop();
        interfaces.addAll(Arrays.asList(c.getInterfaces()));
        if (c.getSuperclass() != null) {
            classes.add(c.getSuperclass());
        }
        classes.addAll(Arrays.asList(c.getInterfaces()));
    }
    return interfaces;
}
 
Example 30
Project: CustomLintRules   File: AutoPointIdInFileDetector.java   Source Code and License 5 votes vote down vote up
public void check() {
    // Visit the DAG, looking for conflicts
    for (Layout layout : mFileToLayout.values()) {
        if (!layout.isIncluded()) { // Only check from "root" nodes
            Deque<Layout> stack = new ArrayDeque<>();
            getIds(layout, stack, new HashSet<>());
        }
    }
}
 
Example 31
Project: allure-java   File: AllureCucumberJvm.java   Source Code and License 5 votes vote down vote up
@Override
public void startOfScenarioLifeCycle(final Scenario scenario) {
    this.currentScenario = scenario;

    final Deque<Tag> tags = new LinkedList<>();
    tags.addAll(scenario.getTags());

    if (SCENARIO_OUTLINE_KEYWORDS.contains(scenario.getKeyword())) {
        synchronized (gherkinSteps) {
            gherkinSteps.clear();
        }
    } else {
        tags.addAll(currentFeature.getTags());
    }

    final LabelBuilder labelBuilder = new LabelBuilder(currentFeature, scenario, tags);


    final TestResult result = new TestResult()
            .withUuid(scenario.getId())
            .withHistoryId(StepUtils.getHistoryId(scenario.getId()))
            .withName(scenario.getName())
            .withLabels(labelBuilder.getScenarioLabels())
            .withLinks(labelBuilder.getScenarioLinks());

    if (!currentFeature.getDescription().isEmpty()) {
        result.withDescription(currentFeature.getDescription());
    }

    lifecycle.scheduleTestCase(result);
    lifecycle.startTestCase(scenario.getId());

}
 
Example 32
Project: kafka-0.11.0.0-src-with-comment   File: InFlightRequests.java   Source Code and License 5 votes vote down vote up
/**
 * Clear out all the in-flight requests for the given node and return them
 *
 * @param node The node
 * @return All the in-flight requests for that node that have been removed
 */
public Iterable<NetworkClient.InFlightRequest> clearAll(String node) {
    Deque<NetworkClient.InFlightRequest> reqs = requests.get(node);
    if (reqs == null) {
        return Collections.emptyList();
    } else {
        return requests.remove(node);
    }
}
 
Example 33
Project: lams   File: QueryParameterUtils.java   Source Code and License 5 votes vote down vote up
public static String buildQueryString(final Map<String, Deque<String>> params) {
    StringBuilder sb = new StringBuilder();
    boolean first = true;
    for (Map.Entry<String, Deque<String>> entry : params.entrySet()) {
        if (entry.getValue().isEmpty()) {
            if (first) {
                first = false;
            } else {
                sb.append('&');
            }
            sb.append(entry.getKey());
            sb.append('=');
        } else {
            for (String val : entry.getValue()) {
                if (first) {
                    first = false;
                } else {
                    sb.append('&');
                }
                sb.append(entry.getKey());
                sb.append('=');
                sb.append(val);
            }
        }
    }
    return sb.toString();
}
 
Example 34
Project: Equella   File: ThreadSafeSimpleDateFormat.java   Source Code and License 5 votes vote down vote up
private void release(DateFormat format, Locale locale)
{
	synchronized( mutex )
	{
		Deque<DateFormat> sp = getSubpool(locale);
		if( sp.size() >= poolSizePerLocale )
		{
			sp.addFirst(format);
		}
	}
}
 
Example 35
Project: smartlog   File: SmartLog.java   Source Code and License 5 votes vote down vote up
@Nonnull
public static LogContext current() {
    final Deque<LogContext> contextQueue = CONTEXTS.get();
    if (!contextQueue.isEmpty()) {
        return contextQueue.peek();
    } else {
        throw new RuntimeException("Loggable context is absent");
    }
}
 
Example 36
Project: kafka-0.11.0.0-src-with-comment   File: RecordAccumulator.java   Source Code and License 5 votes vote down vote up
/**
 * Re-enqueue the given record batch in the accumulator to retry
 */
public void reenqueue(ProducerBatch batch, long now) {
    batch.reenqueued(now);
    Deque<ProducerBatch> deque = getOrCreateDeque(batch.topicPartition);
    synchronized (deque) {
        deque.addFirst(batch);
    }
}
 
Example 37
Project: lams   File: HandlerParser.java   Source Code and License 5 votes vote down vote up
private static HandlerWrapper handleSingleArrayValue(final String string, final HandlerBuilder builder, final Deque<Token> tokens, final Token token, final ExchangeAttributeParser attributeParser) {
    String sv = builder.defaultParameter();
    if (sv == null) {
        throw error(string, token.position, "default parameter not supported");
    }
    Object array = readArrayType(string, tokens, new Token(sv, token.position), builder, attributeParser, "}");
    Token close = tokens.poll();
    if (!close.token.equals("]")) {
        throw error(string, close.position, "expected ]");
    }
    return builder.build(Collections.singletonMap(sv, array));
}
 
Example 38
Project: Aim2Offer   File: 023_BinaryTreeInRowOrder.java   Source Code and License 5 votes vote down vote up
public void printFromTopToBottom(TreeNode root) {
    if (root == null) return;
    Deque<TreeNode> queue = new ArrayDeque<>();
    queue.addLast(root);

    while (!queue.isEmpty()) {
        TreeNode node = queue.pop();
        System.out.print(node.val + " ");
        if (node.left != null)
            queue.addLast(node.left);
        if (node.right != null)
            queue.addLast(node.right);
    }
}
 
Example 39
Project: incubator-netbeans   File: Utils.java   Source Code and License 5 votes vote down vote up
public static String getSignificantIncommingString(Instance in) {
    Set<Instance> processed = new HashSet<Instance>();
    String temp = null;
    Deque<Instance> fifo = new ArrayDeque<Instance>();
    fifo.add(in);

    while (!fifo.isEmpty()) {
        if (fifo.size() > 10) {
            Logger.getLogger(Utils.class.getName()).log(Level.FINE, "overflow in getSignificantIncommingString({0})", new Object[] { in });

            break;
        }

        Instance act = fifo.removeFirst();
        @SuppressWarnings("unchecked")
        List<Value> incoming = act.getReferences();

        for (Value v : incoming) {
            String rName = v.getDefiningInstance().getJavaClass().getName();

            if (temp == null) {
                temp = "<< " + rName; // there is at least some incoming ref
            }

            if (rName.startsWith("java.") || rName.startsWith("javax.")) { // NOI18N
                Instance i = v.getDefiningInstance();

                if (processed.add(i)) {
                    fifo.add(i);
                }
            } else { // Bingo!

                return rName;
            }
        }
    }

    return (temp == null) ? "unknown" : temp; // NOI18N
}
 
Example 40
Project: incubator-netbeans   File: ClassLoaderSupport.java   Source Code and License 5 votes vote down vote up
@NonNull
private static URL[] getRootURLs(@NonNull final ClassPath cp) {
    final List<ClassPath.Entry> entries = cp.entries();
    final Deque<URL> res = new ArrayDeque<>(entries.size());
    for (ClassPath.Entry e : entries) {
        res.offer(e.getURL());
    }
    return res.toArray(new URL[res.size()]);
}