Java Code Examples for java.util.Stack#addAll()

The following examples show how to use java.util.Stack#addAll() . 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: DependencyExcludeNodeVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public boolean visit(DependencyNode node) {
    if (root == null) {
        root = node;
        directs = new HashSet<DependencyNode>();
        path = new Stack<DependencyNode>();
        allPaths = new HashSet<Stack<DependencyNode>>();
        return true;
    }
    path.push(node);
    Artifact artifact = node.getArtifact();
    if (key.equals(artifact.getDependencyConflictId())) {
        if (!path.isEmpty()) {
            directs.add(path.firstElement());
            Stack<DependencyNode> copy = new Stack<DependencyNode>();
            copy.addAll(path);
            allPaths.add(copy);
        }
        return false;
    }
    return true;
}
 
Example 2
Source File: JSONConverter.java    From jmeter-bzm-plugins with Apache License 2.0 6 votes vote down vote up
public static Map<String, Long> getQuantiles(Long[] rtimes, long average) {
    Map<String, Long> result = new HashMap<>();
    Arrays.sort(rtimes);

    double[] quantiles = {0.0, 0.90, 0.95, 0.99, 1.00};

    Stack<Long> timings = new Stack<>();
    timings.addAll(Arrays.asList(rtimes));
    double level = 1.0;
    Long timing = 0L;
    long sqr_diffs = 0;
    for (int qn = quantiles.length - 1; qn >= 0; qn--) {
        double quan = quantiles[qn];
        while (level >= quan && !timings.empty()) {
            timing = timings.pop();
            level -= 1.0 / rtimes.length;
            sqr_diffs += timing * Math.pow(timing - average, 2);
        }
        result.put(getMetricLabel(quan), timing);
    }
    result.put("std", (long) Math.sqrt(sqr_diffs / rtimes.length));
    return result;
}
 
Example 3
Source File: OBOOntology.java    From bluima with Apache License 2.0 6 votes vote down vote up
/**
 * Given a single ID, return that ID, its parents, grandparents etc.
 * 
 * @param termId
 *            The initial "seed" ID.
 * @return The full set of IDs.
 */
public Set<String> getIdsForIdWithAncestors(String termId) {
    if (!terms.containsKey(termId))
        return new HashSet<String>();
    Stack<String> idsToConsider = new Stack<String>();
    idsToConsider.add(termId);
    Set<String> resultIds = new HashSet<String>();
    while (!idsToConsider.isEmpty()) {
        String id = idsToConsider.pop();
        if (!resultIds.contains(id)) {
            resultIds.add(id);
            idsToConsider.addAll(terms.get(id).getIsA());
        }
    }
    return resultIds;
}
 
Example 4
Source File: FlattenerTest.java    From archie with Apache License 2.0 6 votes vote down vote up
@Test
public void checkParentReplacement() throws Exception {
    Archetype flattened = flattener.flatten(bloodPressureComposition);

    Stack<CObject> worklist = new Stack();
    worklist.add(flattened.getDefinition());

    while (!worklist.isEmpty()) {
        CObject object = worklist.pop();
        if (object.getArchetype() != flattened) {
            fail("wrong parent found!");
        }
        for (CAttribute attr : object.getAttributes()) {
            if (attr.getParent() != object) {
                fail("wrong parent found!");
            }
            worklist.addAll(attr.getChildren());
        }
    }

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

    System.out.println(objectMapper.writeValueAsString(flattened));

}
 
Example 5
Source File: ListDefaults.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@DataProvider(name="listProvider", parallel=true)
public static Object[][] listCases() {
    final List<Object[]> cases = new LinkedList<>();
    cases.add(new Object[] { Collections.emptyList() });
    cases.add(new Object[] { new ArrayList<>() });
    cases.add(new Object[] { new LinkedList<>() });
    cases.add(new Object[] { new Vector<>() });
    cases.add(new Object[] { new Stack<>() });
    cases.add(new Object[] { new CopyOnWriteArrayList<>() });
    cases.add(new Object[] { Arrays.asList() });

    List<Integer> l = Arrays.asList(42);
    cases.add(new Object[] { new ArrayList<>(l) });
    cases.add(new Object[] { new LinkedList<>(l) });
    cases.add(new Object[] { new Vector<>(l) });
    Stack<Integer> s = new Stack<>(); s.addAll(l);
    cases.add(new Object[]{s});
    cases.add(new Object[] { new CopyOnWriteArrayList<>(l) });
    cases.add(new Object[] { l });
    return cases.toArray(new Object[0][cases.size()]);
}
 
