Example usage for java.util Stack push

List of usage examples for java.util Stack push

Introduction

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

Prototype

public E push(E item) 

Source Link

Document

Pushes an item onto the top of this stack.

Usage

From source file:ca.weblite.xmlvm.XMLVM.java

/**
 * Finds all of the classes that may be dirty due to changes in 
 * an initial set of classes./*from  w w w  . ja  v  a2 s.c o m*/
 * @param changedClasses An initial set of classes that were modified.
 * @param dirtyClasses The full set of classes that may be dirty due to these
 * changes.  This will necessarily be a superset of changedClasses.  
 * @param depsDir The directory the contains the deps.
 * @throws IOException 
 */
public void collectDirtyClasses(Set<String> changedClasses, Set<String> dirtyClasses, File depsDir)
        throws IOException {

    Set<String> processed = new HashSet<String>();
    Stack<String> stack = new Stack<>();
    stack.addAll(changedClasses);
    dirtyClasses.addAll(changedClasses);
    while (!stack.isEmpty()) {
        String cls = stack.pop();
        if (processed.contains(cls)) {
            continue;
        } else {
            processed.add(cls);
        }
        File depsFile = new File(depsDir, cls + ".deps");
        if (depsFile.exists()) {
            List<String> lines = FileUtils.readLines(depsFile);
            for (String line : lines) {
                String[] parts = line.split(" ");
                String clsName = parts[0];
                if (dirtyClasses.contains(clsName)) {
                    // This class is already marked dirty.
                    continue;
                }
                String kind = parts[1];

                switch (kind) {
                case "usage":
                    dirtyClasses.add(clsName);
                    break;
                case "super":
                case "interface":
                    dirtyClasses.add(clsName);
                    stack.push(clsName);
                    break;
                }
            }
        }
    }

}

From source file:gdt.data.store.Entigrator.java

/**
 * List containers of the entity //from  w w  w . java2 s  . c  o m
 *  @param entity the entity.
 * @return the array of keys of containers.
 */
public String[] ent_listContainers(Sack entity) {
    if (entity == null) {
        // LOGGER.severe(":ent_listContainers:entity is null");
        return null;
    }
    Core[] ca = entity.elementGet("container");
    if (ca == null) {
        // LOGGER.info(":ent_listContainers:no 'container' element in entity=" + entity.getProperty("label"));
        return null;
    }
    Stack<String> s = new Stack<String>();
    Sack container;
    boolean modified = false;
    for (Core aCa : ca) {
        if (entity.getKey().equals(aCa.value))
            continue;
        container = getMember("entity.base", aCa.value);
        if (container == null) {
            entity.removeElementItem("container", aCa.name);
            modified = true;
            continue;
        }
        s.push(aCa.value);
    }
    if (modified)
        save(entity);
    int cnt = s.size();
    if (cnt < 1) {
        //LOGGER.info(":ent_listContainers:empty 'container' element in entity=" + entity.getProperty("label"));
        return null;
    }
    String[] sa = new String[cnt];
    for (int i = 0; i < cnt; i++)
        sa[i] = s.pop();
    return sa;
}

