Example usage for java.util Deque push

List of usage examples for java.util Deque push

Introduction

In this page you can find the example usage for java.util Deque push.

Prototype

void push(E e);

Source Link

Document

Pushes an element onto the stack represented by this deque (in other words, at the head of this deque) if it is possible to do so immediately without violating capacity restrictions, throwing an IllegalStateException if no space is currently available.

Usage

From source file:org.talend.dataprep.transformation.actions.text.ExtractStringTokens.java

@Override
public void compile(ActionContext context) {
    super.compile(context);
    if (context.getActionStatus() == ActionContext.ActionStatus.OK) {

        final String regex = context.getParameters().get(PARAMETER_REGEX);

        // Validate the regex, and put it in context once for all lines:
        // Check 1: not null or empty
        if (StringUtils.isEmpty(regex)) {
            LOGGER.debug("Empty pattern, action canceled");
            context.setActionStatus(ActionContext.ActionStatus.CANCELED);
            return;
        }/*from  w  ww  .  j  a va  2  s. c o  m*/
        // Check 2: valid regex
        try {
            context.get(PATTERN, p -> Pattern.compile(regex));
        } catch (PatternSyntaxException e) {
            LOGGER.debug("Invalid pattern {} --> {}, action canceled", regex, e.getMessage(), e);
            context.setActionStatus(ActionContext.ActionStatus.CANCELED);
        }
        // Create result column
        final Map<String, String> parameters = context.getParameters();
        final String columnId = context.getColumnId();

        // create the new columns
        int limit = parameters.get(MODE_PARAMETER).equals(MULTIPLE_COLUMNS_MODE)
                ? Integer.parseInt(parameters.get(LIMIT))
                : 1;

        final RowMetadata rowMetadata = context.getRowMetadata();
        final ColumnMetadata column = rowMetadata.getById(columnId);
        final List<String> newColumns = new ArrayList<>();
        final Deque<String> lastColumnId = new ArrayDeque<>();
        lastColumnId.push(columnId);
        for (int i = 0; i < limit; i++) {
            final int newColumnIndex = i + 1;
            newColumns.add(context.column(column.getName() + APPENDIX + i, r -> {
                final ColumnMetadata c = ColumnMetadata.Builder //
                        .column() //
                        .type(Type.STRING) //
                        .computedId(StringUtils.EMPTY) //
                        .name(column.getName() + APPENDIX + newColumnIndex) //
                        .build();
                lastColumnId.push(rowMetadata.insertAfter(lastColumnId.pop(), c));
                return c;
            }));
        }

    }
}

From source file:com.icantrap.collections.dawg.DawgBuilder.java

/**
 * The number of nodes - currently - in the structure that will become the Dawg.
 * @return the number of nodes//from w w  w.j av a  2s.  c  om
 */
public int nodeCount() {
    int nodeCount = 0;
    Deque<Node> stack = new LinkedList<Node>();
    stack.push(root);

    while (!stack.isEmpty()) {
        Node ptr = stack.pop();
        ++nodeCount;

        for (Node nextChild : ptr.nextChildren)
            stack.push(nextChild);
        if (null != ptr.child)
            stack.push(ptr.child);
    }

    return nodeCount;
}

From source file:com.cloudera.oryx.rdf.common.tree.DecisionTree.java

@Override
public String toString() {
    StringBuilder result = new StringBuilder();
    if (root != null) {
        Deque<Pair<TreeNode, TreePath>> toPrint = new LinkedList<Pair<TreeNode, TreePath>>();
        toPrint.push(new Pair<TreeNode, TreePath>(root, TreePath.EMPTY));
        while (!toPrint.isEmpty()) {
            Pair<TreeNode, TreePath> entry = toPrint.pop();
            TreeNode node = entry.getFirst();
            TreePath path = entry.getSecond();
            int pathLength = path.length();
            for (int i = 0; i < pathLength; i++) {
                if (i == pathLength - 1) {
                    result.append(" +-");
                } else {
                    result.append(path.isLeftAt(i) ? " | " : "   ");
                }/*from   w ww . j  a  va2 s  .  c om*/
            }
            result.append(node).append('\n');
            if (node != null && !node.isTerminal()) {
                DecisionNode decisionNode = (DecisionNode) node;
                toPrint.push(new Pair<TreeNode, TreePath>(decisionNode.getRight(), path.extendRight()));
                toPrint.push(new Pair<TreeNode, TreePath>(decisionNode.getLeft(), path.extendLeft()));
            }
        }
    }
    return result.toString();
}

From source file:msi.gama.kernel.model.GamlModelSpecies.java

