Example usage for java.util Stack pop

List of usage examples for java.util Stack pop

Introduction

In this page you can find the example usage for java.util Stack pop.

Prototype

public synchronized E pop() 

Source Link

Document

Removes the object at the top of this stack and returns that object as the value of this function.

Usage

From source file:com.joliciel.jochre.graphics.SegmenterImpl.java

/**
 * Split a shape into 2 or more shapes, in the case where two letters have been mistakenly joined together.
 * @param shape the shape to split//from ww w.  j a  va  2s  .  c o  m
 * @param sourceImage the source image containing this shape
 * @param maxBridgeWidth maximum width of a bridge between the two letters (measured vertically)
 * @param minLetterWeight minimum pixel count for a shape portion to be counted a separate letter
 * @param maxOverlap maximum vertical overlap (in pixels) between a right-hand and left-hand shape to be counted as separate letters
 * @return List of Shape, where the list is empty if no split was performed
 */
List<Shape> splitShape(Shape shape, SourceImage sourceImage, int maxBridgeWidth, int minLetterWeight,
        int maxOverlap) {
    LOG.debug("Trying to split shape: " + shape.toString());
    LOG.debug("maxBridgeWidth " + maxBridgeWidth);
    LOG.debug("minLetterWeight " + minLetterWeight);
    LOG.debug("maxOverlap " + maxOverlap);

    Collection<BridgeCandidate> bridgeCandidates = ((ShapeInternal) shape).getBridgeCandidates(maxBridgeWidth);

    if (bridgeCandidates.size() > 0) {
        // (B) weight of right shape & weight of left shape > a certain threshold
        // (C) little overlap right boundary of left shape, left boundary of right shape

        // check if the right and left weight of each bridge candidate is sufficiently big
        LOG.debug("minLetterWeight: " + minLetterWeight);
        LOG.debug("maxOverlap: " + maxOverlap);
        LOG.debug("Eliminating candidates based on pixel count and overlap");
        Set<BridgeCandidate> candidatesToEliminate = new HashSet<BridgeCandidate>();
        for (BridgeCandidate candidate : bridgeCandidates) {
            LOG.debug("Bridge candidate: leftPixels = " + candidate.leftPixels + ", rightPixels = "
                    + candidate.rightPixels);
            LOG.debug("leftShapeRightBoundary = " + candidate.leftShapeRightBoundary
                    + ", rightShapeLeftBoundary = " + candidate.rightShapeLeftBoundary);
            boolean isBridge = true;
            if (candidate.rightPixels < minLetterWeight || candidate.leftPixels < minLetterWeight)
                isBridge = false;
            if (candidate.leftShapeRightBoundary - candidate.rightShapeLeftBoundary > maxOverlap)
                isBridge = false;
            if (!isBridge)
                candidatesToEliminate.add(candidate);
        }

        bridgeCandidates.removeAll(candidatesToEliminate);
        LOG.debug("Remaining bridge candidate size: " + bridgeCandidates.size());

    } // have candidates

    List<Shape> shapes = new ArrayList<Shape>();

    // apply any splits detected
    if (bridgeCandidates.size() > 0) {
        int[] startingPoint = shape.getStartingPoint();
        int startX = startingPoint[0];
        int startY = startingPoint[1];

        for (BridgeCandidate bridge : bridgeCandidates) {
            bridge.leftGroup.touched = false;
            bridge.rightGroup.touched = false;
        }

        // perform split
        for (BridgeCandidate bridge : bridgeCandidates) {
            Shape leftShape = graphicsService.getDot(sourceImage, startX, startY);
            leftShape.setLeft(shape.getRight());
            leftShape.setRight(shape.getLeft());
            leftShape.setTop(shape.getBottom());
            leftShape.setBottom(shape.getTop());

            Shape rightShape = graphicsService.getDot(sourceImage, startX, startY);
            rightShape.setLeft(shape.getRight());
            rightShape.setRight(shape.getLeft());
            rightShape.setTop(shape.getBottom());
            rightShape.setBottom(shape.getTop());

            Stack<VerticalLineGroup> groupStack = new Stack<VerticalLineGroup>();
            groupStack.push(bridge.leftGroup);
            while (!groupStack.isEmpty()) {
                VerticalLineGroup lineGroup = groupStack.pop();
                if (lineGroup.touched)
                    continue;
                lineGroup.touched = true;
                LOG.debug("Touching group, pixelCount: " + lineGroup.pixelCount + ", leftBoundary: "
                        + lineGroup.leftBoundary + ", rightBoundary: " + lineGroup.rightBoundary);
                if (shape.getLeft() + lineGroup.leftBoundary < leftShape.getLeft())
                    leftShape.setLeft(shape.getLeft() + lineGroup.leftBoundary);
                if (shape.getLeft() + lineGroup.rightBoundary > leftShape.getRight())
                    leftShape.setRight(shape.getLeft() + lineGroup.rightBoundary);
                if (shape.getTop() + lineGroup.topBoundary < leftShape.getTop())
                    leftShape.setTop(shape.getTop() + lineGroup.topBoundary);
                if (shape.getTop() + lineGroup.bottomBoundary > leftShape.getBottom())
                    leftShape.setBottom(shape.getTop() + lineGroup.bottomBoundary);
                for (BridgeCandidate leftCandidate : lineGroup.leftCandidates) {
                    if (!bridge.equals(leftCandidate) && !(bridgeCandidates.contains(leftCandidate))) {
                        groupStack.push(leftCandidate.leftGroup);
                    }
                }
                for (BridgeCandidate rightCandidate : lineGroup.rightCandidates) {
                    if (!bridge.equals(rightCandidate) && !(bridgeCandidates.contains(rightCandidate))) {
                        groupStack.push(rightCandidate.rightGroup);
                    }
                }
            } // next left group
            groupStack.push(bridge.rightGroup);
            while (!groupStack.isEmpty()) {
                VerticalLineGroup lineGroup = groupStack.pop();
                if (lineGroup.touched)
                    continue;
                lineGroup.touched = true;
                LOG.debug("Touching group, pixelCount: " + lineGroup.pixelCount + ", leftBoundary: "
                        + lineGroup.leftBoundary + ", rightBoundary: " + lineGroup.rightBoundary);
                if (shape.getLeft() + lineGroup.leftBoundary < rightShape.getLeft())
                    rightShape.setLeft(shape.getLeft() + lineGroup.leftBoundary);
                if (shape.getLeft() + lineGroup.rightBoundary > rightShape.getRight())
                    rightShape.setRight(shape.getLeft() + lineGroup.rightBoundary);
                if (shape.getTop() + lineGroup.topBoundary < rightShape.getTop())
                    rightShape.setTop(shape.getTop() + lineGroup.topBoundary);
                if (shape.getTop() + lineGroup.bottomBoundary > rightShape.getBottom())
                    rightShape.setBottom(shape.getTop() + lineGroup.bottomBoundary);
                for (BridgeCandidate leftCandidate : lineGroup.leftCandidates) {
                    if (!bridge.equals(leftCandidate) && !(bridgeCandidates.contains(leftCandidate))) {
                        groupStack.push(leftCandidate.leftGroup);
                    }
                }
                for (BridgeCandidate rightCandidate : lineGroup.rightCandidates) {
                    if (!bridge.equals(rightCandidate) && !(bridgeCandidates.contains(rightCandidate))) {
                        groupStack.push(rightCandidate.rightGroup);
                    }
                }
            } // next right group
            if (leftShape.getWidth() > 0) {
                LOG.debug("Adding left split: " + leftShape);
                shapes.add(leftShape);
            }
            if (rightShape.getWidth() > 0) {
                LOG.debug("Adding right split: " + rightShape);
                shapes.add(rightShape);
            }
        } // next bridge
    } // do we have any bridges?

    // TODO: we need to join split shapes back together when more than 1 split is applied
    // and the shape in the middle is too small on its own (< minPixelCount)
    return shapes;
}