From source file:com.sqewd.open.dal.core.persistence.db.EntityHelper.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void setColumnValue(final ResultSet rs, final StructAttributeReflect attr,
        final AbstractEntity entity, final AbstractJoinGraph gr, final Stack<KeyValuePair<Class<?>>> path)
        throws Exception {

    KeyValuePair<String> alias = gr.getAliasFor(path, attr.Column, 0);
    String tabprefix = alias.getKey();

    if (EnumPrimitives.isPrimitiveType(attr.Field.getType())) {
        EnumPrimitives prim = EnumPrimitives.type(attr.Field.getType());
        switch (prim) {
        case ECharacter:
            String sv = rs.getString(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), sv.charAt(0));
            }/* w  w w.jav  a 2 s.c  o  m*/
            break;
        case EShort:
            short shv = rs.getShort(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), shv);
            }
            break;
        case EInteger:
            int iv = rs.getInt(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), iv);
            }
            break;
        case ELong:
            long lv = rs.getLong(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), lv);
            }
            break;
        case EFloat:
            float fv = rs.getFloat(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), fv);
            }
            break;
        case EDouble:
            double dv = rs.getDouble(tabprefix + "." + attr.Column);
            if (!rs.wasNull()) {
                PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), dv);
            }
            break;
        default:
            throw new Exception("Unsupported Data type [" + prim.name() + "]");
        }
    } else if (attr.Convertor != null) {
        String value = rs.getString(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            attr.Convertor.load(entity, attr.Column, value);
        }
    } else if (attr.Field.getType().equals(String.class)) {
        String value = rs.getString(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), value);
        }
    } else if (attr.Field.getType().equals(Date.class)) {
        long value = rs.getLong(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            Date dt = new Date(value);
            PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), dt);
        }
    } else if (attr.Field.getType().isEnum()) {
        String value = rs.getString(tabprefix + "." + attr.Column);
        if (!rs.wasNull()) {
            Class ecls = attr.Field.getType();
            Object evalue = Enum.valueOf(ecls, value);
            PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), evalue);
        }
    } else if (attr.Reference != null) {
        Class<?> rt = Class.forName(attr.Reference.Class);
        Object obj = rt.newInstance();
        if (!(obj instanceof AbstractEntity))
            throw new Exception("Unsupported Entity type [" + rt.getCanonicalName() + "]");
        AbstractEntity rentity = (AbstractEntity) obj;
        if (path.size() > 0) {
            path.peek().setKey(attr.Column);
        }

        KeyValuePair<Class<?>> cls = new KeyValuePair<Class<?>>();
        cls.setValue(rentity.getClass());
        path.push(cls);
        setEntity(rentity, rs, gr, path);
        PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), rentity);
        path.pop();
    }
}

From source file:org.apache.tajo.plan.LogicalPlanner.java

@Override
public LogicalNode visitProjection(PlanContext context, Stack<Expr> stack, Projection projection)
        throws TajoException {

    LogicalPlan plan = context.plan;/*from  ww  w  . j  a v  a2s  .  c om*/
    QueryBlock block = context.queryBlock;

    // If a non-from statement is given
    if (!projection.hasChild()) {
        return buildPlanForNoneFromStatement(context, stack, projection);
    }

    String[] referenceNames;
    // in prephase, insert all target list into NamedExprManagers.
    // Then it gets reference names, each of which points an expression in target list.
    Pair<String[], ExprNormalizer.WindowSpecReferences[]> referencesPair = doProjectionPrephase(context,
            projection);
    referenceNames = referencesPair.getFirst();

    ////////////////////////////////////////////////////////
    // Visit and Build Child Plan
    ////////////////////////////////////////////////////////
    stack.push(projection);
    LogicalNode child = visit(context, stack, projection.getChild());

    // check if it is implicit aggregation. If so, it inserts group-by node to its child.
    if (block.isAggregationRequired()) {
        child = insertGroupbyNode(context, child, stack);
    }

    if (block.hasWindowSpecs()) {
        LogicalNode windowAggNode = insertWindowAggNode(context, child, stack, referenceNames,
                referencesPair.getSecond());
        if (windowAggNode != null) {
            child = windowAggNode;
        }
    }
    stack.pop();
    ////////////////////////////////////////////////////////

    ProjectionNode projectionNode;
    Target[] targets;
    targets = buildTargets(context, referenceNames);

    // Set ProjectionNode
    projectionNode = context.queryBlock.getNodeFromExpr(projection);
    projectionNode.init(projection.isDistinct(), targets);
    projectionNode.setChild(child);
    projectionNode.setInSchema(child.getOutSchema());

    if (projection.isDistinct() && block.hasNode(NodeType.GROUP_BY)) {
        throw makeSyntaxError("Cannot support grouping and distinct at the same time yet");
    } else {
        if (projection.isDistinct()) {
            insertDistinctOperator(context, projectionNode, child, stack);
        }
    }

    // It's for debugging and unit tests purpose.
    // It sets raw targets, all of them are raw expressions instead of references.
    if (context.debugOrUnitTests) {
        setRawTargets(context, targets, referenceNames, projection);
    }

    verifyProjectedFields(block, projectionNode);
    return projectionNode;
}

From source file:org.apache.tajo.engine.planner.LogicalPlanner.java

