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()]);
}
 
Example 41
Project: javaide   File: JavaInputAstVisitor.java   Source Code and License 5 votes vote down vote up
/**
 * The compiler does not always preserve the concrete syntax of annotated array dimensions, and
 * mixed-notation array dimensions. Use look-ahead to preserve the original syntax.
 * <p>
 * <p>It is assumed that any number of regular dimension specifiers ({@code []} with no
 * annotations) may be present in the input.
 *
 * @param dimExpressions an ordered list of dimension expressions (e.g. the {@code 0} in {@code
 *                       new int[0]}
 * @param annotations    an ordered list of type annotations grouped by dimension (e.g. {@code
 *                       [[@A, @B], [@C]]} for {@code int @A [] @B @C []}
 */
private void maybeAddDims(
        Deque<ExpressionTree> dimExpressions, Deque<List<AnnotationTree>> annotations) {
    boolean lastWasAnnotation = false;
    while (builder.peekToken().isPresent()) {
        switch (builder.peekToken().get()) {
            case "@":
                if (annotations.isEmpty()) {
                    return;
                }
                List<AnnotationTree> dimAnnotations = annotations.removeFirst();
                if (dimAnnotations.isEmpty()) {
                    continue;
                }
                builder.breakToFill(" ");
                visitAnnotations(dimAnnotations, BreakOrNot.NO, BreakOrNot.NO);
                lastWasAnnotation = true;
                break;
            case "[":
                if (lastWasAnnotation) {
                    builder.breakToFill(" ");
                } else {
                    builder.breakToFill();
                }
                token("[");
                if (!builder.peekToken().get().equals("]")) {
                    scan(dimExpressions.removeFirst(), null);
                }
                token("]");
                lastWasAnnotation = false;
                break;
            default:
                return;
        }
    }
}
 
Example 42
Project: lams   File: HandlerParser.java   Source Code and License 5 votes vote down vote up
static HandlerWrapper parse(final String string, final Map<String, HandlerBuilder> builders, final ExchangeAttributeParser attributeParser) {

        //shunting yard algorithm
        //gets rid or parentheses and fixes up operator ordering
        Deque<Token> tokens = tokenize(string);
        return parseBuilder(string, tokens.pop(), tokens, builders, attributeParser);

    }
 
Example 43
Project: alfresco-repository   File: TransformerDebug.java   Source Code and License 5 votes vote down vote up
private void pop(Call callType, boolean suppressFinish)
{
    Deque<Frame> ourStack = ThreadInfo.getStack();
    if (!ourStack.isEmpty())
    {
        Frame frame = ourStack.peek();

        if ((frame.callType == callType) ||
            (frame.callType == Call.AVAILABLE_AND_TRANSFORM && callType == Call.AVAILABLE))
        {
            int size = ourStack.size();
            String ms = ms(System.currentTimeMillis() - frame.start);

            logInfo(frame, size, ms);
            
            boolean firstLevel = size == 1;
            if (!suppressFinish && (firstLevel || logger.isTraceEnabled()))
            {
                log(FINISHED_IN + ms +
                    (frame.callType == Call.AVAILABLE ? " Transformer NOT called" : "") +
                    (firstLevel ? "\n" : ""), 
                    firstLevel);
            }
            
            setDebugOutput(frame.origDebugOutput);
            ourStack.pop();
        }
    }
}
 
Example 44
Project: kafka-0.11.0.0-src-with-comment   File: InFlightRequests.java   Source Code and License 5 votes vote down vote up
/**
 * Return true if there is no in-flight request and false otherwise
 */
public boolean isEmpty() {
    for (Deque<NetworkClient.InFlightRequest> deque : this.requests.values()) {
        if (!deque.isEmpty())
            return false;
    }
    return true;
}
 
Example 45
Project: CustomWorldGen   File: ModelBakery.java   Source Code and License 5 votes vote down vote up
private void addModelParentLocation(Deque<ResourceLocation> p_188633_1_, Set<ResourceLocation> p_188633_2_, ModelBlock p_188633_3_)
{
    ResourceLocation resourcelocation = p_188633_3_.getParentLocation();

    if (resourcelocation != null && !p_188633_2_.contains(resourcelocation))
    {
        p_188633_1_.add(resourcelocation);
    }
}
 
Example 46
Project: CodeKatas   File: GoogleGuavaDeckOfCardsAsListTest.java   Source Code and License 5 votes vote down vote up
@Test
public void dealHands()
{
    Deque<Card> jdkShuffled = this.jdkDeck.shuffle(new Random(1));
    Deque<Card> ggShuffled = this.ggDeck.shuffle(new Random(1));
    List<Set<Card>> jdkHands = this.jdkDeck.dealHands(jdkShuffled, 5, 5);
    List<Set<Card>> ggHands = this.ggDeck.dealHands(ggShuffled, 5, 5);
    Assert.assertEquals(jdkHands, ggHands);
}
 