From source file:com.datatorrent.stram.plan.logical.LogicalPlan.java

public void findInvalidDelays(OperatorMeta om, List<List<String>> invalidDelays, Stack<OperatorMeta> stack) {
    stack.push(om);/*from   w  w w  .  j a v a2 s  . c  o m*/

    // 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.getOperatorWrapper();
            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();
}

From source file:com.grottworkshop.gwsvectorsandboxlib.VectorDrawable.java

private void inflateInternal(Resources res, XmlPullParser parser, AttributeSet attrs, Theme theme)
        throws XmlPullParserException, IOException {
    final VectorDrawableState state = mVectorState;
    final VPathRenderer pathRenderer = state.mVPathRenderer;
    boolean noPathTag = true;

    // Use a stack to help to build the group tree.
    // The top of the stack is always the current group.
    final Stack<VGroup> groupStack = new Stack<VGroup>();
    groupStack.push(pathRenderer.mRootGroup);

    int eventType = parser.getEventType();
    while (eventType != XmlPullParser.END_DOCUMENT) {
        if (eventType == XmlPullParser.START_TAG) {
            final String tagName = parser.getName();
            final VGroup currentGroup = groupStack.peek();

            if (SHAPE_PATH.equals(tagName)) {
                final VFullPath path = new VFullPath();
                path.inflate(res, attrs, theme);
                currentGroup.mChildren.add(path);
                if (path.getPathName() != null) {
                    pathRenderer.mVGTargetsMap.put(path.getPathName(), path);
                }/*from  w  w  w .ja  v  a2s.  c  om*/
                noPathTag = false;
                state.mChangingConfigurations |= path.mChangingConfigurations;
            } else if (SHAPE_CLIP_PATH.equals(tagName)) {
                final VClipPath path = new VClipPath();
                path.inflate(res, attrs, theme);
                currentGroup.mChildren.add(path);
                if (path.getPathName() != null) {
                    pathRenderer.mVGTargetsMap.put(path.getPathName(), path);
                }
                state.mChangingConfigurations |= path.mChangingConfigurations;
            } else if (SHAPE_GROUP.equals(tagName)) {
                VGroup newChildGroup = new VGroup();
                newChildGroup.inflate(res, attrs, theme);
                currentGroup.mChildren.add(newChildGroup);
                groupStack.push(newChildGroup);
                if (newChildGroup.getGroupName() != null) {
                    pathRenderer.mVGTargetsMap.put(newChildGroup.getGroupName(), newChildGroup);
                }
                state.mChangingConfigurations |= newChildGroup.mChangingConfigurations;
            }
        } else if (eventType == XmlPullParser.END_TAG) {
            final String tagName = parser.getName();
            if (SHAPE_GROUP.equals(tagName)) {
                groupStack.pop();
            }
        }
        eventType = parser.next();
    }

    // Print the tree out for debug.
    if (DBG_VECTOR_DRAWABLE) {
        printGroupTree(pathRenderer.mRootGroup, 0);
    }

    if (noPathTag) {
        final StringBuffer tag = new StringBuffer();

        if (tag.length() > 0) {
            tag.append(" or ");
        }
        tag.append(SHAPE_PATH);

        throw new XmlPullParserException("no " + tag + " defined");
    }
}