@Override
public LogicalNode visitGroupBy(PlanContext context, Stack<Expr> stack, Aggregation aggregation)
        throws PlanningException {

    // Initialization Phase:
    LogicalPlan plan = context.plan;//from  www. j ava2s  . co m
    QueryBlock block = context.queryBlock;

    // Normalize grouping keys and add normalized grouping keys to NamedExprManager
    int groupingKeyNum = aggregation.getGroupSet()[0].getGroupingSets().length;
    ExprNormalizedResult[] normalizedResults = new ExprNormalizedResult[groupingKeyNum];
    for (int i = 0; i < groupingKeyNum; i++) {
        Expr groupingKey = aggregation.getGroupSet()[0].getGroupingSets()[i];
        normalizedResults[i] = normalizer.normalize(context, groupingKey);
    }

    String[] groupingKeyRefNames = new String[groupingKeyNum];
    for (int i = 0; i < groupingKeyNum; i++) {
        groupingKeyRefNames[i] = block.namedExprsMgr.addExpr(normalizedResults[i].baseExpr);
        block.namedExprsMgr.addNamedExprArray(normalizedResults[i].aggExprs);
        block.namedExprsMgr.addNamedExprArray(normalizedResults[i].scalarExprs);
    }

    ////////////////////////////////////////////////////////
    // Visit and Build Child Plan
    ////////////////////////////////////////////////////////
    stack.push(aggregation);
    LogicalNode child = visit(context, stack, aggregation.getChild());
    stack.pop();
    ////////////////////////////////////////////////////////
    GroupbyNode groupingNode = context.queryBlock.getNodeFromExpr(aggregation);
    groupingNode.setChild(child);
    groupingNode.setInSchema(child.getOutSchema());

    // Set grouping sets
    List<Column> groupingColumns = Lists.newArrayList();
    for (int i = 0; i < groupingKeyRefNames.length; i++) {
        String refName = groupingKeyRefNames[i];
        if (context.getQueryBlock().isConstReference(refName)) {
            continue;
        } else if (block.namedExprsMgr.isEvaluated(groupingKeyRefNames[i])) {
            groupingColumns.add(block.namedExprsMgr.getTarget(groupingKeyRefNames[i]).getNamedColumn());
        } else {
            throw new PlanningException("Each grouping column expression must be a scalar expression.");
        }
    }

    int effectiveGroupingKeyNum = groupingColumns.size();
    groupingNode.setGroupingColumns(groupingColumns.toArray(new Column[effectiveGroupingKeyNum]));

    ////////////////////////////////////////////////////////
    // Visit and Build Child Plan
    ////////////////////////////////////////////////////////

    // create EvalNodes and check if each EvalNode can be evaluated here.
    List<String> aggEvalNames = TUtil.newList();
    List<AggregationFunctionCallEval> aggEvalNodes = TUtil.newList();
    boolean includeDistinctFunction = false;
    for (Iterator<NamedExpr> iterator = block.namedExprsMgr.getIteratorForUnevaluatedExprs(); iterator
            .hasNext();) {
        NamedExpr namedExpr = iterator.next();
        try {
            includeDistinctFunction |= PlannerUtil.existsDistinctAggregationFunction(namedExpr.getExpr());
            EvalNode evalNode = exprAnnotator.createEvalNode(context, namedExpr.getExpr(),
                    NameResolvingMode.SUBEXPRS_AND_RELS);
            if (evalNode.getType() == EvalType.AGG_FUNCTION) {
                block.namedExprsMgr.markAsEvaluated(namedExpr.getAlias(), evalNode);
                aggEvalNames.add(namedExpr.getAlias());
                aggEvalNodes.add((AggregationFunctionCallEval) evalNode);
            }
        } catch (VerifyException ve) {
        }
    }
    // if there is at least one distinct aggregation function
    groupingNode.setDistinct(includeDistinctFunction);
    groupingNode.setAggFunctions(aggEvalNodes.toArray(new AggregationFunctionCallEval[aggEvalNodes.size()]));

    Target[] targets = new Target[effectiveGroupingKeyNum + aggEvalNames.size()];

    // In target, grouping columns will be followed by aggregation evals.
    //
    // col1, col2, col3,   sum(..),  agv(..)
    // ^^^^^^^^^^^^^^^    ^^^^^^^^^^^^^^^^^^
    //  grouping keys      aggregation evals

    // Build grouping keys
    for (int i = 0; i < effectiveGroupingKeyNum; i++) {
        Target target = block.namedExprsMgr.getTarget(groupingNode.getGroupingColumns()[i].getQualifiedName());
        targets[i] = target;
    }

    for (int i = 0, targetIdx = effectiveGroupingKeyNum; i < aggEvalNodes.size(); i++, targetIdx++) {
        targets[targetIdx] = block.namedExprsMgr.getTarget(aggEvalNames.get(i));
    }

    groupingNode.setTargets(targets);
    block.unsetAggregationRequire();

    verifyProjectedFields(block, groupingNode);
    return groupingNode;
}