Example 6
Source File: MemHypergraph.java    From pacaya with Apache License 2.0 6 votes vote down vote up
public static List<MemHypernode> topoSortNodes(List<MemHypernode> nodes) {
    // L ← Empty list that will contain the sorted nodes
    LinkedList<MemHypernode> sort = new LinkedList<MemHypernode>();
    Stack<MemHypernode> unmarked = new Stack<MemHypernode>();
    unmarked.addAll(nodes);
    boolean[] tempMarks = new boolean[nodes.size()];
    boolean[] permMarks = new boolean[nodes.size()];
    // while there are unmarked nodes do
    while (unmarked.size() > 0) {
        // select an unmarked node n
        MemHypernode n = unmarked.pop();
        if (permMarks[n.getId()]) {
            continue;
        }
        // visit(n)
        visitNode1(n, sort, unmarked, tempMarks, permMarks);
    }
    return sort;
}
 
Example 7
Source File: ListDefaults.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@DataProvider(name="listProvider", parallel=true)
public static Object[][] listCases() {
    final List<Object[]> cases = new LinkedList<>();
    cases.add(new Object[] { Collections.emptyList() });
    cases.add(new Object[] { new ArrayList<>() });
    cases.add(new Object[] { new LinkedList<>() });
    cases.add(new Object[] { new Vector<>() });
    cases.add(new Object[] { new Stack<>() });
    cases.add(new Object[] { new CopyOnWriteArrayList<>() });
    cases.add(new Object[] { Arrays.asList() });

    List<Integer> l = Arrays.asList(42);
    cases.add(new Object[] { new ArrayList<>(l) });
    cases.add(new Object[] { new LinkedList<>(l) });
    cases.add(new Object[] { new Vector<>(l) });
    Stack<Integer> s = new Stack<>(); s.addAll(l);
    cases.add(new Object[]{s});
    cases.add(new Object[] { new CopyOnWriteArrayList<>(l) });
    cases.add(new Object[] { l });
    return cases.toArray(new Object[0][cases.size()]);
}
 
Example 8
Source File: StackOperators.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
public void execute(ExecutionContext context)
{
    Stack<Object> stack = context.getStack();
    int n = ((Number)stack.pop()).intValue();
    if (n > 0)
    {
        int size = stack.size();
        //Need to copy to a new list to avoid ConcurrentModificationException
        List<Object> copy = new java.util.ArrayList<Object>(
                stack.subList(size - n, size));
        stack.addAll(copy);
    }
}
 
Example 9
Source File: OWLGraphWrapperEdgesExtended.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
    * Returns all parent properties of <code>prop</code> in all ontologies, 
    * and <code>prop</code> itself as the first element (reflexive). 
    * Unlike the method <code>owltools.graph.OWLGraphWrapperEdges.getSuperPropertyReflexiveClosureOf</code>, 
    * the returned super properties here are ordered from the more precise to the more general 
    * (e.g., "in_deep_part_of", then "part_of", then "overlaps"). 
    * 
    * @param prop 	the <code>OWLObjectPropertyExpression</code> for which we want 
    * 				the ordered super properties. 
    * @return		A <code>LinkedHashSet</code> of <code>OWLObjectPropertyExpression</code>s 
    * 				ordered from the more precise to the more general, with <code>prop</code> 
    * 				as the first element. 
    */