From source file:com.wavemaker.json.JSONMarshaller.java

/**
 * doMarshal() returns some status Objects.
 * //from   w  w  w.  j  a  v a2 s. c om
 * CYCLE_DETECTED_OBJECT will be returned if a cycle was detected at a lower level, and this level needs to be not
 * written.
 * 
 * fieldDefinition should never be null; its enclosed typeDefinition may very well be null.
 */
protected static Object doMarshal(Writer writer, Object obj, Object root, JSONState js, boolean sort,
        boolean topLevel, Stack<Object> touchedObjects, Stack<String> propertyNames,
        FieldDefinition fieldDefinition, int arrayLevel, TypeState typeState, boolean prettyPrint, int level,
        Logger logger) throws IOException {

    if (fieldDefinition == null) {
        throw new NullArgumentException("fieldDefinition");
    }

    touchedObjects.push(obj);
    try {
        if (obj != null && fieldDefinition.getTypeDefinition() == null) {
            fieldDefinition = ReflectTypeUtils.getFieldDefinition(obj.getClass(), typeState, false, null);
            arrayLevel = 0;
        }

        // do value conversion
        if (js.getValueTransformer() != null) {
            Tuple.Three<Object, FieldDefinition, Integer> tuple = js.getValueTransformer().transformToJSON(obj,
                    fieldDefinition, arrayLevel, root, getPropertyName(propertyNames, js), js.getTypeState());
            if (tuple != null) {
                obj = tuple.v1;
                fieldDefinition = tuple.v2;
                arrayLevel = tuple.v3;
            }
        }

        if (arrayLevel == fieldDefinition.getDimensions() && fieldDefinition.getTypeDefinition() != null
                && fieldDefinition.getTypeDefinition() instanceof WriteObjectConverter) {
            ((WriteObjectConverter) fieldDefinition.getTypeDefinition()).writeObject(obj, root,
                    getPropertyName(propertyNames, js), writer);
        } else if (obj == null) {
            writer.write("null");

            // handle arrays & Collections
        } else if (arrayLevel < fieldDefinition.getDimensions() || obj.getClass().isArray()) {

            writer.write("[");
            boolean firstElement = true;

            if (obj instanceof Collection) {
                for (Object elem : (Collection<?>) obj) {
                    if (!firstElement) {
                        writer.write(",");

                        if (prettyPrint) {
                            writer.write(" ");
                        }
                    }

                    doMarshal(writer, elem, root, js, sort, false, touchedObjects, propertyNames,
                            fieldDefinition, arrayLevel + 1, typeState, prettyPrint, level, logger);

                    if (firstElement) {
                        firstElement = false;
                    }
                }
            } else if (obj.getClass().isArray()) {
                int length = Array.getLength(obj);
                Object elem;

                for (int i = 0; i < length; i++) {
                    elem = Array.get(obj, i);

                    if (!firstElement) {
                        writer.write(",");

                        if (prettyPrint) {
                            writer.write(" ");
                        }
                    }

                    doMarshal(writer, elem, root, js, sort, false, touchedObjects, propertyNames,
                            fieldDefinition, arrayLevel + 1, typeState, prettyPrint, level, logger);
                    if (firstElement) {
                        firstElement = false;
                    }
                }
            } else {
                throw new WMRuntimeException(MessageResource.JSON_UNKNOWN_COLL_OR_ARRAY, obj, obj.getClass());
            }

            writer.write("]");
            // check for primitives
        } else if (fieldDefinition.getTypeDefinition() != null
                && fieldDefinition.getTypeDefinition() instanceof PrimitiveTypeDefinition) {
            ((PrimitiveTypeDefinition) fieldDefinition.getTypeDefinition()).toJson(writer, obj);
            // handle maps & objects
        } else {
            handleObject(obj, root, js, writer, touchedObjects, propertyNames, sort, fieldDefinition,
                    arrayLevel, typeState, prettyPrint, level, logger);
        }

        return null;
    } finally {
        touchedObjects.pop();
    }
}

