Java Code Examples for java.util.Deque

The following examples show how to use java.util.Deque. These examples are extracted from open source projects. 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
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 2
@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 3
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 4
Source Project: jadx   Source File: BlockProcessor.java    License: Apache License 2.0 6 votes vote down vote up
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 Project: wingtips   Source File: TracerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 6
Source Project: aion   Source File: InFlightConfigReceiver.java    License: MIT License 6 votes vote down vote up
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 7
Source Project: light-oauth2   Source File: Oauth2ServiceGetHandler.java    License: Apache License 2.0 6 votes vote down vote up
@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 8
@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 9
Source Project: wingtips   Source File: AsyncWingtipsHelperTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 10
Source Project: ant-ivy   Source File: IvyNode.java    License: Apache License 2.0 6 votes vote down vote up
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 11
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 12
Source Project: sql-layer   Source File: DagChecker.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 13
Source Project: TencentKona-8   Source File: Help.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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 14
Source Project: wingtips   Source File: SuccessCallbackWithTracingTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 15
Source Project: hadoop   Source File: TestAnd.java    License: Apache License 2.0 6 votes vote down vote up
@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 16
Source Project: examples   Source File: Exec.java    License: Apache License 2.0 6 votes vote down vote up
@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 17
Source Project: turbine   Source File: Parser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 18
private HttpTestHelper configForAnonymous() throws Exception
{
    final Deque<BaseAction<Void,Exception>> deleteActions = new ArrayDeque<>();

    final Map<String, Object> authAttr = new HashMap<>();
    authAttr.put(AnonymousAuthenticationManager.TYPE, AnonymousAuthenticationManager.PROVIDER_TYPE);

    getHelper().submitRequest("authenticationprovider/myanon","PUT", authAttr, SC_CREATED);

    deleteActions.add(object -> getHelper().submitRequest("authenticationprovider/myanon", "DELETE", SC_OK));

    final Map<String, Object> portAttr = new HashMap<>();
    portAttr.put(Port.TYPE, "HTTP");
    portAttr.put(Port.PORT, 0);
    portAttr.put(Port.AUTHENTICATION_PROVIDER, "myanon");
    portAttr.put(Port.PROTOCOLS, Collections.singleton(Protocol.HTTP));
    portAttr.put(Port.TRANSPORTS, Collections.singleton(Transport.TCP));

    getHelper().submitRequest("port/myport","PUT", portAttr, SC_CREATED);
    deleteActions.add(object -> getHelper().submitRequest("port/myport", "DELETE", SC_OK));

    Map<String, Object> clientAuthPort = getHelper().getJsonAsMap("port/myport");
    int boundPort = Integer.parseInt(String.valueOf(clientAuthPort.get("boundPort")));

    assertThat(boundPort, is(greaterThan(0)));

    _tearDownActions = deleteActions;

    HttpTestHelper helper = new HttpTestHelper(getBrokerAdmin(), null, boundPort);
    helper.setPassword(null);
    helper.setUserName(null);
    return helper;

}
 
Example 19
Source Project: magellan   Source File: Navigator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 20
Source Project: DDMQ   Source File: PullBuffer.java    License: Apache License 2.0 5 votes vote down vote up
public boolean addDelayRequest(DelayRequest delayRequest) {
    Deque<DelayRequest> waitQueue = waitQueueMap.computeIfAbsent(
            getRequestTopic(delayRequest.getRequest()), topic -> new LinkedBlockingDeque<>(MAX_WAIT_REQUEST_QUEUE_SIZE));

    if (!waitQueue.offer(delayRequest)) {
        doCleanWaitQueue(waitQueue);
        return waitQueue.offer(delayRequest);
    } else {
        return true;
    }
}
 
Example 21
Source Project: riposte   Source File: HttpProcessingStateTest.java    License: Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void getOverallRequestSpan_works_as_expected(boolean tracingStackIsNull) {
    // given
    Span firstSpanMock = mock(Span.class);
    Span secondSpanMock = mock(Span.class);
    Deque<Span> tracingStack =
        (tracingStackIsNull)
        ? null
        : new ArrayDeque<>();

    if (!tracingStackIsNull) {
        tracingStack.push(firstSpanMock);
        tracingStack.push(secondSpanMock);
    }

    stateSpy.setDistributedTraceStack(tracingStack);

    // when
    Span result = stateSpy.getOverallRequestSpan();

    // then
    if (tracingStackIsNull) {
        assertThat(result).isNull();
    }
    else {
        assertThat(result).isSameAs(firstSpanMock);
    }
}
 