@Override
public Map<String, ISpecies> getAllSpecies() {
    if (allSpecies == null) {
        allSpecies = new TOrderedHashMap();
        final Deque<ISpecies> speciesStack = new ArrayDeque<ISpecies>();
        speciesStack.push(this);
        ISpecies currentSpecies;/* w w w  .  j a va 2s .c  o m*/
        while (!speciesStack.isEmpty()) {
            currentSpecies = speciesStack.pop();
            // scope.getGui().debug("GamlModelSpecies: effectively adding "
            // + currentSpecies.getName());
            allSpecies.put(currentSpecies.getName(), currentSpecies);
            final List<ISpecies> theMicroSpecies = currentSpecies.getMicroSpecies();
            for (final ISpecies microSpec : theMicroSpecies) {
                if (microSpec.getMacroSpecies().equals(currentSpecies)) {
                    speciesStack.push(microSpec);
                }
            }
        }
    }
    return allSpecies;
}

From source file:org.polymap.model2.store.geotools.FeatureTypeBuilder.java

protected ComplexType buildComplexType(Class<? extends Composite> compositeClass, String indent)
        throws Exception {
    // fields -> properties
    Collection<PropertyDescriptor> properties = new ArrayList();

    // super classes and mixins
    Deque<Class> stack = new ArrayDeque();
    stack.push(compositeClass);

    while (!stack.isEmpty()) {
        Class type = stack.pop();
        log.debug(indent + "Composite: " + type);

        // super class
        if (type.getSuperclass() != null && !Entity.class.equals(type.getSuperclass())
                && !Composite.class.equals(type.getSuperclass())) {
            stack.push(type.getSuperclass());
        }/* w  ww  . j a  v a2 s.  c  o m*/

        // mixins
        CompositeInfoImpl typeInfo = new CompositeInfoImpl(type);
        //log.debug( indent + "  " + "Mixins: " + typeInfo.getMixins() );
        stack.addAll(typeInfo.getMixins());

        // fields
        for (Field field : type.getDeclaredFields()) {
            // Property or CollectionProperty
            if (Property.class.isAssignableFrom(field.getType())
                    || CollectionProperty.class.isAssignableFrom(field.getType())) {

                PropertyInfoImpl propInfo = new PropertyInfoImpl(field);
                Class<?> binding = propInfo.getType();

                // attribute
                if (binding.isPrimitive() || binding.equals(String.class)
                        || Number.class.isAssignableFrom(binding) || Boolean.class.isAssignableFrom(binding)
                        || Date.class.isAssignableFrom(binding) || binding.isEnum()) {

                    if (binding.isEnum()) {
                        binding = String.class;
                    }
                    AttributeType propType = buildAttributeType(field, binding);
                    AttributeDescriptor desc = factory.createAttributeDescriptor(propType, propType.getName(),
                            0, propInfo.getMaxOccurs(), propInfo.isNullable(), propInfo.getDefaultValue());
                    properties.add(desc);
                    log.debug(indent + "  " + "Attribute: " + desc);
                }
                // geometry
                else if (Geometry.class.isAssignableFrom(binding)) {
                    AttributeType propType = buildAttributeType(field, binding);

                    GeometryType geomType = factory.createGeometryType(propType.getName(),
                            propType.getBinding(), crs, propType.isIdentified(), propType.isAbstract(),
                            propType.getRestrictions(), propType.getSuper(), propType.getDescription());

                    GeometryDescriptor desc = factory.createGeometryDescriptor(geomType, geomType.getName(), 0,
                            1, propInfo.isNullable(), propInfo.getDefaultValue());
                    properties.add(desc);
                    log.debug(indent + "  " + "Geometry: " + desc);
                }
                // complex
                else if (Composite.class.isAssignableFrom(binding)) {
                    ComplexType propType = buildComplexType((Class<? extends Composite>) binding,
                            indent + "    ");
                    AttributeDescriptor desc = factory.createAttributeDescriptor(propType, nameInStore(field),
                            0, propInfo.getMaxOccurs(), propInfo.isNullable(), propInfo.getDefaultValue());
                    properties.add(desc);
                    log.debug(indent + "  " + "Complex Property: " + desc);
                } else {
                    throw new RuntimeException("Property value type is not supported: " + binding);
                }
            }
        }
    }

    NameInStore nameInStore = compositeClass.getAnnotation(NameInStore.class);
    Name name = buildName(nameInStore != null ? nameInStore.value() : compositeClass.getSimpleName());
    boolean isIdentified = false;
    boolean isAbstract = false;
    List<Filter> restrictions = null;
    AttributeType superType = null;
    Description annotation = compositeClass.getAnnotation(Description.class);
    InternationalString description = annotation != null ? SimpleInternationalString.wrap(annotation.value())
            : null;

    return factory.createComplexType(name, properties, isIdentified, isAbstract, restrictions, superType,
            description);
}

From source file:com.google.uzaygezen.core.Pow2LengthBitSetRangeFactory.java