From source file:com.bettervectordrawable.lib.graphics.drawable.VectorDrawable.java

private void inflateInternal(Resources res, XmlPullParser parser, AttributeSet attrs, Theme theme)
        throws XmlPullParserException, IOException {
    final VectorDrawableState state = mVectorState;
    final VPathRenderer pathRenderer = state.mVPathRenderer;
    boolean noPathTag = true;
    // Use a stack to help to build the group tree.
    // The top of the stack is always the current group.
    final Stack<VGroup> groupStack = new Stack<VGroup>();
    groupStack.push(pathRenderer.mRootGroup);
    int eventType = parser.getEventType();
    while (eventType != XmlPullParser.END_DOCUMENT) {
        if (eventType == XmlPullParser.START_TAG) {
            final String tagName = parser.getName();
            final VGroup currentGroup = groupStack.peek();
            if (SHAPE_PATH.equals(tagName)) {
                final VFullPath path = new VFullPath();
                path.inflate(res, attrs, theme);
                currentGroup.mChildren.add(path);
                if (path.getPathName() != null) {
                    pathRenderer.mVGTargetsMap.put(path.getPathName(), path);
                }/*  w  w w.  ja v  a2  s .  co  m*/
                noPathTag = false;
                state.mChangingConfigurations |= path.mChangingConfigurations;
            } else if (SHAPE_CLIP_PATH.equals(tagName)) {
                final VClipPath path = new VClipPath();
                path.inflate(res, attrs, theme);
                currentGroup.mChildren.add(path);
                if (path.getPathName() != null) {
                    pathRenderer.mVGTargetsMap.put(path.getPathName(), path);
                }
                state.mChangingConfigurations |= path.mChangingConfigurations;
            } else if (SHAPE_GROUP.equals(tagName)) {
                VGroup newChildGroup = new VGroup();
                newChildGroup.inflate(res, attrs, theme);
                currentGroup.mChildren.add(newChildGroup);
                groupStack.push(newChildGroup);
                if (newChildGroup.getGroupName() != null) {
                    pathRenderer.mVGTargetsMap.put(newChildGroup.getGroupName(), newChildGroup);
                }
                state.mChangingConfigurations |= newChildGroup.mChangingConfigurations;
            }
        } else if (eventType == XmlPullParser.END_TAG) {
            final String tagName = parser.getName();
            if (SHAPE_GROUP.equals(tagName)) {
                groupStack.pop();
            }
        }
        eventType = parser.next();
    }
    // Print the tree out for debug.
    if (DBG_VECTOR_DRAWABLE) {
        printGroupTree(pathRenderer.mRootGroup, 0);
    }
    if (noPathTag) {
        final StringBuffer tag = new StringBuffer();
        if (tag.length() > 0) {
            tag.append(" or ");
        }
        tag.append(SHAPE_PATH);
        throw new XmlPullParserException("no " + tag + " defined");
    }
}

From source file:com.espertech.esper.event.util.RendererMeta.java

/**
 * Ctor.//w  ww. j a  v a  2  s .  c  om
 * @param eventType to render
 * @param stack the stack of properties to avoid looping
 * @param options rendering options
 */