Example 47
Project: Backmemed   File: ModelBakery.java   Source Code and License 5 votes vote down vote up
private void loadModels()
{
    Deque<ResourceLocation> deque = Queues.<ResourceLocation>newArrayDeque();
    Set<ResourceLocation> set = Sets.<ResourceLocation>newHashSet();

    for (ResourceLocation resourcelocation : this.models.keySet())
    {
        set.add(resourcelocation);
        this.addModelParentLocation(deque, set, (ModelBlock)this.models.get(resourcelocation));
    }

    while (!((Deque)deque).isEmpty())
    {
        ResourceLocation resourcelocation1 = (ResourceLocation)deque.pop();

        try
        {
            if (this.models.get(resourcelocation1) != null)
            {
                continue;
            }

            ModelBlock modelblock = this.loadModel(resourcelocation1);
            this.models.put(resourcelocation1, modelblock);
            this.addModelParentLocation(deque, set, modelblock);
        }
        catch (Exception exception)
        {
            LOGGER.warn("In parent chain: {}; unable to load model: \'{}\'", new Object[] {JOINER.join(this.getParentPath(resourcelocation1)), resourcelocation1, exception});
        }

        set.add(resourcelocation1);
    }
}
 
Example 48
Project: azeroth   File: BaseUniqueIDGenerator.java   Source Code and License 5 votes vote down vote up
@Override
public Deque<byte[]> batch(int size) throws GeneratorException {
    Deque<byte[]> stack = new ArrayDeque<>();
    for (int i = 0; i < size; i++) {
        stack.add(generate());
    }
    return stack;
}
 
Example 49
Project: r8   File: Enqueuer.java   Source Code and License 5 votes vote down vote up
private static void fillWorkList(Deque<DexType> worklist, DexType type) {
  if (type.isInterface()) {
    // We need to check if the method is shadowed by a class that directly implements
    // the interface and go recursively down to the sub interfaces to reach class
    // implementing the interface
    type.forAllImplementsSubtypes(worklist::addLast);
    type.forAllExtendsSubtypes(worklist::addLast);
  } else {
    type.forAllExtendsSubtypes(worklist::addLast);
  }
}
 
Example 50
Project: java-spring-web   File: TracingHandlerInterceptor.java   Source Code and License 5 votes vote down vote up
private Deque<ActiveSpan> getActiveSpanStack(HttpServletRequest request) {
    Deque<ActiveSpan> stack = (Deque<ActiveSpan>) request.getAttribute(ACTIVE_SPAN_STACK);
    if (stack == null) {
        stack = new ArrayDeque<>();
        request.setAttribute(ACTIVE_SPAN_STACK, stack);
    }
    return stack;
}
 
Example 51
Project: hack   File: SlidingWindowMaximum.java   Source Code and License 5 votes vote down vote up
public int[] maxSlidingWindow(int[] nums, int k) {
    if (k == 0) {
        return new int[0];
    }

    int n = nums.length;

    int[] result = new int[n - k + 1];
    int current = 0;

    Deque<Integer> deque = new ArrayDeque<>();

    for (int i = 0; i < n; i++) {
        while (!deque.isEmpty() && deque.peek() < i - k + 1) {
            deque.poll();
        }

        while(!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) {
            deque.pollLast();
        }

        deque.offer(i);

        if (i >= k - 1) { // allowing sliding window to fit in full initially
            result[current++] = nums[deque.peek()];
        }
    }

    return result;
}
 
Example 52
Project: CustomLintRules   File: AutoPointIdInFileDetector.java   Source Code and License 5 votes vote down vote up
private void findId(Layout layout, String id, Deque<Layout> stack,
                    Map<Layout, Occurrence> occurrences, Set<Layout> seen) {
    seen.add(layout);

    Set<String> layoutIds = layout.getIds();
    if (layoutIds != null && layoutIds.contains(id)) {
        StringBuilder path = new StringBuilder(80);

        if (!stack.isEmpty()) {
            Iterator<Layout> iterator = stack.descendingIterator();
            while (iterator.hasNext()) {
                path.append(iterator.next().getDisplayName());
                path.append(" => ");
            }
        }
        path.append(layout.getDisplayName());
        path.append(" defines ");
        path.append(id);

        assert occurrences.get(layout) == null : id + ',' + layout;
        occurrences.put(layout, new Occurrence(layout.getFile(), null, path.toString()));
    }

    List<Layout> includes = layout.getIncludes();
    if (includes != null) {
        stack.push(layout);
        for (Layout included : includes) {
            if (!seen.contains(included)) {
                findId(included, id, stack, occurrences, seen);
            }
        }
        Layout visited = stack.pop();
        assert visited == layout;
    }
}
 
Example 53
Project: guava-mock   File: ForwardingDequeTest.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public void testForwarding() {
  new ForwardingWrapperTester()
      .testForwarding(Deque.class, new Function<Deque, Deque>() {
        @Override public Deque apply(Deque delegate) {
          return wrap(delegate);
        }
      });
}
 