//TODO: Remove if OWLGraphWrapper changes its implementation
   public LinkedHashSet<OWLObjectPropertyExpression> getSuperPropertyReflexiveClosureOf(
   		OWLObjectPropertyExpression prop) {
   	
   	//try to get the super properties from the cache
   	LinkedHashSet<OWLObjectPropertyExpression> superProps = 
   			this.superPropertyCache.get(prop);
   	if (superProps == null) {

   		superProps = new LinkedHashSet<OWLObjectPropertyExpression>();
   		Stack<OWLObjectPropertyExpression> stack = 
   				new Stack<OWLObjectPropertyExpression>();
   		stack.add(prop);
   		while (!stack.isEmpty()) {
   			OWLObjectPropertyExpression nextProp = stack.pop();
   			Set<OWLObjectPropertyExpression> directSupers = 
   					this.getSuperPropertiesOf(nextProp);
   			directSupers.removeAll(superProps);
   			directSupers.remove(prop);
   			stack.addAll(directSupers);
   			superProps.addAll(directSupers);
   		}
   		//put superProps in cache
   		this.superPropertyCache.put(prop, superProps);
   	}

   	
   	LinkedHashSet<OWLObjectPropertyExpression> superPropsReflexive = 
   			new LinkedHashSet<OWLObjectPropertyExpression>();
   	superPropsReflexive.add(prop);
	superPropsReflexive.addAll(superProps);
	return superPropsReflexive;
}
 
Example 10
Source File: TileDistribution.java    From Carcassonne with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Shuffles the tile amounts. The shuffle is not completely random as it tries to avoid giving a tile type its original
 * amount.
 */
public void shuffle() {
    TileType.enabledTiles().forEach(it -> distribution.putIfAbsent(it, it.getAmount()));
    Stack<Integer> tileAmounts = new Stack<Integer>();
    tileAmounts.addAll(distribution.values());
    Collections.shuffle(tileAmounts);
    TileType.enabledTiles().forEach(it -> distribution.put(it, getPseudoRandomAmount(it, tileAmounts)));
}
 
Example 11
Source File: Entities.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Side-effects {@code result} to return descendants (not including {@code root}).
 */
private static void descendantsWithoutSelf(Entity root, Collection<Entity> result) {
    Stack<Entity> tovisit = new Stack<Entity>();
    tovisit.add(root);

    while (!tovisit.isEmpty()) {
        Entity e = tovisit.pop();
        result.addAll(e.getChildren());
        tovisit.addAll(e.getChildren());
    }
}
 
Example 12
Source File: ActivityUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 检测是否包含指定的 Activity
 * @param clazzs Class(Activity)[]
 * @return {@code true} yes, {@code false} no
 */
public boolean existActivitys(final Class<?>... clazzs) {
    if (clazzs != null && clazzs.length != 0) {
        synchronized (mActivityStacks) {
            // 保存新的堆栈, 防止出现同步问题
            Stack<Activity> stack = new Stack<>();
            stack.addAll(mActivityStacks);
            try {
                // 进行遍历判断
                Iterator<Activity> iterator = stack.iterator();
                while (iterator.hasNext()) {
                    Activity activity = iterator.next();
                    if (activity != null && !activity.isFinishing()) {
                        for (int i = 0, len = clazzs.length; i < len; i++) {
                            if (clazzs[i] != null && activity.getClass().getName().equals(clazzs[i].getName())) {
                                return true;
                            }
                        }
                    }
                }
            } finally {
                // 移除数据, 并且清空内存
                stack.clear();
                stack = null;
            }
        }
    }
    return false;
}
 
Example 13
Source File: OnCompileFrame.java    From Concurnas with MIT License 5 votes vote down vote up
public Stack<Value> copyStack(){
	Stack<Value> ret = new Stack<Value>();
	//soft copy is fine
	ret.addAll(stack);
	
	return ret;
}
 