public RendererMeta(EventType eventType, Stack<EventTypePropertyPair> stack, RendererMetaOptions options) {
    ArrayList<GetterPair> gettersSimple = new ArrayList<GetterPair>();
    ArrayList<GetterPair> gettersIndexed = new ArrayList<GetterPair>();
    ArrayList<GetterPair> gettersMapped = new ArrayList<GetterPair>();
    ArrayList<NestedGetterPair> gettersNested = new ArrayList<NestedGetterPair>();

    EventPropertyDescriptor[] descriptors = eventType.getPropertyDescriptors();
    for (EventPropertyDescriptor desc : descriptors) {
        String propertyName = desc.getPropertyName();

        if ((!desc.isIndexed()) && (!desc.isMapped()) && (!desc.isFragment())) {
            EventPropertyGetter getter = eventType.getGetter(propertyName);
            if (getter == null) {
                log.warn("No getter returned for event type '" + eventType.getName() + "' and property '"
                        + propertyName + "'");
                continue;
            }
            gettersSimple.add(new GetterPair(getter, propertyName,
                    OutputValueRendererFactory.getOutputValueRenderer(desc.getPropertyType(), options)));
        }

        if (desc.isIndexed() && !desc.isRequiresIndex() && (!desc.isFragment())) {
            EventPropertyGetter getter = eventType.getGetter(propertyName);
            if (getter == null) {
                log.warn("No getter returned for event type '" + eventType.getName() + "' and property '"
                        + propertyName + "'");
                continue;
            }
            gettersIndexed.add(new GetterPair(getter, propertyName,
                    OutputValueRendererFactory.getOutputValueRenderer(desc.getPropertyType(), options)));
        }

        if (desc.isMapped() && !desc.isRequiresMapkey() && (!desc.isFragment())) {
            EventPropertyGetter getter = eventType.getGetter(propertyName);
            if (getter == null) {
                log.warn("No getter returned for event type '" + eventType.getName() + "' and property '"
                        + propertyName + "'");
                continue;
            }
            gettersMapped.add(new GetterPair(getter, propertyName,
                    OutputValueRendererFactory.getOutputValueRenderer(desc.getPropertyType(), options)));
        }

        if (desc.isFragment()) {
            EventPropertyGetter getter = eventType.getGetter(propertyName);
            FragmentEventType fragmentType = eventType.getFragmentType(propertyName);
            if (getter == null) {
                log.warn("No getter returned for event type '" + eventType.getName() + "' and property '"
                        + propertyName + "'");
                continue;
            }
            if (fragmentType == null) {
                log.warn("No fragment type returned for event type '" + eventType.getName() + "' and property '"
                        + propertyName + "'");
                continue;
            }

            EventTypePropertyPair pair = new EventTypePropertyPair(fragmentType.getFragmentType(),
                    propertyName);
            if ((options.isPreventLooping() && stack.contains(pair))) {
                continue; // prevent looping behavior on self-references
            }

            stack.push(pair);
            RendererMeta fragmentMetaData = new RendererMeta(fragmentType.getFragmentType(), stack, options);
            stack.pop();

            gettersNested.add(
                    new NestedGetterPair(getter, propertyName, fragmentMetaData, fragmentType.isIndexed()));
        }
    }

    simpleProperties = gettersSimple.toArray(new GetterPair[gettersSimple.size()]);
    indexProperties = gettersIndexed.toArray(new GetterPair[gettersIndexed.size()]);
    mappedProperties = gettersMapped.toArray(new GetterPair[gettersMapped.size()]);
    nestedProperties = gettersNested.toArray(new NestedGetterPair[gettersNested.size()]);
}

From source file:com.zeroio.webdav.WebdavServlet.java

/**
 * PROPFIND Method./*ww w  .ja va  2  s .  co m*/
 *
 * @param context Description of the Parameter
 * @throws ServletException Description of the Exception
 * @throws IOException      Description of the Exception
 */