Example 54
Project: kafka-0.11.0.0-src-with-comment   File: ProducerBatchTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSplitPreservesMagicAndCompressionType() {
    for (byte magic : Arrays.asList(MAGIC_VALUE_V0, MAGIC_VALUE_V1, MAGIC_VALUE_V2)) {
        for (CompressionType compressionType : CompressionType.values()) {
            if (compressionType == CompressionType.NONE && magic < MAGIC_VALUE_V2)
                continue;

            MemoryRecordsBuilder builder = MemoryRecords.builder(ByteBuffer.allocate(1024), magic,
                    compressionType, TimestampType.CREATE_TIME, 0L);

            ProducerBatch batch = new ProducerBatch(new TopicPartition("topic", 1), builder, now);
            while (true) {
                FutureRecordMetadata future = batch.tryAppend(now, "hi".getBytes(), "there".getBytes(),
                        Record.EMPTY_HEADERS, null, now);
                if (future == null)
                    break;
            }

            Deque<ProducerBatch> batches = batch.split(512);
            assertTrue(batches.size() >= 2);

            for (ProducerBatch splitProducerBatch : batches) {
                assertEquals(magic, splitProducerBatch.magic());
                assertTrue(splitProducerBatch.isSplitBatch());

                for (RecordBatch splitBatch : splitProducerBatch.records().batches()) {
                    assertEquals(magic, splitBatch.magic());
                    assertEquals(0L, splitBatch.baseOffset());
                    assertEquals(compressionType, splitBatch.compressionType());
                }
            }
        }
    }
}
 
Example 55
Project: openjdk-jdk10   File: GraphEncoder.java   Source Code and License 5 votes vote down vote up
protected static void pushToWorklist(Node expectedNode, Node actualNode, NodeMap<Node> nodeMapping, Deque<Pair<Node, Node>> workList) {
    nodeMapping.set(expectedNode, actualNode);
    if (expectedNode instanceof AbstractEndNode) {
        /* To ensure phi nodes have been added, we handle everything before block ends. */
        workList.addLast(Pair.create(expectedNode, actualNode));
    } else {
        workList.addFirst(Pair.create(expectedNode, actualNode));
    }
}
 
Example 56
Project: myfaces-trinidad   File: StyleSheetDocument.java   Source Code and License 5 votes vote down vote up
private StyleNode _resolveIncludedProperties(
  StyleContext           context,
  boolean                forIconNode,
  StyleSheetList         styleSheets,
  Map<String, StyleNode> resolvedStyles,
  Map<String, StyleNode> resolvedNamedStyles,
  Deque<String>          includesStack, 
  Deque<String>          namedIncludesStack,
  IncludePropertyNode    includeProperty)
{
  String includeID = null;
  boolean includeIsNamed = false;
  
  if (includeProperty.getName() != null)
  {
    includeID = includeProperty.getName();
    includeIsNamed = true;
  }
  else
  {
    includeID = includeProperty.getSelector();
  }
  
  // for include styles we do not support selectors and properties within client rules
  // this is because, we cannot determine which selector or property should be applied,
  // as the client rules are resolved on the browser.
  // so we look for a selector or property without any client rules.
  // thus pass null for cacheId and clientRule
  StyleNode resolvedNode = _resolveStyleNode(context, forIconNode,
                                         styleSheets,
                                         resolvedStyles,
                                         resolvedNamedStyles,
                                         includesStack,
                                         namedIncludesStack,
                                         includeID,
                                         includeIsNamed,
                                         null,
                                         null);
  return resolvedNode;
}
 
Example 57
Project: SoftUni   File: p01_MachingBrackets.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String input = scan.nextLine();
    Deque<Integer> stack = new ArrayDeque();

    for (int i = 0; i < input.length(); i++) {
        if(input.charAt(i) == '('){
            stack.push(i);
        } else if(input.charAt(i) == ')'){
            int start = stack.pop();
            String cont = input.substring(start, i + 1);
            System.out.println(cont);
        }
    }
}
 
Example 58
Project: alfresco-repository   File: TransformerLog.java   Source Code and License 5 votes vote down vote up
@Override
protected void addOrModify(Deque<String> entries, Object message)
{
    StringBuilder sb = new StringBuilder();
    sb.append(TransformerLogger.DATE_FORMAT.format(new Date()));
    sb.append(' ');
    sb.append(message);

    entries.add(sb.toString());
}
 
Example 59
Project: hadoop-oss   File: TestFilterExpression.java   Source Code and License 5 votes vote down vote up
@Test(timeout = 1000)
public void addChildren() {
  @SuppressWarnings("unchecked")
  Deque<Expression> expressions = mock(Deque.class);
  test.addChildren(expressions);
  verify(expr).addChildren(expressions);
  verifyNoMoreInteractions(expr);
}
 
Example 60
Project: hadoop-oss   File: TestFilterExpression.java   Source Code and License 5 votes vote down vote up
@Test(timeout = 1000)
public void addArguments() {
  @SuppressWarnings("unchecked")
  Deque<String> args = mock(Deque.class);
  test.addArguments(args);
  verify(expr).addArguments(args);
  verifyNoMoreInteractions(expr);
}