Example 14
Source File: CliContext.java    From milkman with MIT License 5 votes vote down vote up
public Optional<RequestContainer> findRequestByIdish(String idish) {
	Stack<String> splits = new Stack<String>();
	splits.addAll(Arrays.asList(idish.split("/")));
	
	
	if (splits.isEmpty()) {
		throw new IllegalArgumentException("No id given");
	}
	
	String reqName = splits.pop();
	Optional<String> colName = Optional.empty();
	Optional<String> wsName = Optional.empty();
	
	if (!splits.isEmpty()) {
		colName = Optional.ofNullable(splits.pop());
	}
	
	if (!splits.isEmpty()) {
		wsName = Optional.ofNullable(splits.pop());
	}
	
	
	Workspace ws = wsName.flatMap(this::findWorkspaceByIdish).orElse(currentWorkspace);
	if (ws == null) {
		throw new IllegalArgumentException("No workspace given");
	}

	Collection col = colName.flatMap(cn -> findCollectionByIdish(cn, ws)).orElse(currentCollection);
	if (col == null) {
		throw new IllegalArgumentException("No collection given");
	}

	return findMatching(reqName,  col.getRequests(), RequestContainer::getName);
}
 
Example 15
Source File: OWLGraphWrapperEdges.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * caches full outgoing and incoming edges
 * <p>
 * in general you should not need to call this directly;
 * used internally by this class.
 * 
 * @see OWLGraphWrapperEdges#clearCachedEdges()
 * @see OWLGraphWrapperEdges#getPrimitiveIncomingEdges(OWLObject)
 * @see OWLGraphWrapperEdges#getPrimitiveOutgoingEdges(OWLObject)
 * @see OWLGraphWrapperEdges#getEdgesBetween(OWLObject, OWLObject)
 */
public void cacheEdges() {
	synchronized (edgeCacheMutex) {
		edgeBySource = new HashMap<OWLObject,Set<OWLGraphEdge>>();
		edgeByTarget = new HashMap<OWLObject,Set<OWLGraphEdge>>();

		// initialize with all named objects in ontology
		Stack<OWLObject> allObjs = new Stack<OWLObject>();
		allObjs.addAll(getAllOWLObjects());

		Set<OWLObject> visisted = new HashSet<OWLObject>();

		while (allObjs.size() > 0) {
			OWLObject s = allObjs.pop();
			if (visisted.contains(s))
				continue;
			visisted.add(s);
			if (!edgeBySource.containsKey(s))
				edgeBySource.put(s, new OWLGraphEdgeSet());
			for (OWLGraphEdge edge : getPrimitiveOutgoingEdges(s)) {
			    edgeBySource.get(s).add(edge);
				OWLObject t = edge.getTarget();
				if (!edgeByTarget.containsKey(t))
					edgeByTarget.put(t, new OWLGraphEdgeSet());
				edgeByTarget.get(t).add(edge);

				// we also want to get all edges from class expressions;
				// class expressions aren't in the initial signature, but
				// we add them here when we encounter them
				if (t instanceof OWLClassExpression) {
					allObjs.add(t);
				}
			}
		}
	}
}
 
Example 16
Source File: ActivityUtils.java    From DevUtils with Apache License 2.0 4 votes vote down vote up
/**
 * 结束多个类名 Activity
 * @param clazzs Class(Activity)[]
 * @return {@link ActivityUtils}
 */
public ActivityUtils finishActivity(final Class<?>... clazzs) {
    if (clazzs != null && clazzs.length != 0) {
        synchronized (mActivityStacks) {
            // 保存新的堆栈, 防止出现同步问题
            Stack<Activity> stack = new Stack<>();
            stack.addAll(mActivityStacks);
            // 清空全部, 便于后续操作处理
            mActivityStacks.clear();
            // 判断是否销毁
            boolean isRemove;
            // 进行遍历移除
            Iterator<Activity> iterator = stack.iterator();
            while (iterator.hasNext()) {
                Activity activity = iterator.next();
                // 判断是否想要关闭的 Activity
                if (activity != null) {
                    // 默认不需要销毁
                    isRemove = false;
                    // 循环判断
                    for (int i = 0, len = clazzs.length; i < len; i++) {
                        // 判断是否相同
                        if (activity.getClass() == clazzs[i]) {
                            isRemove = true;
                            break;
                        }
                    }
                    // 判断是否销毁
                    if (isRemove) {
                        // 如果 Activity 没有 finish 则进行 finish
                        if (!activity.isFinishing()) {
                            activity.finish();
                        }
                        // 删除对应的 Item
                        iterator.remove();
                    }
                } else {
                    // 删除对应的 Item
                    iterator.remove();
                }
            }
            // 把不符合条件的保存回去
            mActivityStacks.addAll(stack);
            // 移除数据, 并且清空内存
            stack.clear();
            stack = null;
        }
    }
    return this;
}
 