protected void doPropfind(ActionContext context) throws ServletException, IOException {

    String path = getRelativePath(context.getRequest());

    //fix for windows clients
    if (path.equals("/files")) {
        path = "";
    }

    if (path.endsWith("/")) {
        path = path.substring(0, path.length() - 1);
    }

    if ((path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) {
        context.getResponse().sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }

    if (path.indexOf("/.") > -1 || path.indexOf(".DS_Store") > -1) {
        //Fix for MACOSX finder. Do not allow requests for files starting with a period
        return;
    }
    //System.out.println("METHOD PROPFIND....PATH: " + path);
    // Properties which are to be displayed.
    Vector properties = null;
    // Propfind depth by default 1 for performance reasons
    int depth = 1;
    // Propfind type
    int type = FIND_ALL_PROP;

    String depthStr = context.getRequest().getHeader("Depth");
    if (depthStr == null) {
        depth = INFINITY;
    } else {
        if (depthStr.equals("0")) {
            depth = 0;
        } else if (depthStr.equals("1")) {
            depth = 1;
        } else if (depthStr.equals("infinity")) {
            depth = INFINITY;
        }
    }

    /*
     *  Read the request xml and determine all the properties
     */
    Node propNode = null;
    DocumentBuilder documentBuilder = getDocumentBuilder();
    try {
        Document document = documentBuilder.parse(new InputSource(context.getRequest().getInputStream()));
        // Get the root element of the document
        Element rootElement = document.getDocumentElement();
        NodeList childList = rootElement.getChildNodes();
        for (int i = 0; i < childList.getLength(); i++) {
            Node currentNode = childList.item(i);
            switch (currentNode.getNodeType()) {
            case Node.TEXT_NODE:
                break;
            case Node.ELEMENT_NODE:
                if (currentNode.getNodeName().endsWith("prop")) {
                    type = FIND_BY_PROPERTY;
                    propNode = currentNode;
                }
                if (currentNode.getNodeName().endsWith("propname")) {
                    type = FIND_PROPERTY_NAMES;
                }
                if (currentNode.getNodeName().endsWith("allprop")) {
                    type = FIND_ALL_PROP;
                }
                break;
            }
        }
    } catch (Exception e) {
        // Most likely there was no content : we use the defaults.
        // TODO : Enhance that !
        //e.printStackTrace(System.out);
    }

    if (type == FIND_BY_PROPERTY) {
        properties = new Vector();
        if (!properties.contains("creationdate")) {
            //If the request did not contain creationdate property then add this to requested properties
            //to make the information available for clients
            properties.addElement("creationdate");
        }
        NodeList childList = propNode.getChildNodes();
        for (int i = 0; i < childList.getLength(); i++) {
            Node currentNode = childList.item(i);
            switch (currentNode.getNodeType()) {
            case Node.TEXT_NODE:
                break;
            case Node.ELEMENT_NODE:
                String nodeName = currentNode.getNodeName();
                String propertyName = null;
                if (nodeName.indexOf(':') != -1) {
                    propertyName = nodeName.substring(nodeName.indexOf(':') + 1);
                } else {
                    propertyName = nodeName;
                }
                // href is a live property which is handled differently
                properties.addElement(propertyName);
                break;
            }
        }
    }

    // Properties have been determined
    // Retrieve the resources

    Connection db = null;
    boolean exists = true;
    boolean status = true;
    Object current = null;
    Object child = null;
    ModuleContext resources = null;
    SystemStatus thisSystem = null;
    StringBuffer xmlsb = new StringBuffer();
    try {
        db = this.getConnection(context);
        resources = getCFSResources(db, context);
        if (resources == null) {
            context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
        thisSystem = this.getSystemStatus(context);
        current = resources.lookup(thisSystem, db, path);
        if (current instanceof ModuleContext) {
            //System.out.println( ((ModuleContext) current).toString());
        }
    } catch (NamingException e) {
        //e.printStackTrace(System.out);
        exists = false;
        int slash = path.lastIndexOf('/');
        if (slash != -1) {
            String parentPath = path.substring(0, slash);
            Vector currentLockNullResources = (Vector) lockNullResources.get(parentPath);
            if (currentLockNullResources != null) {
                Enumeration lockNullResourcesList = currentLockNullResources.elements();
                while (lockNullResourcesList.hasMoreElements()) {
                    String lockNullPath = (String) lockNullResourcesList.nextElement();
                    if (lockNullPath.equals(path)) {
                        context.getResponse().setStatus(WebdavStatus.SC_MULTI_STATUS);
                        context.getResponse().setContentType("text/xml; charset=UTF-8");
                        // Create multistatus object
                        XMLWriter generatedXML = new XMLWriter(context.getResponse().getWriter());
                        generatedXML.writeXMLHeader();
                        generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(),
                                XMLWriter.OPENING);
                        parseLockNullProperties(context.getRequest(), generatedXML, lockNullPath, type,
                                properties);
                        generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);
                        generatedXML.sendData();
                        //e.printStackTrace(System.out);
                        return;
                    }
                }
            }
        }
    } catch (SQLException e) {
        e.printStackTrace(System.out);
        context.getResponse().sendError(CFS_SQLERROR, e.getMessage());
        status = false;
    } finally {
        this.freeConnection(db, context);
    }

    if (!status) {
        return;
    }

    if (!exists) {
        context.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND, path);
        return;
    }

    context.getResponse().setStatus(WebdavStatus.SC_MULTI_STATUS);
    context.getResponse().setContentType("text/xml; charset=UTF-8");
    // Create multistatus object
    ////System.out.println("Creating Multistatus Object");

    XMLWriter generatedXML = new XMLWriter(context.getResponse().getWriter());
    generatedXML.writeXMLHeader();
    generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(), XMLWriter.OPENING);

    //System.out.println("Depth: " + depth);
    if (depth == 0) {
        parseProperties(context, resources, generatedXML, path, type, properties);
    } else {
        // The stack always contains the object of the current level
        Stack stack = new Stack();
        stack.push(path);
        // Stack of the objects one level below
        Stack stackBelow = new Stack();

        while ((!stack.isEmpty()) && (depth >= 0)) {
            String currentPath = (String) stack.pop();
            try {
                if (!currentPath.equals(path)) {
                    //object at url currentPath not yet looked up. so perform lookup at url currentPath
                    child = resources.lookup(currentPath);
                    parseProperties(context, resources, generatedXML, currentPath, type, properties);
                }
            } catch (NamingException e) {
                e.printStackTrace(System.out);
                continue;
            }

            if (!status) {
                return;
            }

            if ((current instanceof ModuleContext) && depth > 0) {
                // Get a list of all the resources at the current path and store them
                // in the stack
                try {
                    NamingEnumeration enum1 = ((ModuleContext) current).list("");
                    int count = 0;
                    while (enum1.hasMoreElements()) {
                        NameClassPair ncPair = (NameClassPair) enum1.nextElement();
                        String newPath = currentPath;
                        if (!(newPath.endsWith("/"))) {
                            newPath += "/";
                        }
                        newPath += ncPair.getName();
                        //System.out.println("STACKING CHILD: " + newPath);
                        stackBelow.push(newPath);
                        count++;
                    }
                    if (currentPath.equals(path) && count == 0) {
                        // This directory does not have any files or folders.
                        //System.out.println("DIRECTORY HAS NO FILES OR FOLDERS...");
                        parseProperties(context, resources, generatedXML, properties);
                    }
                } catch (NamingException e) {
                    //e.printStackTrace(System.out);
                    context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
                    return;
                }

                // Displaying the lock-null resources present in that collection
                String lockPath = currentPath;
                if (lockPath.endsWith("/")) {
                    lockPath = lockPath.substring(0, lockPath.length() - 1);
                }
                Vector currentLockNullResources = (Vector) lockNullResources.get(lockPath);
                if (currentLockNullResources != null) {
                    Enumeration lockNullResourcesList = currentLockNullResources.elements();
                    while (lockNullResourcesList.hasMoreElements()) {
                        String lockNullPath = (String) lockNullResourcesList.nextElement();
                        System.out.println("Lock null path: " + lockNullPath);
                        parseLockNullProperties(context.getRequest(), generatedXML, lockNullPath, type,
                                properties);
                    }
                }
            }
            if (stack.isEmpty()) {
                depth--;
                stack = stackBelow;
                stackBelow = new Stack();
            }
            xmlsb.append(generatedXML.toString());
            //System.out.println("xml : " + generatedXML.toString());
            generatedXML.sendData();
        }
    }

    Iterator locks = lockNullResources.keySet().iterator();
    while (locks.hasNext()) {
        String lockpath = (String) locks.next();
        //System.out.println("LOCK PATH: " + lockpath);
    }

    generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);
    xmlsb.append(generatedXML.toString());
    generatedXML.sendData();
    //System.out.println("xml: " + xmlsb.toString());
}

