@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); }
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; }
/** * 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; }
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); } }
/** * 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; } }
/** * 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(); }
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); } }
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; }
@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)) { } }
@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); }
@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); }
@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)); }
@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)) { } }
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() ); } } }
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; }
@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); }
@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); }
/** * 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; } }; }
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); }
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; }
@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)); }
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); }
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; }
/** * 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)); }
@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); }
@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()); }
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); }
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; }
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<>()); } } }
@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()); }
/** * 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); } }
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(); }
private void release(DateFormat format, Locale locale) { synchronized( mutex ) { Deque<DateFormat> sp = getSubpool(locale); if( sp.size() >= poolSizePerLocale ) { sp.addFirst(format); } } }
@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"); } }
/** * 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); } }
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)); }
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); } }
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 }
@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()]); }