Example 17
Source File: PDGSlicer.java    From compiler with Apache License 2.0 4 votes vote down vote up
@Override
public boolean equals(final Object o) {
    if (this == o) return true;
    if (!(o instanceof PDGSlicer)) return false;
    final PDGSlicer pdgSlicer = (PDGSlicer) o;

    final Stack<PDGNode> nodes1 = new Stack<PDGNode>();
    final Stack<PDGNode> nodes2 = new Stack<PDGNode>();
    final Set<PDGNode> visited1 = new HashSet<PDGNode>();
    final Set<PDGNode> visited2 = new HashSet<PDGNode>();
    nodes1.addAll(entryNodes);
    nodes2.addAll(pdgSlicer.getEntrynodesList());

    while (nodes1.size() != 0) {
        if (nodes1.size() != nodes2.size())
            return false;
        final PDGNode node1 = nodes1.pop();
        final PDGNode node2 = nodes2.pop();
        // compare statements
        if ((!node1.hasStmt() && node2.hasStmt()) ||
                (node1.hasStmt() && !node2.hasStmt()))
            return false;
        if (node1.hasStmt() && node2.hasStmt() &&
                !node1.getStmt().equals(node2.getStmt()))
            return false;

        // compare expressions
        if ((!node1.hasExpr() && node2.hasStmt()) ||
                (node1.hasExpr() && !node2.hasExpr()))
            return false;
        if (node1.hasExpr() && node2.hasExpr() &&
                !node1.getExpr().equals(node2.getExpr()))
            return false;

        // compare out edges
        if (node1.getOutEdges().size() != node2.getOutEdges().size())
            return false;

        visited1.add(node1);
        visited2.add(node2);

        for (int i = 0; i < node1.getSuccessors().size(); i++) {
            final List<PDGEdge> outEdges1 = node1.getOutEdges(node1.getSuccessors().get(i));
            final List<PDGEdge> outEdges2 = node2.getOutEdges(node2.getSuccessors().get(i));
            if (outEdges1.size() != outEdges2.size())
                return false;
            for (int j = 0; j < outEdges1.size(); j++) {
                if (outEdges1.get(j).getKind() != outEdges2.get(j).getKind() ||
                        !outEdges1.get(j).getLabel().equals(outEdges2.get(j).getLabel()))
                    return false;
            }

            if (!visited1.contains(node1.getSuccessors().get(i)))
                nodes1.push(node1.getSuccessors().get(i));
            if (!visited2.contains(node2.getSuccessors().get(i)))
                nodes2.push(node2.getSuccessors().get(i));
        }
    }

    return true;
}
 
