下面列出了java.util.Stack#contains ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Sets the recently changed filters.
*
* @param changeHistory the change history
* @since 3.0
*/
private void setRecentlyChangedFilters(Stack<FilterDescriptor> changeHistory) {
Stack<String> oldestFirstStack= new Stack<String>();
int length= Math.min(changeHistory.size(), MAX_FILTER_MENU_ENTRIES);
for (int i= 0; i < length; i++)
oldestFirstStack.push(changeHistory.pop().getId());
length= Math.min(fLRUFilterIdsStack.size(), MAX_FILTER_MENU_ENTRIES - oldestFirstStack.size());
int NEWEST= 0;
for (int i= 0; i < length; i++) {
String filter= fLRUFilterIdsStack.remove(NEWEST);
if (!oldestFirstStack.contains(filter))
oldestFirstStack.push(filter);
}
fLRUFilterIdsStack= oldestFirstStack;
}
private void walk ( final Stack<DataSourceNode> stack, final DataSourceNode node )
{
if ( stack.contains ( node ) )
{
this.logStream.println ( "Loop found: " + StringHelper.join ( stack, " -> " ) );
// loop found
return;
}
stack.push ( node );
for ( final DataSourceNode ref : node.getReferences () )
{
walk ( stack, ref );
}
stack.pop ();
}
private void calculateReachabilityAndMarkBackEdges(final Stack<RegionNode> aCurrentPath, final RegionNode aNode, final Set<RegionNode> aVisited) {
if (aVisited.add(aNode)) {
aCurrentPath.push(aNode);
for (final Edge<ControlFlowEdgeType, RegionNode> theEdge : aNode.outgoingEdges().collect(Collectors.toList())) {
final RegionNode theTarget = theEdge.targetNode();
if (aCurrentPath.contains(theTarget)) {
// This is a back edge
theEdge.newTypeIs(ControlFlowEdgeType.back);
// We have already visited the back edge, so we do not to continue here
// As this would lead to an endless loop
} else {
// Normal edge
// Continue with graph traversal
calculateReachabilityAndMarkBackEdges(aCurrentPath, theTarget, aVisited);
}
}
aCurrentPath.pop();
}
}
void scanDependencies(Stack<CtPackageReference> path) {
CtPackageReference ref = path.peek();
// return if already scanned
if (scanned.contains(ref)) {
return;
}
scanned.add(ref);
Set<CtPackageReference> refs = packRefs.get(ref);
if (refs != null) {
for (CtPackageReference p : refs) {
if (path.contains(p)) {
List<CtPackageReference> circularPath = new ArrayList<>(
path.subList(path.indexOf(p), path.size()));
circularPath.add(p);
circularPathes.add(circularPath);
break;
} else {
path.push(p);
scanDependencies(path);
path.pop();
}
}
}
}
private static void checkBlock(AMLTestCase block, List<AMLTestCase> blocks, Stack<String> refStack, Stack<AMLAction> actionStack, Set<String> recursiveBlocks, AlertCollector alertCollector) {
for(AMLAction a : block.getActions()) {
if(JavaStatement.value(a.getActionURI()) == JavaStatement.INCLUDE_BLOCK) {
String blockReference = a.getTemplate();
AMLTestCase refBlock = getBlockByReference(blockReference, blocks);
if(refBlock == null) {
alertCollector.add(new Alert(a.getLine(), a.getUID(), a.getReference(), Column.Template.getName(), "Reference to unknown block: " + blockReference));
continue;
}
if(refStack.contains(blockReference)) {
AMLAction firstAction = actionStack.firstElement();
List<String> path = new ArrayList<>(refStack);
path.add(blockReference);
recursiveBlocks.addAll(refStack);
alertCollector.add(new Alert(firstAction.getLine(), a.getUID(), firstAction.getReference(), "Recursion detected: " + StringUtils.join(path, " -> ")));
continue;
}
refStack.push(blockReference);
actionStack.push(a);
checkBlock(refBlock, blocks, refStack, actionStack, recursiveBlocks, alertCollector);
actionStack.pop();
refStack.pop();
}
}
}
/**
* Unregister last registered context associated with current thread - the last context
* has to be passed to validate right usage of ContextProvider.
*/
public static synchronized void unregister(Context requestedContext) {
if (requestedContext == null) {
//DO NOTHING
return;
}
Stack<Context> threadCache = contextCache.get(Thread.currentThread());
if (threadCache == null) {
logger.error("Illegal state in ContextProvider. No cached contexts for current thread " + Thread.currentThread().getName() + ". Requested context: " + requestedContext);
return;
}
if (!threadCache.isEmpty()) {
Context deregisteredContext = threadCache.pop();
if (deregisteredContext != requestedContext) {
if (threadCache.contains(requestedContext)) {
logger.error("Illegal state in ContextProvider. Context, which should be unregistered, is not on top of stack. Recovery is perfomed, context " + deregisteredContext + " is removed from stack.");
while (deregisteredContext != requestedContext) {
deregisteredContext = threadCache.pop();
logger.error("Illegal state in ContextProvider. Context, which should be unregistered, is not on top of stack. Recovery is perfomed, context " + deregisteredContext + " is removed from stack.");
}
logger.error("Illegal state in ContextProvider. Context, which should be unregistered, is not on top of stack. Recovery finished. Requested context is " + requestedContext);
} else {
threadCache.push(deregisteredContext);
logger.error("Illegal state in ContextProvider. Last context in stack was " + deregisteredContext + " but requested context is " + requestedContext);
return;
}
}
if (threadCache.isEmpty()) {
contextCache.remove(Thread.currentThread());
}
} else {
contextCache.remove(Thread.currentThread());
logger.error("Illegal state in ContextProvider. Empty context cache.");
}
}
private void writeRelationshipData(JsonGenerator gen, ResourceIdentifier resourceId,
Map<ResourceIdentifier, Resource> resourceMap,
Stack<ResourceIdentifier> inclusionStack,
SerializerProvider serializerProvider) throws IOException {
Resource resource = resourceMap.get(resourceId);
if (resource != null && !inclusionStack.contains(resourceId)) {
writeResource(gen, resource, resourceMap, inclusionStack, serializerProvider);
}
else {
gen.writeObject(resourceId);
}
}
public boolean hasLoopHashtable() {
Node temp = head;
Stack<Node> stack = new Stack<>();
while (temp != null) {
if (stack.contains(temp)) {
temp.next = null;
return true;
}
stack.add(temp);
temp = temp.next;
}
return false;
}
private static final String resolve(String var,
Resolver resolver,
Stack<String> stack,
final boolean failOnUnresolved)
{
if (stack.contains(var))
{
throw new IllegalArgumentException
(String.format("recursively defined variable: %s stack=%s", var,
stack));
}
String result = resolver.resolve(var, resolver);
if (result == null)
{
if(failOnUnresolved)
{
throw new IllegalArgumentException("no such variable: " + var);
}
else
{
return "${"+var+"}";
}
}
stack.push(var);
try
{
return expand(result, resolver, stack, failOnUnresolved);
}
finally
{
stack.pop();
}
}
private void clearEvictionDataInAllCallers(String rootModuleConf, Stack<IvyNode> callerStack) {
for (Caller caller : callerStack.peek().getCallers(rootModuleConf)) {
IvyNode callerNode = findNode(caller.getModuleRevisionId());
if (callerNode != null) {
callerNode.eviction = new IvyNodeEviction(callerNode);
if (!callerStack.contains(callerNode)) {
callerStack.push(callerNode);
clearEvictionDataInAllCallers(rootModuleConf, callerStack);
callerStack.pop();
}
}
}
}
private void searchBackward(V node, Set<V> visited, Set<V> component) {
Stack<V> worklist = new Stack<V>();
worklist.push(node);
while (!worklist.isEmpty()) {
V curr = worklist.pop();
visited.add(curr);
component.add(curr);
for (V pred: getDirectPredecessors(curr))
if (!visited.contains(pred) && !worklist.contains(pred))
worklist.add(pred);
}
}
public void findInvalidDelays(OperatorMeta om, List<List<String>> invalidDelays, Stack<OperatorMeta> stack)
{
stack.push(om);
// depth first successors traversal
boolean isDelayOperator = om.getOperator() instanceof Operator.DelayOperator;
if (isDelayOperator) {
if (om.getValue(OperatorContext.APPLICATION_WINDOW_COUNT) != 1) {
LOG.debug("detected DelayOperator having APPLICATION_WINDOW_COUNT not equal to 1");
invalidDelays.add(Collections.singletonList(om.getName()));
}
}
for (StreamMeta downStream: om.outputStreams.values()) {
for (InputPortMeta sink : downStream.sinks) {
OperatorMeta successor = sink.getOperatorMeta();
if (isDelayOperator) {
sink.attributes.put(IS_CONNECTED_TO_DELAY_OPERATOR, true);
// Check whether all downstream operators are already visited in the path
if (successor != null && !stack.contains(successor)) {
LOG.debug("detected DelayOperator does not immediately output to a visited operator {}.{}->{}.{}",
om.getName(), downStream.getSource().getPortName(), successor.getName(), sink.getPortName());
invalidDelays.add(Arrays.asList(om.getName(), successor.getName()));
}
} else {
findInvalidDelays(successor, invalidDelays, stack);
}
}
}
stack.pop();
}
private void inspectComponent(InspectedComponent component) {
//stack for recursion algorithm
Stack<InspectedComponent> componentsStack = new Stack<InspectedComponent>();
componentsStack.push(component);
while (!componentsStack.isEmpty()) {
//what is current component?
InspectedComponent topComponent = componentsStack.peek();
//what is following component?
InspectedComponent nextComponent = topComponent.getNextComponent();
if (nextComponent != null) {
if (!alreadyVisitedFromTheDirection(visitedComponents, nextComponent)) {
//following component found
if (componentsStack.contains(nextComponent)) {
//cycle found
componentsStack.push(nextComponent);
cycleFound(componentsStack);
} else {
//recursion can go deeper
componentsStack.push(nextComponent);
}
}
} else {
visitedComponents.add(topComponent);
//no other follower, let's step back in the stack
componentsStack.pop();
}
}
}
/**
* Finds all components on the loop and convert all edges to fast-propagate.
* @param loopComponent
*/
private static void inspectEdgesInLoop(InspectedComponent loopComponent) {
Set<InspectedComponent> componentsInLoop = new HashSet<>();
componentsInLoop.add(loopComponent);
Stack<InspectedComponent> path = new Stack<>();
InspectedComponent pointer = loopComponent.getOutputPortComponent(1);
if (pointer != null) {
path.push(pointer);
while (pointer != null) {
InspectedComponent follower = pointer.getNextComponent();
if (follower != null) {
if (componentsInLoop.contains(follower)) {
componentsInLoop.addAll(path);
} else if (!path.contains(follower)) {
path.push(follower);
pointer = follower;
}
} else {
path.pop();
pointer = !path.isEmpty() ? path.peek() : null;
}
}
}
//converts list of inspected components to list of engine components
Set<Node> engineComponents = new HashSet<>();
for (InspectedComponent component : componentsInLoop) {
Node engineComponent = component.getComponent();
//if one of inspected components is a Subgraph, the subgraph has to be executed in fast-propagate mode
if (SubgraphUtils.isSubJobComponent(engineComponent.getType())) {
//the component can be also instance of MockupComponent, which is used for cluster graph analyse
if (engineComponent instanceof SubgraphComponent) {
((SubgraphComponent) engineComponent).setFastPropagateExecution(true);
}
}
engineComponents.add(engineComponent);
}
//convert all edges to fast-propagate type
try {
GraphUtils.makeEdgesFastPropagate(engineComponents);
} catch (Exception e) {
throw new JetelRuntimeException("Phase edge detected inside the loop.", e);
}
}
/**
* uses trajans algorithm to get all strongly connected components
*
* @return Strongly connected components
*/
private Set<IndexedGraph> trajan(IndexedGraph graph) {
Map<Integer, Node> nodes = createNodes(graph);
Set<IndexedGraph> result = new HashSet<>();
int index = 0;
Stack<Node> tarStack = new Stack<>();
for (Integer cat : nodes.keySet()) {
Node u = nodes.get(cat);
if (!nodes.get(cat).visited) {
u.index = index;
u.visited = true;
u.lowlink = index;
index++;
u.vindex = 0;
tarStack.push(u);
u.caller = null;
Node last = u;
IndexedGraph curSCC = new IndexedGraph();
Set<Node> curSCCnodes = new HashSet<>();
while (true) {
if (last.vindex < last.adjacentNodes.size()) {
Node w = nodes.get(last.adjacentNodes.get(last.vindex));
last.vindex++;
if (w == null) continue;
if (!w.visited) {
w.caller = last;
w.vindex = 0;
w.index = index;
w.visited = true;
w.lowlink = index;
index++;
tarStack.push(w);
last = w;
} else if (tarStack.contains(w)) {
last.lowlink = Math.min(last.lowlink, w.lowlink);
}
} else {
if (last.lowlink == last.index) {
Node top = tarStack.pop();
curSCCnodes.add(top);
while (!top.key.equals(last.key)) {
top = tarStack.pop();
curSCCnodes.add(top);
}
if (!curSCCnodes.isEmpty()) {
for (Node n : curSCCnodes) {
for (Integer adjacent : n.adjacentNodes) {
if (curSCCnodes.contains(nodes.get(adjacent))) curSCC.put(n.key, adjacent);
}
}
if (!curSCC.isEmpty()) result.add(curSCC);
}
curSCCnodes.clear();
curSCC = new IndexedGraph();
}
Node newLast = last.caller;
if (newLast != null) {
newLast.lowlink = Math.min(newLast.lowlink, last.lowlink);
last = newLast;
} else {
break;
}
}
}
}
}
return result;
}
private Set<BytecodeBasicBlock> generateEdges(
final Set<BytecodeBasicBlock> aVisited, final BytecodeBasicBlock aBlock, final Stack<BytecodeBasicBlock> aNestingStack, final Map<BytecodeOpcodeAddress, BytecodeBasicBlock> aBlocks) {
aNestingStack.push(aBlock);
if (aVisited.add(aBlock)) {
for (final BytecodeInstruction theInstruction : aBlock.getInstructions()) {
if (theInstruction.isJumpSource()) {
for (final BytecodeOpcodeAddress theTarget : theInstruction.getPotentialJumpTargets()) {
final BytecodeBasicBlock theTargetBlock = aBlocks.get(theTarget);
if (!aNestingStack.contains(theTargetBlock)) {
// Normal edge
aBlock.addSuccessor(theTargetBlock);
generateEdges(aVisited, theTargetBlock, aNestingStack, aBlocks);
} else {
// Back edge
aBlock.addSuccessor(theTargetBlock);
}
}
}
}
// Properly handle the fall thru case
if (!aBlock.endsWithReturn() && !aBlock.endsWithThrow() && !aBlock.endsWithGoto()) {
final BytecodeInstruction theLast = aBlock.lastInstruction();
final BytecodeInstruction theNext = nextInstructionOf(theLast);
final BytecodeBasicBlock theNextBlock = aBlocks.get(theNext.getOpcodeAddress());
aBlock.addSuccessor(theNextBlock);
generateEdges(aVisited, theNextBlock, aNestingStack, aBlocks);
}
for (final BytecodeBasicBlock theBlock : aBlock.getSuccessors()) {
if (theBlock.getType() != BytecodeBasicBlock.Type.NORMAL) {
generateEdges(aVisited, theBlock, aNestingStack, aBlocks);
}
}
}
aNestingStack.pop();
return aVisited;
}
@VisibleForTesting
public static void validateActionInputDirectory(
String directoryPath,
Directory directory,
Stack<Digest> pathDigests,
Set<Digest> visited,
Map<Digest, Directory> directoriesIndex,
Consumer<String> onInputFile,
Consumer<String> onInputDirectory,
Consumer<Digest> onInputDigest,
PreconditionFailure.Builder preconditionFailure) {
Set<String> entryNames = new HashSet<>();
String lastFileName = "";
for (FileNode fileNode : directory.getFilesList()) {
String fileName = fileNode.getName();
if (entryNames.contains(fileName)) {
preconditionFailure
.addViolationsBuilder()
.setType(VIOLATION_TYPE_INVALID)
.setSubject("/" + directoryPath + ": " + fileName)
.setDescription(DUPLICATE_DIRENT);
} else if (lastFileName.compareTo(fileName) > 0) {
preconditionFailure
.addViolationsBuilder()
.setType(VIOLATION_TYPE_INVALID)
.setSubject("/" + directoryPath + ": " + lastFileName + " > " + fileName)
.setDescription(DIRECTORY_NOT_SORTED);
}
/* FIXME serverside validity check? regex?
Preconditions.checkState(
fileName.isValidFilename(),
INVALID_FILE_NAME);
*/
lastFileName = fileName;
entryNames.add(fileName);
onInputDigest.accept(fileNode.getDigest());
String filePath = directoryPath.isEmpty() ? fileName : (directoryPath + "/" + fileName);
onInputFile.accept(filePath);
}
String lastDirectoryName = "";
for (DirectoryNode directoryNode : directory.getDirectoriesList()) {
String directoryName = directoryNode.getName();
if (entryNames.contains(directoryName)) {
preconditionFailure
.addViolationsBuilder()
.setType(VIOLATION_TYPE_INVALID)
.setSubject("/" + directoryPath + ": " + directoryName)
.setDescription(DUPLICATE_DIRENT);
} else if (lastDirectoryName.compareTo(directoryName) > 0) {
preconditionFailure
.addViolationsBuilder()
.setType(VIOLATION_TYPE_INVALID)
.setSubject("/" + directoryPath + ": " + lastDirectoryName + " > " + directoryName)
.setDescription(DIRECTORY_NOT_SORTED);
}
/* FIXME serverside validity check? regex?
Preconditions.checkState(
directoryName.isValidFilename(),
INVALID_FILE_NAME);
*/
lastDirectoryName = directoryName;
entryNames.add(directoryName);
Digest directoryDigest = directoryNode.getDigest();
if (pathDigests.contains(directoryDigest)) {
preconditionFailure
.addViolationsBuilder()
.setType(VIOLATION_TYPE_INVALID)
.setSubject(DIRECTORY_CYCLE_DETECTED)
.setDescription("/" + directoryPath + ": " + directoryName);
} else {
String subDirectoryPath =
directoryPath.isEmpty() ? directoryName : (directoryPath + "/" + directoryName);
onInputDirectory.accept(subDirectoryPath);
if (!visited.contains(directoryDigest)) {
validateActionInputDirectoryDigest(
subDirectoryPath,
directoryDigest,
pathDigests,
visited,
directoriesIndex,
onInputFile,
onInputDirectory,
onInputDigest,
preconditionFailure);
} else {
enumerateActionInputDirectory(
subDirectoryPath,
directoriesIndex.get(directoryDigest),
directoriesIndex,
onInputFile,
onInputDirectory);
}
}
}
}
private void service(Request request, Response response)
throws IOException, ServletException
{
if (httpContext.handleSecurity(request, response)) {
final Thread t = Thread.currentThread();
Stack<String> usedURIStack = threadStacks.get(t);
if (usedURIStack == null) {
usedURIStack = new Stack<String>();
threadStacks.put(t, usedURIStack);
}
String uri =
(String) request.getAttribute("javax.servlet.include.request_uri");
if (uri == null) {
uri = request.getRequestURI();
}
if (usedURIStack.contains(uri)) {
throw new ServletException("Recursive include of \"" + uri + "\"");
}
usedURIStack.push(uri);
try {
if (servlet instanceof SingleThreadModel) {
synchronized (servlet) {
if (config == null) {
// Activator.log.info("Serving: " + uri);
servlet.service(request, response);
// Activator.log.info("Served: " + uri);
} else {
serviceResource(request, response, config);
}
}
} else {
if (config == null) {
// Activator.log.info(Thread.currentThread().getName() + " Serving: " + uri);
servlet.service(request, response);
// Activator.log.info(Thread.currentThread().getName() + " Served: " + uri);
} else {
serviceResource(request, response, config);
}
}
} finally {
usedURIStack.pop();
if (usedURIStack.empty()) {
threadStacks.remove(t);
}
}
}
}
private void parseHtml(final String uri,
final ServletContext context,
final ServletOutputStream os,
final Stack<String> usedFiles)
throws IOException
{
if (usedFiles.contains(uri)) {
os.print("<b><font color=\"red\">SSI Error: Recursive include: " + uri
+ "</font></b>");
return;
}
usedFiles.push(uri);
InputStream raw;
try {
raw = context.getResourceAsStream(uri);
} catch (final Exception e) {
raw = null;
}
if (raw == null) {
os.print("<b><font color=\"red\">SSI Error: Error reading file: " + uri
+ "</font></b>");
return;
}
final InputStream is = new BufferedInputStream(raw);
byte c;
boolean tagBegin = false;
final StringBuffer buf = new StringBuffer(20);
while ((c = (byte) is.read()) != -1) {
if (c == '<') {
buf.setLength(0);
tagBegin = true;
} else if (tagBegin && c == '>') {
String restOfTag = buf.toString();
final String ssi_pattern = "!--#";
if (restOfTag.length() > ssi_pattern.length()
&& restOfTag.startsWith(ssi_pattern)) { // is this an
// ssi tag?
restOfTag = restOfTag.substring(ssi_pattern.length());
final String include_pattern = "include";
if (restOfTag.length() > include_pattern.length()
&& restOfTag.startsWith(include_pattern)) { // is
// this
// an
// include
// directive?
restOfTag = restOfTag.substring(include_pattern.length());
final String file_pattern = "file=\"";
final int index = restOfTag.indexOf(file_pattern);
if (index > 0 && Character.isWhitespace(restOfTag.charAt(0))) {
restOfTag = restOfTag.substring(index + file_pattern.length());
final String file = restOfTag.substring(0, restOfTag.indexOf('\"'));
parseHtml(uri.substring(0, uri.lastIndexOf("/") + 1) + file,
context, os, usedFiles);
} else {
os.print("<b><font color=\"red\">SSI Error: Unsupported directive</font></b>");
}
} else {
os.print("<b><font color=\"red\">SSI Error: Unsupported directive</font></b>");
}
} else {
os.print('<');
os.print(restOfTag);
os.print('>');
}
tagBegin = false;
} else if (tagBegin) {
buf.append((char) c);
} else {
os.write(c);
}
}
is.close();
usedFiles.pop();
}
/**
* Check: is the NODE n in the given stack<br>
* <br>
* <b>WARNING</b>: This is currently an inefficient implementation.
* This should be converted from a linear lookup to a constant operation.
*
* @param stack
* @param n
* @return boolean
*/
protected boolean isInStack(Stack<NODE> stack, NODE n) {
// TODO make this more efficient
return stack.contains(n);
}