From source file:com.concursive.connect.web.webdav.servlets.WebdavServlet.java

/**
 * PROPFIND Method.//w ww.  j av a  2  s.  com
 *
 * @param context Description of the Parameter
 * @throws javax.servlet.ServletException Description of the Exception
 * @throws java.io.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;
    }

    // Properties which are to be displayed.
    Vector properties = null;
    // Propfind depth
    int depth = INFINITY;
    // 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();
      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 object = null;
    ModuleContext resources = 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;
        }
        object = resources.lookup(db, path);
    } 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(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();
            if (!currentPath.equals(path)) {
                parseProperties(context, resources, generatedXML, currentPath, type, properties);
            }
            try {
                db = this.getConnection(context);
                object = resources.lookup(db, currentPath);
            } catch (NamingException e) {
                continue;
            } catch (SQLException e) {
                //e.printStackTrace(System.out);
                context.getResponse().sendError(SQLERROR, e.getMessage());
                status = false;
            } finally {
                this.freeConnection(db, context);
            }

            if (!status) {
                return;
            }

            if ((object instanceof ModuleContext) && depth > 0) {
                // Get a list of all the resources at the current path and store them
                // in the stack
                try {
                    NamingEnumeration enum1 = resources.list(currentPath);
                    int count = 0;
                    while (enum1.hasMoreElements()) {
                        NameClassPair ncPair = (NameClassPair) enum1.nextElement();
                        String newPath = currentPath;
                        if (!(newPath.endsWith("/"))) {
                            newPath += "/";
                        }
                        newPath += ncPair.getName();
                        stackBelow.push(newPath);
                        count++;
                    }
                    if (currentPath.equals(path) && count == 0) {
                        // This directory does not have any 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();
        }
    }

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

From source file:mml.handler.get.MMLGetMMLHandler.java

/**
 * Create the MMLtext using the invert index and the cortex and corcode
 * @param cortex the plain text version//from w ww.  ja  v  a  2s .c o  m
 * @param ccDflt the default STIL markup for that plain text
 * @param ccPages the page-breaks or null
 * @param layer the number of the layer to build
 */