Example 18
Source File: AToExists.java    From spf with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void visit(Literal literal) {
	final int len = literal.numArgs();
	if (aPredicate.equals(literal.getPredicate())) {
		if (len == 1) {
			final Lambda innerLambda = makeEntityToTruthLambda(literal
					.getArg(0));
			if (innerLambda == null) {
				throw new IllegalStateException("Invalid A expression: "
						+ literal);
			}
			innerLambda.getBody().accept(this);
			final Stack<Pair<Variable, ? extends LogicalExpression>> currentStack = new Stack<Pair<Variable, ? extends LogicalExpression>>();
			// To avoid the case of variables shared through various
			// structures, replace the current variable with a new one in
			// the inner body. This is a safe and simple way to solve this
			// problem. More efficient solutions are possible.
			final Variable newVariable = new Variable(innerLambda
					.getArgument().getType());
			// The result contains in the first place the processed body of
			// the inner lambda.
			currentStack.push(Pair.of(
					newVariable,
					ReplaceExpression.of(result.first(),
							innerLambda.getArgument(), newVariable)));
			// Append stack from sub tree
			currentStack.addAll(result.second());
			result = Pair.of(newVariable, currentStack);
		} else {
			throw new IllegalStateException("invalid A expression: "
					+ literal);
		}
	} else {
		literal.getPredicate().accept(this);
		final Pair<? extends LogicalExpression, Stack<Pair<Variable, ? extends LogicalExpression>>> newPredPair = result;

		final LogicalExpression[] newArgs = new LogicalExpression[len];
		final List<Stack<Pair<Variable, ? extends LogicalExpression>>> newStacks = new ArrayList<Stack<Pair<Variable, ? extends LogicalExpression>>>(
				len);
		boolean argsChanged = false;
		for (int i = 0; i < len; ++i) {
			final LogicalExpression arg = literal.getArg(i);
			arg.accept(this);
			newArgs[i] = result.first();
			newStacks.add(result.second());
			if (arg != result.first()) {
				argsChanged = true;
			}
		}

		// Merge stacks returned from all arguments.
		final Stack<Pair<Variable, ? extends LogicalExpression>> mergedStack = new Stack<Pair<Variable, ? extends LogicalExpression>>();
		for (final Stack<Pair<Variable, ? extends LogicalExpression>> stack : newStacks) {
			mergedStack.addAll(stack);
		}

		if (argsChanged || newPredPair.first() != literal.getPredicate()) {
			result = Pair.of(new Literal(newPredPair.first(), newArgs),
					mergedStack);
		} else {
			result = Pair.of(literal, mergedStack);
		}
	}

	// Try to wrap the literal with existential quantifiers.
	result = Pair.of(wrapIfPossible(result.first(), result.second()),
			result.second());

}
 
Example 19
Source File: SchemaReferencesMetaData.java    From secure-data-service with Apache License 2.0 4 votes vote down vote up
/**
 * A tree walker implementation that searches for leaf nodes of type ReferenceSchema within a NeutralSchema tree.
 *
 * @param schema
 * @param current nesting level e.g. studentCompetency.objectiveId.studentCompetencyObjectiveId
 * @param refMap  A map from entityType to a List of SchemaReferenceNode, each of which represents
 *                a path like studentCompetency.objectiveId.studentCompetencyObjectiveId
 */
public void collectReferences(NeutralSchema schema, final Stack<SchemaReferenceNode> currentPath, ListMultimap refMap) {
    if(schema instanceof ReferenceSchema) {
        ReferenceSchema reference = (ReferenceSchema)schema;
        AppInfo appInfo = (AppInfo)reference.getAnnotation(Annotation.AnnotationType.APPINFO);
        if(appInfo != null) {

            Stack<SchemaReferenceNode> refPath = new Stack<SchemaReferenceNode>();
            refPath.addAll(currentPath);
            if(refPath.peek().getName().equals("reference")) {
                refPath.pop();
            }
            String type = appInfo.getReferenceType();
            refPath.peek().setReferences(type);
            refMap.put(type, refPath);
            LOG.debug("Found a Reference from {}->{}", refPath, type);
        } else {
            LOG.warn("No AppInfo for {}. Cannot determine what EntityType it points to!", currentPath);
        }

    } else {
        Map<String, NeutralSchema> fields = schema.getFields();
        for(String fieldName:fields.keySet()) {

            NeutralSchema fieldSchema = fields.get(fieldName);
            Map<String, Object> properties = fieldSchema.getProperties();
            Long minOccurs           =       (Long)  properties.get("minCardinality");
            Long maxOccurs           =       (Long)  properties.get("maxCardinality");
            final String elementType =       (String)properties.get("elementType");

            boolean loop = Iterables.any(currentPath, new Predicate<SchemaReferenceNode>() {
                @Override
                public boolean apply(@Nullable SchemaReferenceNode schemaReferenceNode) {
                    String refs =  schemaReferenceNode.getReferences();
                    if(refs != null && elementType != null && refs.equals(elementType)){
                        LOG.debug("Cycle found. Repeating [" + elementType + "]" + " in [" + getTypePath(currentPath) + "]");
                        return true;
                    } else {
                        return false;
                    }
                }
            });

            if(loop) {
                continue;
            }

            SchemaReferenceNode pathNode = new SchemaReferenceNode(fieldName);
            pathNode.setMinOccurs(minOccurs); pathNode.setMaxOccurs(maxOccurs);
            pathNode.setReferences(elementType);
            currentPath.push(pathNode);

            if(fieldSchema.getType().equals("list")) {
                Map<String, NeutralSchema> listFields = fieldSchema.getFields();
                for(NeutralSchema listFieldSchema:listFields.values()) {
                    collectReferences(listFieldSchema, currentPath, refMap);
                    currentPath.pop();
                }
            } else {
                collectReferences(fieldSchema, currentPath, refMap);
                currentPath.pop();
            }

        }
    }
}
 