From source file:com.almarsoft.GroundhogReader.MessageListActivity.java

private void fillListNonRecursive(Article root, int depth, String replyto) {

    Stack<MiniHeader> stack = new Stack<MiniHeader>();

    boolean markReplies = mPrefs.getBoolean("markReplies", true);
    boolean finished = false;

    String clean_subject;/*from ww w .j a  v a  2  s  . co m*/
    MiniHeader tmpMiniItem;
    HeaderItemClass ih = null;
    String[] refsArray;
    String msgId;

    ArrayList<HeaderItemClass> nonStarredItems = new ArrayList<HeaderItemClass>();
    HashSet<String> bannedTrollsSet = DBUtils.getBannedTrolls(getApplicationContext());
    HashSet<String> starredSet = DBUtils.getStarredSubjectsSet(getApplicationContext());

    // Proxy for speed
    HashSet<String> myPostsSetProxy = mMyPostsSet;
    ArrayList<HeaderItemClass> headerItemsListProxy = new ArrayList<HeaderItemClass>();
    int refsArrayLen;

    while (!finished) {

        if (root == null)
            finished = true;

        root.setReplyTo(replyto);

        if (!root.isDummy()) {
            ih = new HeaderItemClass(root, depth);

            // Don't feed the troll
            if (!bannedTrollsSet.contains(root.getFrom())) {

                // Put the replies in red (if configured)
                if (markReplies) {
                    refsArray = root.getReferences();
                    refsArrayLen = refsArray.length;
                    msgId = null;

                    if (refsArray != null && refsArrayLen > 0) {
                        msgId = refsArray[refsArrayLen - 1];
                    }

                    if (msgId != null && myPostsSetProxy != null && myPostsSetProxy.contains(msgId))
                        ih.myreply = true;
                    else
                        ih.myreply = false;
                }

                clean_subject = root.simplifiedSubject();
                if (starredSet.contains(clean_subject)) {
                    ih.starred = true;
                    headerItemsListProxy.add(ih); // Starred items first
                } else {
                    // Nonstarred items will be added to mHeaderItemsList at the end
                    nonStarredItems.add(ih);
                }
            }
        }

        if (root.next != null) {
            tmpMiniItem = new MiniHeader(root.next, depth, replyto);
            stack.push(tmpMiniItem);
        }

        if (root.kid != null) {

            replyto = root.getFrom();
            if (!root.isDummy())
                ++depth;
            root = root.kid;

        } else if (!stack.empty()) {

            tmpMiniItem = stack.pop();
            root = tmpMiniItem.article;
            depth = tmpMiniItem.depth;
            replyto = tmpMiniItem.replyto;

        } else
            finished = true;

    }

    // Now add the non starred items after the starred ones
    int nonStarredItemsLen = nonStarredItems.size();
    for (int i = 0; i < nonStarredItemsLen; i++) {
        headerItemsListProxy.add(nonStarredItems.get(i));
    }

    mHeaderItemsList = headerItemsListProxy;
    nonStarredItems = null;
}

From source file:com.hippo.vector.VectorDrawable.java