@Override
public Map<Pow2LengthBitSetRange, NodeValue<V>> apply(MapNode<BitVector, V> from) {
    if (from == null) {
        return ImmutableMap.of();
    }/*ww  w  .  ja  va 2s. c o  m*/
    Deque<MapNode<BitVector, V>> inputStack = new ArrayDeque<MapNode<BitVector, V>>();
    Deque<BitVectorWithIterationLevelAndValue> outputStack = new ArrayDeque<BitVectorWithIterationLevelAndValue>();
    inputStack.push(from);
    int n = elementLengthSums.length;
    int bitCount = n == 0 ? 0 : elementLengthSums[n - 1];
    outputStack.push(new BitVectorWithIterationLevelAndValue(BitVectorFactories.OPTIMAL.apply(bitCount), n,
            from.getValue()));
    MapNode<BitVector, V> inputNode;
    Map<Pow2LengthBitSetRange, NodeValue<V>> map = Maps.newHashMap();
    while ((inputNode = inputStack.poll()) != null) {
        BitVectorWithIterationLevelAndValue outputElement = outputStack.poll();
        map.put(new Pow2LengthBitSetRange(outputElement.bitVector,
                outputElement.level == 0 ? 0 : elementLengthSums[outputElement.level - 1]),
                NodeValue.of(outputElement.value, inputNode.getChildren().isEmpty()));
        Preconditions.checkArgument(
                outputElement.level > 0 || (inputNode.getChildren().isEmpty() && outputElement.level >= 0));
        for (Entry<BitVector, MapNode<BitVector, V>> entry : inputNode.getChildren().entrySet()) {
            inputStack.push(entry.getValue());
            BitVector childBitSet = outputElement.bitVector.clone();
            BitVector key = entry.getKey();
            for (int i = key.size() == 0 ? -1 : key.nextSetBit(0); i != -1; i = i == key.size() - 1 ? -1
                    : key.nextSetBit(i + 1)) {
                int bitIndex = (outputElement.level == 1 ? 0 : elementLengthSums[outputElement.level - 2]) + i;
                Preconditions.checkState(bitIndex < bitCount, "bitIndex is too high");
                Preconditions.checkState(!childBitSet.get(bitIndex));
                childBitSet.set(bitIndex);
            }
            outputStack.push(new BitVectorWithIterationLevelAndValue(childBitSet, outputElement.level - 1,
                    entry.getValue().getValue()));
        }
    }
    Preconditions.checkState(outputStack.isEmpty() & !map.isEmpty());
    return map;
}

From source file:io.jmnarloch.spring.cloud.zuul.trie.AbstractTrie.java

protected T remove(N root, String key) {

    int index = 0;
    N node = root;//w  w w .  jav  a2 s .c o  m
    N next;
    final Deque<N> stack = new LinkedList<N>();

    while (index < key.length()) {
        stack.push(node);
        next = node.getNext(getChar(key, index));
        if (next == null) {
            return null;
        }
        node = next;
        index++;
    }
    if (!node.hasValue()) {
        return null;
    }
    final T value = node.getValue();
    node.setSize(node.getSize() - 1);
    node.removeValue();
    index = key.length() - 1;
    while (!stack.isEmpty()) {
        final char c = getChar(key, index);
        node = stack.pop();

        if (node.getNext(c).isEmpty()) {
            node.removeNext(c);
        }
        node.setSize(node.getSize() - 1);
        index--;
    }
    return value;
}

From source file:com.darkstar.beanCartography.utils.finder.Finder.java

/**
 * Search through all contained objects.  Those matching a filter will have
 * the corresponding interceptor executed.
 *
 * @param target object to search//w  ww.j a  va  2s . c  o m
 */
public void find(Object target) {
    if (target == null)
        return;
    Deque<BeanContext> stack = new LinkedList<>();
    Set<BeanContext> visited = new LinkedHashSet<>();
    stack.push(new BeanContext(target));

    while (!stack.isEmpty())
        visit(stack, visited);
}

From source file:org.azrul.langkuik.Langkuik.java

