java.util.Deque Java Examples
The following examples show how to use
java.util.Deque.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UnreachableCodeEliminator.java From JAADAS with GNU General Public License v3.0 | 6 votes |
private <T> Set<T> reachable(T first, DirectedGraph<T> g) { if ( first == null || g == null ) { return Collections.<T>emptySet(); } Set<T> visited = new HashSet<T>(g.size()); Deque<T> q = new ArrayDeque<T>(); q.addFirst(first); do { T t = q.removeFirst(); if ( visited.add(t) ) { q.addAll(g.getSuccsOf(t)); } } while (!q.isEmpty()); return visited; }
Example #2
Source File: InFlightConfigReceiver.java From aion with MIT License | 6 votes |
private void rollback(Deque<InFlightConfigChangeResult> steps, CfgAion newCfg) throws RollbackException { LOG.info("Trying to rollback. Undo steps are: {}", steps.toString()); List<InFlightConfigChangeException> exceptions = new LinkedList<>(); while (!steps.isEmpty()) { InFlightConfigChangeResult result = steps.pop(); try { LOG.trace("About to call undo for application result {}", result); result.getApplier().undo(activeCfg, newCfg); } catch (InFlightConfigChangeException ex) { exceptions.add(ex); LOG.error( String.format("Rollback error while trying to undo %s", result.toString())); } } if (!exceptions.isEmpty()) { throw new RollbackException("Rollback had errors", exceptions); } }
Example #3
Source File: SuccessCallbackWithTracingTest.java From wingtips with Apache License 2.0 | 6 votes |
@DataProvider(value = { "true", "false" }) @Test public void current_thread_info_constructor_sets_fields_as_expected(boolean useStaticFactory) { // given Tracer.getInstance().startRequestWithRootSpan("request-" + UUID.randomUUID().toString()); Deque<Span> spanStackMock = Tracer.getInstance().getCurrentSpanStackCopy(); Map<String, String> mdcInfoMock = MDC.getCopyOfContextMap(); // when SuccessCallbackWithTracing instance = (useStaticFactory) ? withTracing(successCallbackMock) : new SuccessCallbackWithTracing(successCallbackMock); // then assertThat(instance.origSuccessCallback).isSameAs(successCallbackMock); assertThat(instance.spanStackForExecution).isEqualTo(spanStackMock); assertThat(instance.mdcContextMapForExecution).isEqualTo(mdcInfoMock); }
Example #4
Source File: BlockProcessor.java From jadx with Apache License 2.0 | 6 votes |
private static void computeDominanceFrontier(MethodNode mth) { for (BlockNode exit : mth.getExitBlocks()) { exit.setDomFrontier(EMPTY); } List<BlockNode> domSortedBlocks = new ArrayList<>(mth.getBasicBlocks().size()); Deque<BlockNode> stack = new LinkedList<>(); stack.push(mth.getEnterBlock()); while (!stack.isEmpty()) { BlockNode node = stack.pop(); for (BlockNode dominated : node.getDominatesOn()) { stack.push(dominated); } domSortedBlocks.add(node); } Collections.reverse(domSortedBlocks); for (BlockNode block : domSortedBlocks) { try { computeBlockDF(mth, block); } catch (Exception e) { throw new JadxRuntimeException("Failed compute block dominance frontier", e); } } }
Example #5
Source File: Help.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
@Override public void execute(Deque<String> options) throws UserSyntaxException, UserDataException { if (options.isEmpty()) { Command.displayHelp(); return; } ensureMaxArgumentCount(options, 1); String commandName = options.remove(); Command c = Command.valueOf(commandName); if (c == null) { throw new UserDataException("unknown command '" + commandName + "'"); } println(c.getTitle()); println(); c.displayUsage(System.out); }
Example #6
Source File: DagChecker.java From sql-layer with GNU Affero General Public License v3.0 | 6 votes |
private boolean tryAdd(Set<? extends T> roots, Graph<T, Pair> graph, Set<T> knownNodes, CycleDetector<T, Pair> cycleDetector, Deque<T> nodePath) { for (T node : roots) { nodePath.addLast(node); graph.addVertex(node); if (knownNodes.add(node)) { Set<? extends T> nodesFrom = nodesFrom(node); for (T from : nodesFrom) { graph.addVertex(from); Pair edge = new Pair(from, node); graph.addEdge(from, node, edge); nodePath.addLast(from); if (cycleDetector.detectCycles()) return false; nodePath.removeLast(); } if (!tryAdd(nodesFrom, graph, knownNodes, cycleDetector, nodePath)) return false; } nodePath.removeLast(); } return true; }
Example #7
Source File: SPARQLSyntaxComplianceTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
private static Object[][] getTestData() { List<Object[]> tests = new ArrayList<>(); Deque<String> manifests = new ArrayDeque<>(); manifests.add( SPARQLSyntaxComplianceTest.class.getClassLoader() .getResource("testcases-sparql-1.1-w3c/manifest-all.ttl") .toExternalForm()); while (!manifests.isEmpty()) { String pop = manifests.pop(); SPARQLSyntaxManifest manifest = new SPARQLSyntaxManifest(pop); tests.addAll(manifest.tests); manifests.addAll(manifest.subManifests); } Object[][] result = new Object[tests.size()][6]; tests.toArray(result); return result; }
Example #8
Source File: IvyNode.java From ant-ivy with Apache License 2.0 | 6 votes |
Boolean doesExclude(ModuleDescriptor md, String rootModuleConf, String[] moduleConfs, DependencyDescriptor dd, Artifact artifact, Deque<IvyNode> callersStack) { // artifact is excluded if it match any of the exclude pattern for this dependency... if (directlyExcludes(md, moduleConfs, dd, artifact)) { return Boolean.TRUE; } // ... or if it is excluded by all its callers IvyNode c = getData().getNode(md.getModuleRevisionId()); if (c != null) { if (callersStack.contains(c)) { // a circular dependency, we cannot be conclusive here return null; } return c.doesCallersExclude(rootModuleConf, artifact, callersStack); } return Boolean.FALSE; }
Example #9
Source File: TracerTest.java From wingtips with Apache License 2.0 | 6 votes |
@Test public void registerWithThread_should_do_nothing_if_copy_of_same_stack_is_passed_in() { // given Tracer tracer = Tracer.getInstance(); tracer.startRequestWithRootSpan("foo"); Span subspan = tracer.startSubSpan("bar", SpanPurpose.LOCAL_ONLY); assertThat(MDC.get(SpanFieldForLoggerMdc.TRACE_ID.mdcKey)).isEqualTo(subspan.getTraceId()); // when Deque<Span> spanStack = getSpanStackThreadLocal().get(); tracer.registerWithThread(new LinkedList<>(spanStack)); // then assertThat(getSpanStackThreadLocal().get()).isEqualTo(spanStack); assertThat(MDC.get(SpanFieldForLoggerMdc.TRACE_ID.mdcKey)).isEqualTo(subspan.getTraceId()); }
Example #10
Source File: AsyncWingtipsHelperTest.java From wingtips with Apache License 2.0 | 6 votes |
@DataProvider(value = { "true", "false" }) @Test public void biConsumerWithTracing_separate_args_works_as_expected(boolean useStaticMethod) { // given Pair<Deque<Span>, Map<String, String>> setupInfo = generateTracingInfo(); // when BiConsumer result = (useStaticMethod) ? biConsumerWithTracing(biConsumerMock, setupInfo.getLeft(), setupInfo.getRight()) : DEFAULT_IMPL.biConsumerWithTracing(biConsumerMock, setupInfo.getLeft(), setupInfo.getRight()); // then verifyBiConsumerWithTracing(result, biConsumerMock, setupInfo.getLeft(), setupInfo.getRight()); }
Example #11
Source File: Exec.java From examples with Apache License 2.0 | 6 votes |
@Override public void addArguments(Deque<String> args) { while(!args.isEmpty()) { String arg = args.pop(); if("+".equals(arg) && !getArguments().isEmpty() && "{}".equals(getArguments().get(getArguments().size() - 1))) { // + terminates the arguments if the previous argument was {} setBatch(true); break; } else if(";".equals(arg)) { // ; terminates the arguments break; } else { addArgument(arg); } } }
Example #12
Source File: TransformerDebugLog.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
@Override protected void addOrModify(Deque<DebugEntry> entries, Object message) { String msg = (String)message; String requestId = getRequestId(msg); if (requestId != null) { Iterator<DebugEntry> iterator = entries.descendingIterator(); while (iterator.hasNext()) { DebugEntry entry = iterator.next(); if (requestId.equals(entry.requestId)) { entry.addLine(msg); return; } } entries.add(new DebugEntry(requestId, msg)); } }
Example #13
Source File: Oauth2ServiceGetHandler.java From light-oauth2 with Apache License 2.0 | 6 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { IMap<String, Service> services = CacheStartupHookProvider.hz.getMap("services"); Deque<String> serviceIdDeque = exchange.getQueryParameters().get("serviceId"); String serviceId = serviceIdDeque == null? "%" : serviceIdDeque.getFirst() + "%"; int page = Integer.valueOf(exchange.getQueryParameters().get("page").getFirst()) - 1; Deque<String> pageSizeDeque = exchange.getQueryParameters().get("pageSize"); int pageSize = pageSizeDeque == null? 10 : Integer.valueOf(pageSizeDeque.getFirst()); LikePredicate likePredicate = new LikePredicate("serviceId", serviceId); PagingPredicate pagingPredicate = new PagingPredicate(likePredicate, new ServiceComparator(), pageSize); pagingPredicate.setPage(page); Collection<Service> values = services.values(pagingPredicate); exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "application/json"); exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(values)); processAudit(exchange); }
Example #14
Source File: Solution.java From DailyCodingProblem with GNU Lesser General Public License v3.0 | 6 votes |
private static boolean find(int[] arr, int i, int k, Deque<Integer> stack) { if (k == 0) return true; if (k < 0 || i >= arr.length) return false; for (; i < arr.length; i++) { stack.push(arr[i]); if (find(arr, i + 1, k - arr[i], stack)) return true; stack.pop(); } return false; }
Example #15
Source File: Parser.java From turbine with Apache License 2.0 | 6 votes |
/** * Given a base {@code type} and some number of {@code extra} c-style array dimension specifiers, * construct a new array type. * * <p>For reasons that are unclear from the spec, {@code int @A [] x []} is equivalent to {@code * int [] @A [] x}, not {@code int @A [] [] x}. */ private Type extraDims(Type ty) { ImmutableList<Anno> annos = maybeAnnos(); if (!annos.isEmpty() && token != Token.LBRACK) { // orphaned type annotations throw error(token); } Deque<ImmutableList<Anno>> extra = new ArrayDeque<>(); while (maybe(Token.LBRACK)) { eat(Token.RBRACK); extra.push(annos); annos = maybeAnnos(); } ty = extraDims(ty, extra); return ty; }
Example #16
Source File: Slf4jServiceActivator.java From wildfly-core with GNU Lesser General Public License v2.1 | 6 votes |
@Override protected HttpHandler getHttpHandler() { return new HttpHandler() { @Override public void handleRequest(final HttpServerExchange exchange) { final Map<String, Deque<String>> params = exchange.getQueryParameters(); String msg = DEFAULT_MESSAGE; if (params.containsKey("msg")) { msg = getFirstValue(params, "msg"); } // Log all levels LOGGER.trace(msg); LOGGER.debug(msg); LOGGER.info(msg); LOGGER.warn(msg); LOGGER.error(msg); //LOGGER.fatal(msg); exchange.getResponseSender().send("Response sent"); } }; }
Example #17
Source File: TestAnd.java From hadoop with Apache License 2.0 | 6 votes |
@Test(timeout = 1000) public void testFailSecond() throws IOException { And and = new And(); PathData pathData = mock(PathData.class); Expression first = mock(Expression.class); when(first.apply(pathData, -1)).thenReturn(Result.PASS); 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); verify(second).apply(pathData, -1); verifyNoMoreInteractions(first); verifyNoMoreInteractions(second); }
Example #18
Source File: ProxyModelAssociationsAdapter.java From dsl-devkit with Eclipse Public License 1.0 | 5 votes |
@Override public Map<EObject, Deque<EObject>> getInferredModelToSourceMap() { DirectLinkingResourceStorageLoadable loadable = (DirectLinkingResourceStorageLoadable) ((DirectLinkingResourceStorageFacade) resource.getResourceStorageFacade()).getOrCreateResourceStorageLoadable(resource); try { uninstall(); loadable.loadIntoResource(resource, ResourceLoadMode.ONLY_ASSOCIATIONS); } catch (IOException e) { throw new WrappedException(e); } return ((InferredModelAssociator.Adapter) EcoreUtil.getAdapter(resource.eAdapters(), InferredModelAssociator.Adapter.class)).getInferredModelToSourceMap(); }
Example #19
Source File: TransformerDebug.java From alfresco-repository with GNU Lesser General Public License v3.0 | 5 votes |
/** * Log a message prefixed with the current transformation reference * and include a exception, suppressing the stack trace if repeated * as we return up the stack of transformers. * @param message */ public void debug(String message, Throwable t) { if (isEnabled()) { // Trim messages of the form: "Failed... : \n reader:...\n writer:..." String msg = t.getMessage(); if (msg != null) { int i = msg.indexOf(": \n"); if (i != -1) { msg = msg.substring(0, i); } log(message + ' ' + msg); } else { log(message); } Deque<Frame> ourStack = ThreadInfo.getStack(); if (!ourStack.isEmpty()) { Frame frame = ourStack.peek(); frame.setFailureReason(message +' '+ getRootCauseMessage(t)); } } }
Example #20
Source File: AsyncWingtipsHelperJava7Test.java From wingtips with Apache License 2.0 | 5 votes |
private Pair<Deque<Span>, Map<String, String>> generateTracingInfo() { resetTracing(); Tracer.getInstance().startRequestWithRootSpan("someSpan"); Pair<Deque<Span>, Map<String, String>> result = Pair.of( Tracer.getInstance().getCurrentSpanStackCopy(), (Map<String, String>)new HashMap<>(MDC.getCopyOfContextMap()) ); resetTracing(); return result; }
Example #21
Source File: Navigator.java From magellan with Apache License 2.0 | 5 votes |
/** * Navigates from the current screen back to the screen in this Navigator's back stack immediately before the * Screen parameter. Screens in between the current screen and the Screen parameter on the back stack are removed. * If the Screen parameter is not present in this Navigator's back stack, this method is equivalent to * {@link #goBackToRoot(NavigationType) goBackToRoot(NavigationType)} * * @param screen screen to navigate back to through this Navigator's back stack * @param navigationType determines how the navigation event is animated */ public void goBackBefore(final Screen screen, NavigationType navigationType) { navigate(new HistoryRewriter() { @Override public void rewriteHistory(Deque<Screen> history) { checkArgument(history.contains(screen), "Can't go back past a screen that isn't in history."); while (history.size() > 1) { if (history.pop() == screen) { break; } } } }, navigationType, BACKWARD); }
Example #22
Source File: LinkedDequeTest.java From multiway-pool with Apache License 2.0 | 5 votes |
@Test(dataProvider = "warmedDeque") public void pollLast_whenPopulated(Deque<SimpleLinkedValue> deque) { SimpleLinkedValue last = deque.peekLast(); assertThat(deque.pollLast(), is(last)); assertThat(deque, hasSize((int) capacity() - 1)); assertThat(deque.contains(last), is(false)); }
Example #23
Source File: Solution.java From LeetCode-Solution-in-Good-Style with Apache License 2.0 | 5 votes |
public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new ArrayList<>(); if (root == null) { return res; } // Java 文档中 Stack 类建议使用 Deque 代替 Stack,注意:只使用栈的相关接口 Deque<Integer> path = new ArrayDeque<>(); pathSum(root, sum, path, res); return res; }
Example #24
Source File: PathTestCase.java From quarkus-http with Apache License 2.0 | 5 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { exchange.addResponseHeader(MATCHED, matched); exchange.addResponseHeader(PATH, exchange.getRelativePath()); for(Map.Entry<String, Deque<String>> param : exchange.getQueryParameters().entrySet()) { exchange.setResponseHeader(param.getKey(), param.getValue().getFirst()); } exchange.endExchange(); }
Example #25
Source File: Summary.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
@Override public void execute(Deque<String> options) throws UserSyntaxException, UserDataException { ensureMaxArgumentCount(options, 1); Path p = getJFRInputFile(options); try { printInformation(p); } catch (IOException e) { couldNotReadError(p, e); } }
Example #26
Source File: SupplierWithTracingTest.java From wingtips with Apache License 2.0 | 5 votes |
@DataProvider(value = { "true | true | true", "true | false | true", "false | true | true", "false | false | true", "true | true | false", "true | false | false", "false | true | false", "false | false | false", }, splitBy = "\\|") @Test public void pair_constructor_sets_fields_as_expected( boolean nullSpanStack, boolean nullMdcInfo, boolean useStaticFactory ) { // given Deque<Span> spanStackMock = (nullSpanStack) ? null : mock(Deque.class); Map<String, String> mdcInfoMock = (nullMdcInfo) ? null : mock(Map.class); // when SupplierWithTracing instance = (useStaticFactory) ? withTracing(supplierMock, Pair.of(spanStackMock, mdcInfoMock)) : new SupplierWithTracing(supplierMock, Pair.of(spanStackMock, mdcInfoMock) ); // then assertThat(instance.origSupplier).isSameAs(supplierMock); assertThat(instance.spanStackForExecution).isEqualTo(spanStackMock); assertThat(instance.mdcContextMapForExecution).isEqualTo(mdcInfoMock); }
Example #27
Source File: AddAndRemoveOnListAdapterOutsideOfJavaScriptContextTest.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
@Test public void testPop() throws ScriptException { final Deque<Object> l = getListAdapter(); assertEquals(l.removeLast(), 4); assertEquals(l.size(), 3); assertEquals(l.getLast(), 3); }
Example #28
Source File: Solution150.java From LeetCodeSolution with Apache License 2.0 | 5 votes |
/** * 1.About Complexity * 1.1 Time Complexity is O(n) * 1.2 Space Complexity is O(n) * 2.how I solve * 2.1 use a stack to cache operate result * 2.2 circulate from head to tail,there have two condition * 2.2.1 current string is a integer,add current element to stack * 2.2.2 current string is a operator,take two num from stack and perform corresponding operation, * add operate result to stack * 2.3 return stack's top element * 3.About submit record * 3.1 20ms and 39.1MB memory in LeetCode China * 3.2 5ms and 35.8MB memory in LeetCode * 4.Q&A * @param tokens * @return */ public int evalRPNByStack(String[] tokens) { Deque<String> stack=new LinkedList<>(); for(int i=0,length=tokens.length;i<length;i++){ if((tokens[i].charAt(0)>='0'&&tokens[i].charAt(0)<='9')||tokens[i].length()>1){ stack.addFirst(tokens[i]); } else{ int num=Integer.valueOf(stack.removeFirst()); int temp=Integer.valueOf(stack.removeFirst()); switch(tokens[i]){ case "+":{ temp+=num; break; } case "-":{ temp-=num; break; } case "*":{ temp*=num; break; } case "/":{ temp/=num; break; } } stack.addFirst(Integer.toString(temp)); } } return Integer.valueOf(stack.removeFirst()); }
Example #29
Source File: GraphEncoder.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
protected static void verifyPhi(PhiNode expectedPhi, PhiNode actualPhi, NodeMap<Node> nodeMapping, Deque<Pair<Node, Node>> workList) { AbstractMergeNode expectedMergeNode = expectedPhi.merge(); AbstractMergeNode actualMergeNode = actualPhi.merge(); assert actualMergeNode == nodeMapping.get(expectedMergeNode); for (EndNode expectedEndNode : expectedMergeNode.ends) { EndNode actualEndNode = (EndNode) nodeMapping.get(expectedEndNode); if (actualEndNode != null) { ValueNode expectedPhiInput = expectedPhi.valueAt(expectedEndNode); ValueNode actualPhiInput = actualPhi.valueAt(actualEndNode); verifyNodeEqual(expectedPhiInput, actualPhiInput, nodeMapping, workList, false); } } }
Example #30
Source File: DefaultApplicationEngine.java From ldp4j with Apache License 2.0 | 5 votes |
private <T> void initializeComponent(T object, Deque<? super T> initializedComponents) throws ComponentLifecycleException { try { LifecycleManager.init(object); initializedComponents.push(object); } catch (LifecycleException e) { throw new ComponentLifecycleException(object,e); } }