private void inflateInternal(Context context, XmlPullParser parser, AttributeSet attrs)
        throws XmlPullParserException, IOException {
    final VectorDrawableState state = mVectorState;
    final VPathRenderer pathRenderer = state.mVPathRenderer;
    boolean noPathTag = true;

    // Use a stack to help to build the group tree.
    // The top of the stack is always the current group.
    final Stack<VGroup> groupStack = new Stack<>();
    groupStack.push(pathRenderer.mRootGroup);

    int eventType = parser.getEventType();
    while (eventType != XmlPullParser.END_DOCUMENT) {
        if (eventType == XmlPullParser.START_TAG) {
            final String tagName = parser.getName();
            final VGroup currentGroup = groupStack.peek();

            if (SHAPE_PATH.equals(tagName)) {
                final VFullPath path = new VFullPath();
                path.inflate(context, attrs);
                currentGroup.mChildren.add(path);
                if (path.getPathName() != null) {
                    pathRenderer.mVGTargetsMap.put(path.getPathName(), path);
                }//from   w w  w.ja  v  a2s .co  m
                noPathTag = false;
                state.mChangingConfigurations |= path.mChangingConfigurations;
            } else if (SHAPE_CLIP_PATH.equals(tagName)) {
                final VClipPath path = new VClipPath();
                path.inflate(context, attrs);
                currentGroup.mChildren.add(path);
                if (path.getPathName() != null) {
                    pathRenderer.mVGTargetsMap.put(path.getPathName(), path);
                }
                state.mChangingConfigurations |= path.mChangingConfigurations;
            } else if (SHAPE_GROUP.equals(tagName)) {
                VGroup newChildGroup = new VGroup();
                newChildGroup.inflate(context, attrs);
                currentGroup.mChildren.add(newChildGroup);
                groupStack.push(newChildGroup);
                if (newChildGroup.getGroupName() != null) {
                    pathRenderer.mVGTargetsMap.put(newChildGroup.getGroupName(), newChildGroup);
                }
                state.mChangingConfigurations |= newChildGroup.mChangingConfigurations;
            }
        } else if (eventType == XmlPullParser.END_TAG) {
            final String tagName = parser.getName();
            if (SHAPE_GROUP.equals(tagName)) {
                groupStack.pop();
            }
        }
        eventType = parser.next();
    }

    // Print the tree out for debug.
    if (DBG_VECTOR_DRAWABLE) {
        printGroupTree(pathRenderer.mRootGroup, 0);
    }

    if (noPathTag) {
        final StringBuilder tag = new StringBuilder();

        if (tag.length() > 0) {
            tag.append(" or ");
        }
        tag.append(SHAPE_PATH);

        throw new XmlPullParserException("no " + tag + " defined");
    }
}

From source file:android.support.graphics.drawable.VectorDrawableCompat.java

private void inflateInternal(Resources res, XmlPullParser parser, AttributeSet attrs, Theme theme)
        throws XmlPullParserException, IOException {
    final VectorDrawableCompatState state = mVectorState;
    final VPathRenderer pathRenderer = state.mVPathRenderer;
    boolean noPathTag = true;

    // Use a stack to help to build the group tree.
    // The top of the stack is always the current group.
    final Stack<VGroup> groupStack = new Stack<VGroup>();
    groupStack.push(pathRenderer.mRootGroup);

    int eventType = parser.getEventType();
    while (eventType != XmlPullParser.END_DOCUMENT) {
        if (eventType == XmlPullParser.START_TAG) {
            final String tagName = parser.getName();
            final VGroup currentGroup = groupStack.peek();
            if (SHAPE_PATH.equals(tagName)) {
                final VFullPath path = new VFullPath();
                path.inflate(res, attrs, theme, parser);
                currentGroup.mChildren.add(path);
                if (path.getPathName() != null) {
                    pathRenderer.mVGTargetsMap.put(path.getPathName(), path);
                }/* www.j  a v a2 s .co  m*/
                noPathTag = false;
                state.mChangingConfigurations |= path.mChangingConfigurations;
            } else if (SHAPE_CLIP_PATH.equals(tagName)) {
                final VClipPath path = new VClipPath();
                path.inflate(res, attrs, theme, parser);
                currentGroup.mChildren.add(path);
                if (path.getPathName() != null) {
                    pathRenderer.mVGTargetsMap.put(path.getPathName(), path);
                }
                state.mChangingConfigurations |= path.mChangingConfigurations;
            } else if (SHAPE_GROUP.equals(tagName)) {
                VGroup newChildGroup = new VGroup();
                newChildGroup.inflate(res, attrs, theme, parser);
                currentGroup.mChildren.add(newChildGroup);
                groupStack.push(newChildGroup);
                if (newChildGroup.getGroupName() != null) {
                    pathRenderer.mVGTargetsMap.put(newChildGroup.getGroupName(), newChildGroup);
                }
                state.mChangingConfigurations |= newChildGroup.mChangingConfigurations;
            }
        } else if (eventType == XmlPullParser.END_TAG) {
            final String tagName = parser.getName();
            if (SHAPE_GROUP.equals(tagName)) {
                groupStack.pop();
            }
        }
        eventType = parser.next();
    }

    // Print the tree out for debug.
    if (DBG_VECTOR_DRAWABLE) {
        printGroupTree(pathRenderer.mRootGroup, 0);
    }

    if (noPathTag) {
        final StringBuffer tag = new StringBuffer();

        if (tag.length() > 0) {
            tag.append(" or ");
        }
        tag.append(SHAPE_PATH);

        throw new XmlPullParserException("no " + tag + " defined");
    }
}