Example 22
Source Project: beam   Source File: BeamBatchWorker.java    License: Apache License 2.0 5 votes vote down vote up
/** Adds all the side inputs into the sink test so it is available from the DoFn's. */
private void addInputs(BaseTSet sinkTSet, Map<String, CachedTSet> sideInputTSets) {
  if (sideInputTSets.isEmpty()) {
    return;
  }

  TBaseGraph graph = sinkTSet.getTBaseGraph();
  TBase currNode = null;
  Deque<TBase> deque = new ArrayDeque<>();
  deque.add(sinkTSet);
  while (!deque.isEmpty()) {
    currNode = deque.remove();
    deque.addAll(graph.getPredecessors(currNode));
    if (currNode instanceof ComputeTSet) {
      if (((ComputeTSet) currNode).getComputeFunc() instanceof DoFnFunction) {
        Set<String> sideInputKeys =
            ((DoFnFunction) ((ComputeTSet) currNode).getComputeFunc()).getSideInputKeys();
        for (String sideInputKey : sideInputKeys) {
          if (!sideInputTSets.containsKey(sideInputKey)) {
            throw new IllegalStateException("Side input not found for key " + sideInputKey);
          }
          ((ComputeTSet) currNode).addInput(sideInputKey, sideInputTSets.get(sideInputKey));
        }
      }
    }
  }
}
 
Example 23
Source Project: java-uniqueid   Source File: OnePerMillisecondDecorator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Deque<byte[]> batch(int size) throws GeneratorException {
    Deque<byte[]> deck = new ArrayDeque<>();
    for (int i = 0; i < size; i++) {
        deck.add(generate());
    }
    return deck;
}
 
Example 24
Source Project: java-uniqueid   Source File: BaseUniqueIDGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@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 25
Source Project: jolie   Source File: SessionThread.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private void addMessageWaiter( InputOperation operation, SessionMessageFuture future ) {
	Deque< SessionMessageFuture > waitersList = messageWaiters.get( operation.id() );
	if( waitersList == null ) {
		waitersList = new ArrayDeque<>();
		messageWaiters.put( operation.id(), waitersList );
	}
	waitersList.addLast( future );
}
 
Example 26
@Test
public void testInvokePush() throws ScriptException {
    final Deque<Object> l = getListAdapter();
    l.addLast(5);
    assertEquals(l.size(), 5);
    assertEquals(l.getLast(), 5);
    assertEquals(l.getFirst(), 1);
}
 
Example 27
static List<Integer> topologicalSort(GraphDirectedByAdjacencyList g) {
    int[] color = new int[g.getV()];
    Deque<Integer> stack = new ArrayDeque<>(g.getV());
    Deque<Integer> sorted = new ArrayDeque<>(g.getV());

    for (int i = 0; i < g.getV(); i++) {
        if (color[i] != WHITE) continue;
        stack.push(i);

        while (!stack.isEmpty()) {
            int v = stack.peek();

            if (color[v] == WHITE) {
                color[v] = GRAY;
            } else {
                color[v] = BLACK;
                sorted.push(stack.pop());
            }

            for (int w : g.getAdjacencyList().get(v)) {
                if (color[w] == GRAY) {
                    // Found a cycle
                    return new ArrayList<>();
                } else if (color[w] == WHITE) {
                    stack.push(w);
                }
            }
        }
    }

    return new ArrayList<>(sorted);
}
 
Example 28
Source Project: Bats   Source File: RuleQueue.java    License: Apache License 2.0 5 votes vote down vote up
/** Returns whether to skip a match. This happens if any of the
 * {@link RelNode}s have importance zero. */
private boolean skipMatch(VolcanoRuleMatch match) {
  for (RelNode rel : match.rels) {
    Double importance = planner.relImportances.get(rel);
    if (importance != null && importance == 0d) {
      return true;
    }
  }

  // If the same subset appears more than once along any path from root
  // operand to a leaf operand, we have matched a cycle. A relational
  // expression that consumes its own output can never be implemented, and
  // furthermore, if we fire rules on it we may generate lots of garbage.
  // For example, if
  //   Project(A, X = X + 0)
  // is in the same subset as A, then we would generate
  //   Project(A, X = X + 0 + 0)
  //   Project(A, X = X + 0 + 0 + 0)
  // also in the same subset. They are valid but useless.
  final Deque<RelSubset> subsets = new ArrayDeque<>();
  try {
    checkDuplicateSubsets(subsets, match.rule.getOperand(), match.rels);
  } catch (Util.FoundOne e) {
    return true;
  }
  return false;
}
 
Example 29
Source Project: AtOffer   Source File: PrintListFromTailToHead.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 不修改链表,借助Stack的辅助,先顺序放入Stack中,再从Stack中拿出,就是逆序的。
 * 这里用LinkedList就足够了,LinkedList是个链表,在头部插入元素的复杂度是O(1)。
 * @param listNode
 * @return
 */
public ArrayList<Integer> printListFromTailToHead1(ListNode listNode) {
    Deque<Integer> stack = new LinkedList<>();
    while(listNode != null) {
        stack.push(listNode.val);
        listNode = listNode.next;
    }
    return new ArrayList<>(stack);
}
 
Example 30
Source Project: ldp4j   Source File: DefaultApplicationEngine.java    License: Apache License 2.0 5 votes vote down vote up
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);
	}
}