void createMML(ScratchVersion cortex, ScratchVersion ccDflt, ScratchVersion ccPages, int layer) {
    String text = cortex.getLayerString(layer);
    mml = new StringBuilder();
    String stilDflt = ccDflt.getLayerString(layer);
    String stilPages = (ccPages == null) ? null : ccPages.getLayerString(layer);
    JSONObject mDflt = (JSONObject) JSONValue.parse(stilDflt);
    if (stilPages != null) {
        JSONObject mPages = (JSONObject) JSONValue.parse(stilPages);
        mDflt = mergeCorcodes(mDflt, mPages);
    }
    JSONArray ranges = (JSONArray) mDflt.get("ranges");
    Stack<EndTag> stack = new Stack<EndTag>();
    int offset = 0;
    for (int i = 0; i < ranges.size(); i++) {
        JSONObject r = (JSONObject) ranges.get(i);
        Number len = (Number) r.get("len");
        Number relOff = (Number) r.get("reloff");
        String name = (String) r.get("name");
        if (invertIndex.containsKey(name)) {
            JSONObject def = invertIndex.get(name);
            String startTag = mmlStartTag(def, offset);
            String endTag = mmlEndTag(def, len.intValue());
            int start = offset + relOff.intValue();
            // 1. insert pending end-tags and text before current range
            int pos = offset;
            while (!stack.isEmpty() && stack.peek().offset <= start) {
                // check for NLs here if obj is of type lineformat
                int tagEnd = stack.peek().offset;
                boolean isLF = isLineFormat(stack);
                for (int j = pos; j < tagEnd; j++) {
                    char c = text.charAt(j);
                    if (c != '\n') {
                        if (globals.containsKey(c))
                            mml.append(globals.get(c));
                        else
                            mml.append(c);
                    } else if (isLF && j < tagEnd - 1)
                        startPreLine(stack);
                    else
                        mml.append(c);
                }
                pos = tagEnd;
                // newlines are not permitted before tag end
                while (mml.length() > 0 && mml.charAt(mml.length() - 1) == '\n')
                    mml.setLength(mml.length() - 1);
                mml.append(stack.pop().text);
            }
            // 2. insert intervening text
            boolean inPre = isLineFormat(stack);
            int nNLs = countTerminalNLs(mml);
            for (int j = pos; j < start; j++) {
                char c = text.charAt(j);
                if (c == '\n') {
                    if (mml.length() == 0 || nNLs == 0)
                        mml.append(c);
                    if (nNLs > 0)
                        nNLs--;
                    if (inPre)
                        startPreLine(stack);
                } else {
                    mml.append(c);
                    nNLs = 0;
                }
            }
            // 3. insert new start tag
            normaliseNewlines(startTag);
            mml.append(startTag);
            stack.push(new EndTag(start + len.intValue(), endTag, def));
        } else
            System.out.println("Ignoring tag " + name);
        offset += relOff.intValue();
    }
    //empty stack
    int pos = offset;
    while (!stack.isEmpty()) {
        int tagEnd = stack.peek().offset;
        boolean inPre = isLineFormat(stack);
        for (int j = pos; j < tagEnd; j++) {
            char c = text.charAt(j);
            mml.append(c);
            if (c == '\n' && inPre && j < tagEnd - 1)
                startPreLine(stack);
        }
        pos = tagEnd;
        // newlines are not permitted before tag end
        while (mml.length() > 0 && mml.charAt(mml.length() - 1) == '\n')
            mml.setLength(mml.length() - 1);
        mml.append(stack.pop().text);
    }
}

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

void findContiguousPixels(ImageGrid sourceImage, WritableImageGrid mirror, Shape shape, int x, int y,
        int blackThreshold) {
    // let's imagine
    // 0 X 0 0 x x
    // x x x 0 0 x
    // 0 0 x x x x
    // so we have to go up and to the left to keep finding contiguous black pixels.
    Stack<int[]> pointStack = new Stack<int[]>();
    pointStack.push(new int[] { x, y });

    while (!pointStack.isEmpty()) {
        int[] point = pointStack.pop();
        x = point[0];/*from   w  w w  . j ava  2  s .  c  o m*/
        y = point[1];
        // Add this pixel to the mirror so that we don't touch it again.
        mirror.setPixel(x, y, 1);
        for (int rely = y - 1; rely <= y + 1; rely++) {
            for (int relx = x - 1; relx <= x + 1; relx++) {
                if (mirror.getPixel(relx, rely) > 0)
                    continue;
                if (sourceImage.isPixelBlack(relx, rely, blackThreshold)) {
                    if (relx < shape.getLeft())
                        shape.setLeft(relx);
                    if (relx > shape.getRight())
                        shape.setRight(relx);
                    if (rely > shape.getBottom())
                        shape.setBottom(rely);

                    // we don't have to check top, cause it's all going
                    // from top to bottom.
                    pointStack.push(new int[] { relx, rely });
                }
            }
        }
    }
}

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//w  ww.ja v a 2 s  . 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:hudson.model.Hudson.java

/**
 * Gets all the {@link Item}s recursively in the {@link ItemGroup} tree
 * and filter them by the given type.//from  ww w .jav a 2s  . com
 */
public <T extends Item> List<T> getAllItems(Class<T> type) {
    List<T> r = new ArrayList<T>();

    Stack<ItemGroup> q = new Stack<ItemGroup>();
    q.push(this);

    while (!q.isEmpty()) {
        ItemGroup<?> parent = q.pop();
        for (Item i : parent.getItems()) {
            if (type.isInstance(i)) {
                if (i.hasPermission(Item.READ))
                    r.add(type.cast(i));
            }
            if (i instanceof ItemGroup)
                q.push((ItemGroup) i);
        }
    }

    return r;
}