public void initLangkuik(final EntityManagerFactory emf, final UI ui,
        final RelationManagerFactory relationManagerFactory, List<Class<?>> customTypeInterfaces) {

    List<Class<?>> rootClasses = new ArrayList<>();
    for (ManagedType<?> entity : emf.getMetamodel().getManagedTypes()) {
        Class<?> clazz = entity.getJavaType();
        if (clazz.getAnnotation(WebEntity.class).isRoot() == true) {
            rootClasses.add(clazz);//from ww  w.j  a va  2s. c om
        }
    }

    //Manage custom type
    if (customTypeInterfaces == null) {
        customTypeInterfaces = new ArrayList<>();
    }
    //add system level custom type
    customTypeInterfaces.add(AttachmentCustomType.class);
    //create DAOs for custom types
    final List<DataAccessObject<?>> customTypeDaos = new ArrayList<>();
    for (Class<?> clazz : customTypeInterfaces) {
        customTypeDaos.add(new HibernateGenericDAO(emf, clazz));
    }

    //Setup page
    VerticalLayout main = new VerticalLayout();
    VerticalLayout content = new VerticalLayout();
    final Navigator navigator = new Navigator(ui, content);
    final HorizontalLayout breadcrumb = new HorizontalLayout();

    MenuBar menubar = new MenuBar();
    menubar.setId("MENUBAR");
    main.addComponent(menubar);
    main.addComponent(breadcrumb);
    main.addComponent(content);

    final Deque<History> history = new ArrayDeque<>();
    final Configuration config = Configuration.getInstance();

    history.push(new History("START", "Start"));
    StartView startView = new StartView(history, breadcrumb);
    navigator.addView("START", startView);
    MenuBar.MenuItem create = menubar.addItem("Create", null);
    MenuBar.MenuItem view = menubar.addItem("View", null);

    final PageParameter pageParameter = new PageParameter(customTypeDaos, emf, relationManagerFactory, history,
            config, breadcrumb);

    for (final Class rootClass : rootClasses) {
        final WebEntity myObject = (WebEntity) rootClass.getAnnotation(WebEntity.class);
        final DataAccessObject<?> dao = new HibernateGenericDAO<>(emf, rootClass);
        create.addItem("New " + myObject.name(), new MenuBar.Command() {
            @Override
            public void menuSelected(MenuBar.MenuItem selectedItem) {
                Object object = dao.createNew(true);
                BeanView<Object, ?> createNewView = new BeanView<>(object, null, null, pageParameter);
                String targetView = "CREATE_NEW_APPLICATION_" + UUID.randomUUID().toString();
                navigator.addView(targetView, (View) createNewView);
                history.clear();
                history.push(new History("START", "Start"));
                History his = new History(targetView, "Create new " + myObject.name());
                history.push(his);
                navigator.navigateTo(targetView);
            }
        });
        view.addItem("View " + myObject.name(), new MenuBar.Command() {
            @Override
            public void menuSelected(MenuBar.MenuItem selectedItem) {
                PlainTableView<?> seeApplicationView = new PlainTableView<>(rootClass, pageParameter);
                String targetView = "VIEW_APPLICATION_" + UUID.randomUUID().toString();
                navigator.addView(targetView, (View) seeApplicationView);
                history.clear();
                history.push(new History("START", "Start"));
                History his = new History(targetView, "View " + myObject.name());
                history.push(his);
                navigator.navigateTo(targetView);
            }
        });
    }

    menubar.addItem("Logout", null).addItem("Logout", new MenuBar.Command() {
        @Override
        public void menuSelected(MenuBar.MenuItem selectedItem) {
            ConfirmDialog.show(ui, "Please Confirm:", "Are you really sure you want to log out?", "I am",
                    "Not quite", new ConfirmDialog.Listener() {
                        @Override
                        public void onClose(ConfirmDialog dialog) {
                            if (dialog.isConfirmed()) {
                                HttpServletRequest req = (HttpServletRequest) VaadinService.getCurrentRequest();
                                HttpServletResponse resp = (HttpServletResponse) VaadinService
                                        .getCurrentResponse();
                                Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                                SecurityContextLogoutHandler ctxLogOut = new SecurityContextLogoutHandler();
                                ctxLogOut.logout(req, resp, auth);
                            }
                        }
                    });

        }
    });
    navigator.navigateTo("START");
    ui.setContent(main);
}

From source file:net.sf.jasperreports.engine.json.expression.member.evaluation.ObjectConstructionExpressionEvaluator.java

private List<JRJsonNode> goAnywhereDown(JRJsonNode jrJsonNode) {
    List<JRJsonNode> result = new ArrayList<>();
    Deque<JRJsonNode> stack = new ArrayDeque<>();

    if (log.isDebugEnabled()) {
        log.debug("initial stack population with: " + jrJsonNode.getDataNode());
    }/*w  ww .  jav a  2  s  .  co  m*/

    // populate the stack initially
    stack.push(jrJsonNode);

    while (!stack.isEmpty()) {
        JRJsonNode stackNode = stack.pop();
        JsonNode stackDataNode = stackNode.getDataNode();

        addChildrenToStack(stackNode, stack);

        if (log.isDebugEnabled()) {
            log.debug("processing stack element: " + stackDataNode);
        }

        // process the current stack item
        if (stackDataNode.isObject()) {
            JRJsonNode childWithKeys = constructNewObjectNodeWithKeys(stackNode);

            if (childWithKeys != null) {
                result.add(childWithKeys);
            }
        }
    }

    return result;
}