Java Code Examples for java.util.Deque#peek()
The following examples show how to use
java.util.Deque#peek() .
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: RecursiveTap.java From sql-layer with GNU Affero General Public License v3.0 | 6 votes |
public final void in() { Deque<RecursiveTap> tapStack = tapStack(); if (tapStack != null) { // print("in %s", this); long now = System.nanoTime(); inCount++; inNanos = now; if (!tapStack.isEmpty()) { RecursiveTap current = tapStack.peek(); current.lastDuration = now - current.inNanos; current.cumulativeNanos += current.lastDuration; // print(" added %s to %s", current.lastDuration / MILLION, current); } tapStack.push(this); } // else: outermost tap has just been disabled }
Example 2
Source File: Structurizer.java From immutables with Apache License 2.0 | 6 votes |
private static List<Term> parseReturnType(List<Term> signature) { if (signature.isEmpty()) { return ImmutableList.of(); } Deque<Term> terms = new ArrayDeque<>(signature); Term last = terms.removeLast(); if (!last.isWordOrNumber() || last.is("static")) { return ImmutableList.of(); } while (!terms.isEmpty()) { Term t = terms.peek(); if (t.is("<")) { removeTillMatching(terms, "<", ">"); } else if (modifiers.contains(t.toString())) { terms.remove(); } else { // it is possible that there are // no whitespace or comments already removeCommentsAndWhitespace(terms); return ImmutableList.copyOf(terms); } } return ImmutableList.of(); }
Example 3
Source File: LegacyTransformerDebug.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
/** * Called to identify a transformer that cannot be used during working out * available transformers. */ @Deprecated public void unavailableTransformer(ContentTransformer transformer, String sourceMimetype, String targetMimetype, long maxSourceSizeKBytes) { if (isEnabled()) { Deque<Frame> ourStack = ThreadInfo.getStack(); Frame frame = ourStack.peek(); if (frame != null) { Deque<String> isTransformableStack = ThreadInfo.getIsTransformableStack(); String name = (!isTransformableStack.isEmpty()) ? isTransformableStack.getFirst() : getName(transformer); boolean debug = (maxSourceSizeKBytes != 0); if (frame.unavailableTransformers == null) { frame.unavailableTransformers = new TreeSet<UnavailableTransformer>(); } String priority = gePriority(transformer, sourceMimetype, targetMimetype); frame.unavailableTransformers.add(new UnavailableTransformer(name, priority, maxSourceSizeKBytes, debug)); } } }
Example 4
Source File: Line.java From CVScanner with GNU General Public License v3.0 | 6 votes |
public static List<Line> joinSegments(List<Line> segments){ Deque<Line> stack = new ArrayDeque(); stack.push(segments.get(0)); for(int i = 1; i < segments.size(); i++){ Line second = segments.get(i); Line first = stack.peek(); Line merged = first.merge(second); if(merged != null){ stack.pop(); stack.push(merged); } else stack.push(second); } return new ArrayList<>(stack); }
Example 5
Source File: Command.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
protected boolean acceptOption(Deque<String> options, String expected) throws UserSyntaxException { if (expected.equals(options.peek())) { if (options.size() < 2) { throw new UserSyntaxException("missing value for " + options.peek()); } options.remove(); return true; } return false; }
Example 6
Source File: PerfectHashDictionaryTransCard.java From dictomaton with Apache License 2.0 | 5 votes |
private Collection<Integer> sortStatesTopological(final int initialState, CompactIntArray stateNSuffixes) { List<Integer> reverseTopologicalOrder = new ArrayList<>(stateNSuffixes.size()); boolean[] marked = new boolean[stateNSuffixes.size()]; Deque<Integer> stack = new ArrayDeque<>(stateNSuffixes.size()); Deque<Integer> head = new ArrayDeque<>(stateNSuffixes.size()); stack.push(initialState); while (!stack.isEmpty()) { Integer currentState = stack.peek(); if (currentState == head.peek()) { stack.pop(); head.pop(); marked[currentState] = true; reverseTopologicalOrder.add(currentState); } else { head.push(currentState); int trans = d_stateOffsets.get(currentState); int transUpperBound = transitionsUpperBound(currentState); if (trans < transUpperBound) // has children for (; trans < transUpperBound; ++trans) { int nextState = d_transitionTo.get(trans); if (!marked[nextState]) { stack.push(nextState); } } } } return reverseTopologicalOrder; }
Example 7
Source File: ComposedRunnerJobFactory.java From spring-cloud-dataflow with Apache License 2.0 | 5 votes |
private void removeProcessedNodes(Deque<LabelledTaskNode> visitorDeque, SplitNode splitNode) { //remove the nodes of the split since it has already been processed while (visitorDeque.peek() != null && !(visitorDeque.peek().equals(splitNode))) { visitorDeque.pop(); } // pop the SplitNode that marks the beginning of the split from the deque if (visitorDeque.peek() != null) { visitorDeque.pop(); } }
Example 8
Source File: AsyncCompletionHandlerWithTracingAndMdcSupportTest.java From riposte with Apache License 2.0 | 5 votes |
@DataProvider(value = { "NULL", "EMPTY", "HAS_EXISTING_SPAN" }, splitBy = "\\|") @Test public void getTraceForCall_works_as_expected(ExistingSpanStackState existingSpanStackState) { // given Deque<Span> spanStack; Span expectedResult; switch (existingSpanStackState) { case NULL: spanStack = null; expectedResult = null; break; case EMPTY: spanStack = new LinkedList<>(); expectedResult = null; break; case HAS_EXISTING_SPAN: spanStack = handlerSpy.distributedTraceStackToUse; assertThat(spanStack).isNotEmpty(); expectedResult = spanStack.peek(); break; default: throw new IllegalArgumentException("Unhandled state: " + existingSpanStackState.name()); } Whitebox.setInternalState(handlerSpy, "distributedTraceStackToUse", spanStack); // when Span spanForCall = handlerSpy.getSpanForCall(); // then assertThat(spanForCall).isEqualTo(expectedResult); }
Example 9
Source File: Runtime.java From PCDP with Eclipse Public License 1.0 | 5 votes |
/** * Get the current task of the current thread. * @return Currently executing task. */ public static BaseTask currentTask() { final Deque<BaseTask> taskStack = Runtime.threadLocalTaskStack.get(); if (taskStack.isEmpty()) { return null; } else { return taskStack.peek(); } }
Example 10
Source File: PatriciaTreeMutable.java From xodus with Apache License 2.0 | 5 votes |
private boolean deleteImpl(@NotNull final ByteIterable key) { final ByteIterator it = key.iterator(); NodeBase node = root; final Deque<ChildReferenceTransient> stack = new ArrayDeque<>(); for (; ; ) { if (node == null || NodeBase.MatchResult.getMatchingLength(node.matchesKeySequence(it)) < 0) { return false; } if (!it.hasNext()) { break; } final byte nextByte = it.next(); stack.push(new ChildReferenceTransient(nextByte, node)); node = node.getChild(this, nextByte); } if (!node.hasValue()) { return false; } --size; MutableNode mutableNode = node.getMutableCopy(this); ChildReferenceTransient parent = stack.peek(); final boolean hasChildren = mutableNode.hasChildren(); if (!hasChildren && parent != null) { stack.pop(); mutableNode = parent.mutate(this); mutableNode.removeChild(parent.firstByte); if (!mutableNode.hasValue() && mutableNode.getChildrenCount() == 1) { mutableNode.mergeWithSingleChild(this); } } else { mutableNode.setValue(null); if (!hasChildren) { mutableNode.setKeySequence(ByteIterable.EMPTY); } else if (mutableNode.getChildrenCount() == 1) { mutableNode.mergeWithSingleChild(this); } } mutateUp(stack, mutableNode); return true; }
Example 11
Source File: XMLSyntaxSupport.java From netbeans with Apache License 2.0 | 5 votes |
/** * Constructs a path from the root of the document to the given syntax element. * * @param element the element to start with * @return top-down path of SyntaxElements from the document root towards the original SyntaxElement */ public List<SyntaxElement> getPathFromRoot(SyntaxElement element) { Deque<SyntaxElement> stack = new ArrayDeque<>(); SyntaxElement elementRef = element; while (elementRef != null) { if (isEndTag(element) || (isEmptyTag(elementRef) && stack.isEmpty()) || (isStartTag(elementRef) && stack.isEmpty())) { stack.push(elementRef); elementRef = elementRef.getPrevious(); continue; } if (isStartTag(elementRef)) { if (isEndTag(stack.peek())) { SyntaxElement end = stack.peek(); if (end.getNode().getNodeName().equals(elementRef.getNode().getNodeName())) { stack.pop(); } } else { SyntaxElement e = stack.peek(); stack.push(elementRef); } } elementRef = elementRef.getPrevious(); } // reverse: List<SyntaxElement> res = new ArrayList<>(stack.size()); while ((elementRef = stack.poll()) != null) { res.add(elementRef); } return res; }
Example 12
Source File: Context.java From camunda-bpm-platform with Apache License 2.0 | 5 votes |
public static CoreExecutionContext<? extends CoreExecution> getCoreExecutionContext() { Deque<CoreExecutionContext<? extends CoreExecution>> stack = getStack(executionContextStackThreadLocal); if(stack == null || stack.isEmpty()) { return null; } else { return stack.peek(); } }
Example 13
Source File: ConnectionMetaData.java From apm-agent-java with Apache License 2.0 | 4 votes |
@Nullable private HostPort parseAddressList(String connectionUrl) { TreeNode parsedTree = null; Deque<TreeNode> stack = new ArrayDeque<>(); StringBuilder currentValueBuffer = null; for (char c : connectionUrl.toLowerCase().toCharArray()) { switch (c) { case '(': { TreeNode treeNode = new TreeNode(); if (stack.isEmpty()) { parsedTree = treeNode; } else { stack.peek().childNodes.add(treeNode); } stack.push(treeNode); currentValueBuffer = treeNode.name; break; } case ')': { stack.pop(); // continue to do the same as finding `=` } case '=': { if (stack.isEmpty()) { currentValueBuffer = null; } else { currentValueBuffer = stack.peek().value; } break; } default: { if (currentValueBuffer == null) { logger.warn("Failed to parse Oracle DB address list from: {}", connectionUrl); } else { currentValueBuffer.append(c); } } } } HostPort ret = null; if (parsedTree == null) { logger.warn("Failed to parse Oracle DB address list from: {}", connectionUrl); } else { ret = findAddressInTree(connectionUrl, parsedTree); } return ret; }
Example 14
Source File: NonblockingEndpointExecutionHandler.java From riposte with Apache License 2.0 | 4 votes |
protected @Nullable Span findEndpointExecutionSpan(@NotNull HttpProcessingState state) { Deque<Span> spanStack = state.getDistributedTraceStack(); return (spanStack == null) ? null : spanStack.peek(); }
Example 15
Source File: AsyncWingtipsHelperTest.java From wingtips with Apache License 2.0 | 4 votes |
@DataProvider(value = { "true | true | true", "false | true | true", "true | false | true", "false | false | true", "true | true | false", "false | true | false", "true | false | false", "false | false | false", }, splitBy = "\\|") @Test public void linkTracingToCurrentThread_separate_args_works_as_expected(boolean useNullSpanStack, boolean useNullMdcInfo, boolean useStaticMethod) { // given Pair<Deque<Span>, Map<String, String>> info = generateTracingInfo(); info.getRight().put("fooMdcKey", UUID.randomUUID().toString()); Deque<Span> spanStackForLinking = (useNullSpanStack) ? null : info.getLeft(); Map<String, String> mdcInfoForLinking = (useNullMdcInfo) ? null : info.getRight(); resetTracing(); Tracer.getInstance().startRequestWithRootSpan("foo-" + UUID.randomUUID().toString()); Pair<Deque<Span>, Map<String, String>> expectedPreCallInfo = Pair.of( Tracer.getInstance().getCurrentSpanStackCopy(), MDC.getCopyOfContextMap() ); Map<String, String> expectedMdcInfo; // The expected MDC info will vary depending on combinations. if (useNullMdcInfo) { // MDC may still be populated after the call if the span stack is not empty if (useNullSpanStack) expectedMdcInfo = Collections.emptyMap(); else { // MDC will have been populated with tracing info. expectedMdcInfo = new HashMap<>(); Span expectedSpan = spanStackForLinking.peek(); expectedMdcInfo.put(SpanFieldForLoggerMdc.TRACE_ID.mdcKey, expectedSpan.getTraceId()); } } else { // Not null MDC. Start with the MDC info for linking. expectedMdcInfo = new HashMap<>(mdcInfoForLinking); if (useNullSpanStack) { // In the case of a null span stack, the trace info would be removed from the MDC. expectedMdcInfo.remove(SpanFieldForLoggerMdc.TRACE_ID.mdcKey); } } // when Pair<Deque<Span>, Map<String, String>> preCallInfo = (useStaticMethod) ? linkTracingToCurrentThread(spanStackForLinking, mdcInfoForLinking) : DEFAULT_IMPL.linkTracingToCurrentThread(spanStackForLinking, mdcInfoForLinking); Pair<Deque<Span>, Map<String, String>> postCallInfo = Pair.of( Tracer.getInstance().getCurrentSpanStackCopy(), MDC.getCopyOfContextMap() ); // then assertThat(preCallInfo).isEqualTo(expectedPreCallInfo); assertThat(postCallInfo.getLeft()).isEqualTo(spanStackForLinking); if (expectedMdcInfo.isEmpty()) { assertThat(postCallInfo.getRight()).isNullOrEmpty(); } else { assertThat(postCallInfo.getRight()).isEqualTo(expectedMdcInfo); } }
Example 16
Source File: AsyncNettyHelperTest.java From riposte with Apache License 2.0 | 4 votes |
@DataProvider(value = { "true | true", "false | true", "true | false", "false | false", }, splitBy = "\\|") @Test public void unlinkTracingAndMdcFromCurrentThread_separate_args_works_as_expected(boolean useNullSpanStack, boolean useNullMdcInfo) { // given Pair<Deque<Span>, Map<String, String>> info = setupStateWithTracingAndMdcInfo(); info.getRight().put("fooMdcKey", UUID.randomUUID().toString()); Deque<Span> spanStackForLinking = (useNullSpanStack) ? null : info.getLeft(); Map<String, String> mdcInfoForLinking = (useNullMdcInfo) ? null : info.getRight(); // Setup the current thread with something that is not ultimately what we expect so that our assertions are // verifying that the unlinkTracingAndMdcFromCurrentThread method actually did something. resetTracingAndMdc(); Tracer.getInstance().startRequestWithRootSpan("foo-" + UUID.randomUUID().toString()); Map<String, String> expectedMdcInfo; // The expected MDC info will vary depending on combinations. if (useNullMdcInfo) { // MDC may still be populated after the call if the span stack is not empty if (useNullSpanStack) expectedMdcInfo = Collections.emptyMap(); else { // MDC will have been populated with tracing info. expectedMdcInfo = new HashMap<>(); Span expectedSpan = spanStackForLinking.peek(); expectedMdcInfo.put(SpanFieldForLoggerMdc.TRACE_ID.mdcKey, expectedSpan.getTraceId()); } } else { // Not null MDC. Since unlinkTracingAndMdcFromCurrentThread doesn't call registerWithThread when // the span stack is null we don't need to worry about trace ID and span JSON being removed from MDC. // Therefore it should match mdcInfoForLinking exactly. expectedMdcInfo = new HashMap<>(mdcInfoForLinking); } // when AsyncNettyHelper.unlinkTracingAndMdcFromCurrentThread(spanStackForLinking, mdcInfoForLinking); Pair<Deque<Span>, Map<String, String>> postCallInfo = Pair.of( Tracer.getInstance().getCurrentSpanStackCopy(), MDC.getCopyOfContextMap() ); // then assertThat(postCallInfo.getLeft()).isEqualTo(spanStackForLinking); assertThat(postCallInfo.getRight()).isEqualTo(expectedMdcInfo); }
Example 17
Source File: LabelBuilder.java From allure-java with Apache License 2.0 | 4 votes |
LabelBuilder(final Feature feature, final TestCase scenario, final Deque<PickleTag> tags) { final TagParser tagParser = new TagParser(feature, scenario); getScenarioLabels().add(createFeatureLabel(feature.getName())); getScenarioLabels().add(createStoryLabel(scenario.getName())); while (tags.peek() != null) { final PickleTag tag = tags.remove(); final String tagString = tag.getName(); if (tagString.contains(COMPOSITE_TAG_DELIMITER)) { final String[] tagParts = tagString.split(COMPOSITE_TAG_DELIMITER, 2); if (tagParts.length < 2 || Objects.isNull(tagParts[1]) || tagParts[1].isEmpty()) { // skip empty tags, e.g. '@tmsLink=', to avoid formatter errors continue; } final String tagKey = tagParts[0].toUpperCase(); final String tagValue = tagParts[1]; // Handle composite named links if (tagKey.startsWith(PLAIN_LINK + ".")) { tryHandleNamedLink(tagString); continue; } switch (tagKey) { case SEVERITY: getScenarioLabels().add(createSeverityLabel(tagValue.toLowerCase())); break; case TMS_LINK: getScenarioLinks().add(createTmsLink(tagValue)); break; case ISSUE_LINK: getScenarioLinks().add(createIssueLink(tagValue)); break; case PLAIN_LINK: getScenarioLinks().add(createLink(null, tagValue, tagValue, null)); break; default: LOGGER.warn("Composite tag {} is not supported. adding it as RAW", tagKey); getScenarioLabels().add(getTagLabel(tag)); break; } } else if (tagParser.isPureSeverityTag(tag)) { getScenarioLabels().add(createSeverityLabel(tagString.substring(1))); } else if (!tagParser.isResultTag(tag)) { getScenarioLabels().add(getTagLabel(tag)); } } getScenarioLabels().addAll(Arrays.asList( createHostLabel(), createThreadLabel(), createPackageLabel(feature.getName()), createSuiteLabel(feature.getName()), createTestClassLabel(scenario.getName()), createFrameworkLabel("cucumber2jvm"), createLanguageLabel("java") )); }
Example 18
Source File: StacktraceAsserter.java From j2cl with Apache License 2.0 | 4 votes |
private void handleOptionalFrame( Deque<String> expectedFrames, Deque<String> actualFrames, Stacktrace expectedStacktrace, Stacktrace actualStacktrace) { if (expectedFrames.isEmpty()) { if (actualFrames.isEmpty()) { // no more frames we are done return; } // pop one frame of the actual actualFrames.pop(); if (actualFrames.isEmpty()) { // no more frames we are done return; } // still frames on actual but no more on the expected fail(expectedStacktrace, actualStacktrace); } // we might need to skip a frame in the actual frames // Lets see if there are more optional frames int optionalCount = countOptionals(expectedFrames) + 1; // Start skipping frames until we find the next expected frame or run out of optional frames for (int i = 0; i < optionalCount; i++) { if (actualFrames.isEmpty()) { if (expectedFrames.isEmpty()) { // we are good break; } fail(expectedStacktrace, actualStacktrace); } if (expectedFrames.isEmpty()) { actualFrames.pop(); continue; } String actualFrame = actualFrames.peek(); String nextRealFrame = expectedFrames.peek(); if (actualFrame.equals(nextRealFrame)) { // we are good break; } else { actualFrames.pop(); continue; } } }
Example 19
Source File: LabelBuilder.java From allure-java with Apache License 2.0 | 4 votes |
LabelBuilder(final Feature feature, final TestCase scenario, final Deque<String> tags) { final TagParser tagParser = new TagParser(feature, scenario); while (tags.peek() != null) { final String tag = tags.remove(); if (tag.contains(COMPOSITE_TAG_DELIMITER)) { final String[] tagParts = tag.split(COMPOSITE_TAG_DELIMITER, 2); if (tagParts.length < 2 || Objects.isNull(tagParts[1]) || tagParts[1].isEmpty()) { // skip empty tags, e.g. '@tmsLink=', to avoid formatter errors continue; } final String tagKey = tagParts[0].toUpperCase(); final String tagValue = tagParts[1]; // Handle composite named links if (tagKey.startsWith(PLAIN_LINK + ".")) { tryHandleNamedLink(tag); continue; } switch (tagKey) { case SEVERITY: getScenarioLabels().add(ResultsUtils.createSeverityLabel(tagValue.toLowerCase())); break; case TMS_LINK: getScenarioLinks().add(ResultsUtils.createTmsLink(tagValue)); break; case ISSUE_LINK: getScenarioLinks().add(ResultsUtils.createIssueLink(tagValue)); break; case PLAIN_LINK: getScenarioLinks().add(ResultsUtils.createLink(null, tagValue, tagValue, null)); break; default: LOGGER.warn("Composite tag {} is not supported. adding it as RAW", tagKey); getScenarioLabels().add(getTagLabel(tag)); break; } } else if (tagParser.isPureSeverityTag(tag)) { getScenarioLabels().add(ResultsUtils.createSeverityLabel(tag.substring(1))); } else if (!tagParser.isResultTag(tag)) { getScenarioLabels().add(getTagLabel(tag)); } } final String featureName = feature.getName(); final URI uri = scenario.getUri(); getScenarioLabels().addAll(Arrays.asList( createHostLabel(), createThreadLabel(), createFeatureLabel(featureName), createStoryLabel(scenario.getName()), createSuiteLabel(featureName), createTestClassLabel(scenario.getName()), createFrameworkLabel("cucumber4jvm"), createLanguageLabel("java"), createLabel("gherkin_uri", uri.toString()) )); featurePackage(uri.toString(), featureName) .map(ResultsUtils::createPackageLabel) .ifPresent(getScenarioLabels()::add); }
Example 20
Source File: Tracer.java From wingtips with Apache License 2.0 | 2 votes |
/** * The {@link Span} set as the "current" one for this thread. * <p/> * NOTE: If {@link #currentSpanStackThreadLocal} is null or empty for this thread it will try to reconstitute the {@link Span} from the logging {@link org.slf4j.MDC}. * This is useful in some situations, for example async request processing where the thread changes but the MDC is smart enough to transfer the span anyway. * In any case as a caller you don't have to care - you'll just get the {@link Span} appropriate for the caller, or null if one hasn't been set up yet. */ public Span getCurrentSpan() { Deque<Span> spanStack = currentSpanStackThreadLocal.get(); return (spanStack == null) ? null : spanStack.peek(); }