Example 20
Source File: SharedBufferAccessor.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Returns all elements from the previous relation starting at the given entry.
 *
 * @param nodeId  id of the starting entry
 * @param version Version of the previous relation which shall be extracted
 * @return Collection of previous relations starting with the given value
 */
public List<Map<String, List<EventId>>> extractPatterns(
	final NodeId nodeId,
	final DeweyNumber version) {

	List<Map<String, List<EventId>>> result = new ArrayList<>();

	// stack to remember the current extraction states
	Stack<SharedBufferAccessor.ExtractionState> extractionStates = new Stack<>();

	// get the starting shared buffer entry for the previous relation
	Lockable<SharedBufferNode> entryLock = sharedBuffer.getEntry(nodeId);

	if (entryLock != null) {
		SharedBufferNode entry = entryLock.getElement();
		extractionStates.add(new SharedBufferAccessor.ExtractionState(Tuple2.of(nodeId, entry), version, new Stack<>()));

		// use a depth first search to reconstruct the previous relations
		while (!extractionStates.isEmpty()) {
			final SharedBufferAccessor.ExtractionState extractionState = extractionStates.pop();
			// current path of the depth first search
			final Stack<Tuple2<NodeId, SharedBufferNode>> currentPath = extractionState.getPath();
			final Tuple2<NodeId, SharedBufferNode> currentEntry = extractionState.getEntry();

			// termination criterion
			if (currentEntry == null) {
				final Map<String, List<EventId>> completePath = new LinkedHashMap<>();

				while (!currentPath.isEmpty()) {
					final NodeId currentPathEntry = currentPath.pop().f0;

					String page = currentPathEntry.getPageName();
					List<EventId> values = completePath
						.computeIfAbsent(page, k -> new ArrayList<>());
					values.add(currentPathEntry.getEventId());
				}
				result.add(completePath);
			} else {

				// append state to the path
				currentPath.push(currentEntry);

				boolean firstMatch = true;
				for (SharedBufferEdge edge : currentEntry.f1.getEdges()) {
					// we can only proceed if the current version is compatible to the version
					// of this previous relation
					final DeweyNumber currentVersion = extractionState.getVersion();
					if (currentVersion.isCompatibleWith(edge.getDeweyNumber())) {
						final NodeId target = edge.getTarget();
						Stack<Tuple2<NodeId, SharedBufferNode>> newPath;

						if (firstMatch) {
							// for the first match we don't have to copy the current path
							newPath = currentPath;
							firstMatch = false;
						} else {
							newPath = new Stack<>();
							newPath.addAll(currentPath);
						}

						extractionStates.push(new SharedBufferAccessor.ExtractionState(
							target != null ? Tuple2.of(target, sharedBuffer.getEntry(target).getElement()) : null,
							edge.getDeweyNumber(),
							newPath));
					}
				}
			}

		}
	}
	return result;
}