下面列出了javax.servlet.ServletResponseWrapper#java.util.Deque 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
@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));
}
}
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;
}
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);
}
}
}
@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());
}
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);
}
}
@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);
}
@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");
}
};
}
@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());
}
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;
}
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;
}
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;
}
@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);
}
@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);
}
@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);
}
@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);
}
}
}
/**
* 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;
}
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;
}
/**
* 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);
}
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;
}
}
@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);
}
}
/** 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));
}
}
}
}
}
@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;
}
/**
* {@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;
}
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 );
}
@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);
}
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);
}
/** 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;
}
/**
* 不修改链表,借助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);
}
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);
}
}