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:alluxio.master.file.DefaultFileSystemMaster.java

/**
 * Implements renaming./*from  ww  w  .j a va 2 s.  c o  m*/
 *
 * @param srcInodePath the path of the rename source
 * @param dstInodePath the path to the rename destination
 * @param replayed whether the operation is a result of replaying the journal
 * @param options method options
 * @throws FileDoesNotExistException if a non-existent file is encountered
 * @throws InvalidPathException if an invalid path is encountered
 * @throws IOException if an I/O error is encountered
 */
private void renameInternal(LockedInodePath srcInodePath, LockedInodePath dstInodePath, boolean replayed,
        RenameOptions options) throws FileDoesNotExistException, InvalidPathException, IOException {

    // Rename logic:
    // 1. Change the source inode name to the destination name.
    // 2. Insert the source inode into the destination parent.
    // 3. Do UFS operations if necessary.
    // 4. Remove the source inode (reverting the name) from the source parent.
    // 5. Set the last modification times for both source and destination parent inodes.

    Inode<?> srcInode = srcInodePath.getInode();
    AlluxioURI srcPath = srcInodePath.getUri();
    AlluxioURI dstPath = dstInodePath.getUri();
    InodeDirectory srcParentInode = srcInodePath.getParentInodeDirectory();
    InodeDirectory dstParentInode = dstInodePath.getParentInodeDirectory();
    String srcName = srcPath.getName();
    String dstName = dstPath.getName();

    LOG.debug("Renaming {} to {}", srcPath, dstPath);

    // 1. Change the source inode name to the destination name.
    srcInode.setName(dstName);
    srcInode.setParentId(dstParentInode.getId());

    // 2. Insert the source inode into the destination parent.
    if (!dstParentInode.addChild(srcInode)) {
        // On failure, revert changes and throw exception.
        srcInode.setName(srcName);
        srcInode.setParentId(srcParentInode.getId());
        throw new InvalidPathException("Destination path: " + dstPath + " already exists.");
    }

    // 3. Do UFS operations if necessary.
    // If the source file is persisted, rename it in the UFS.
    try {
        if (!replayed && srcInode.isPersisted()) {
            MountTable.Resolution resolution = mMountTable.resolve(srcPath);

            String ufsSrcPath = resolution.getUri().toString();
            UnderFileSystem ufs = resolution.getUfs();
            String ufsDstUri = mMountTable.resolve(dstPath).getUri().toString();
            // Create ancestor directories from top to the bottom. We cannot use recursive create
            // parents here because the permission for the ancestors can be different.
            List<Inode<?>> dstInodeList = dstInodePath.getInodeList();
            Stack<Pair<String, MkdirsOptions>> ufsDirsToMakeWithOptions = new Stack<>();
            AlluxioURI curUfsDirPath = new AlluxioURI(ufsDstUri).getParent();
            // The dst inode does not exist yet, so the last inode in the list is the existing parent.
            for (int i = dstInodeList.size() - 1; i >= 0; i--) {
                if (ufs.isDirectory(curUfsDirPath.toString())) {
                    break;
                }
                Inode<?> curInode = dstInodeList.get(i);
                MkdirsOptions mkdirsOptions = MkdirsOptions.defaults().setCreateParent(false)
                        .setOwner(curInode.getOwner()).setGroup(curInode.getGroup())
                        .setMode(new Mode(curInode.getMode()));
                ufsDirsToMakeWithOptions.push(new Pair<>(curUfsDirPath.toString(), mkdirsOptions));
                curUfsDirPath = curUfsDirPath.getParent();
            }
            while (!ufsDirsToMakeWithOptions.empty()) {
                Pair<String, MkdirsOptions> ufsDirAndPerm = ufsDirsToMakeWithOptions.pop();
                if (!ufs.mkdirs(ufsDirAndPerm.getFirst(), ufsDirAndPerm.getSecond())) {
                    throw new IOException(
                            ExceptionMessage.FAILED_UFS_CREATE.getMessage(ufsDirAndPerm.getFirst()));
                }
            }
            boolean success;
            if (srcInode.isFile()) {
                success = ufs.renameFile(ufsSrcPath, ufsDstUri);
            } else {
                success = ufs.renameDirectory(ufsSrcPath, ufsDstUri);
            }
            if (!success) {
                throw new IOException(ExceptionMessage.FAILED_UFS_RENAME.getMessage(ufsSrcPath, ufsDstUri));
            }
        }
    } catch (Exception e) {
        // On failure, revert changes and throw exception.
        if (!dstParentInode.removeChild(dstName)) {
            LOG.error("Failed to revert rename changes. Alluxio metadata may be inconsistent.");
        }
        srcInode.setName(srcName);
        srcInode.setParentId(srcParentInode.getId());
        throw e;
    }

    // TODO(jiri): A crash between now and the time the rename operation is journaled will result in
    // an inconsistency between Alluxio and UFS.

    // 4. Remove the source inode (reverting the name) from the source parent. The name must be
    // reverted or removeChild will not be able to find the appropriate child entry since it is
    // keyed on the original name.
    srcInode.setName(srcName);
    if (!srcParentInode.removeChild(srcInode)) {
        // This should never happen.
        LOG.error("Failed to rename {} to {} in Alluxio. Alluxio and under storage may be " + "inconsistent.",
                srcPath, dstPath);
        srcInode.setName(dstName);
        if (!dstParentInode.removeChild(dstName)) {
            LOG.error("Failed to revert changes when renaming {} to {}. Alluxio metadata may be "
                    + "inconsistent.", srcPath, dstPath);
        }
        srcInode.setName(srcName);
        srcInode.setParentId(srcParentInode.getId());
        throw new IOException("Failed to remove source path " + srcPath + " from parent");
    }
    srcInode.setName(dstName);

    // 5. Set the last modification times for both source and destination parent inodes.
    // Note this step relies on setLastModificationTimeMs being thread safe to guarantee the
    // correct behavior when multiple files are being renamed within a directory.
    dstParentInode.setLastModificationTimeMs(options.getOperationTimeMs());
    srcParentInode.setLastModificationTimeMs(options.getOperationTimeMs());
    Metrics.PATHS_RENAMED.inc();
}

From source file:com.espertech.esper.event.xml.XSDSchemaMapper.java

private static SchemaElementComplex process(String complexElementName, String complexElementNamespace,
        XSComplexTypeDefinition complexActualElement, boolean isArray,
        Stack<NamespaceNamePair> nameNamespaceStack, int maxRecursiveDepth) {
    if (log.isDebugEnabled()) {
        log.debug("Processing complex " + complexElementNamespace + " " + complexElementName + " stack "
                + nameNamespaceStack);// w w  w . jav a2 s. co m
    }

    List<SchemaItemAttribute> attributes = new ArrayList<SchemaItemAttribute>();
    List<SchemaElementSimple> simpleElements = new ArrayList<SchemaElementSimple>();
    List<SchemaElementComplex> complexElements = new ArrayList<SchemaElementComplex>();

    Short optionalSimplyType = null;
    String optionalSimplyTypeName = null;
    if (complexActualElement.getSimpleType() != null) {
        XSSimpleTypeDecl simpleType = (XSSimpleTypeDecl) complexActualElement.getSimpleType();
        optionalSimplyType = simpleType.getPrimitiveKind();
        optionalSimplyTypeName = simpleType.getName();
    }

    SchemaElementComplex complexElement = new SchemaElementComplex(complexElementName, complexElementNamespace,
            attributes, complexElements, simpleElements, isArray, optionalSimplyType, optionalSimplyTypeName);

    // add attributes
    XSObjectList attrs = complexActualElement.getAttributeUses();
    for (int i = 0; i < attrs.getLength(); i++) {
        XSAttributeUse attr = (XSAttributeUse) attrs.item(i);
        String namespace = attr.getAttrDeclaration().getNamespace();
        String name = attr.getAttrDeclaration().getName();
        XSSimpleTypeDecl simpleType = (XSSimpleTypeDecl) attr.getAttrDeclaration().getTypeDefinition();
        attributes.add(
                new SchemaItemAttribute(namespace, name, simpleType.getPrimitiveKind(), simpleType.getName()));
    }

    if ((complexActualElement.getContentType() == XSComplexTypeDefinition.CONTENTTYPE_ELEMENT)
            || (complexActualElement.getContentType() == XSComplexTypeDefinition.CONTENTTYPE_MIXED)) {
        // has children
        XSParticle particle = complexActualElement.getParticle();
        if (particle.getTerm() instanceof XSModelGroup) {
            XSModelGroup group = (XSModelGroup) particle.getTerm();
            XSObjectList particles = group.getParticles();
            for (int i = 0; i < particles.getLength(); i++) {
                XSParticle childParticle = (XSParticle) particles.item(i);

                if (childParticle.getTerm() instanceof XSElementDeclaration) {
                    XSElementDeclaration decl = (XSElementDeclaration) childParticle.getTerm();
                    boolean isArrayFlag = isArray(childParticle);

                    if (isSimpleTypeCategory(decl.getTypeDefinition().getTypeCategory())) {

                        XSSimpleTypeDecl simpleType = (XSSimpleTypeDecl) decl.getTypeDefinition();
                        Integer fractionDigits = getFractionRestriction(simpleType);
                        simpleElements.add(new SchemaElementSimple(decl.getName(), decl.getNamespace(),
                                simpleType.getPrimitiveKind(), simpleType.getName(), isArrayFlag,
                                fractionDigits));
                    }

                    if (isComplexTypeCategory(decl.getTypeDefinition().getTypeCategory())) {
                        String name = decl.getName();
                        String namespace = decl.getNamespace();
                        NamespaceNamePair nameNamespace = new NamespaceNamePair(namespace, name);
                        nameNamespaceStack.add(nameNamespace);

                        // if the stack contains
                        if (maxRecursiveDepth != Integer.MAX_VALUE) {
                            int containsCount = 0;
                            for (NamespaceNamePair pair : nameNamespaceStack) {
                                if (nameNamespace.equals(pair)) {
                                    containsCount++;
                                }
                            }

                            if (containsCount >= maxRecursiveDepth) {
                                continue;
                            }
                        }

                        complexActualElement = (XSComplexTypeDefinition) decl.getTypeDefinition();
                        SchemaElementComplex innerComplex = process(name, namespace, complexActualElement,
                                isArrayFlag, nameNamespaceStack, maxRecursiveDepth);

                        nameNamespaceStack.pop();

                        if (log.isDebugEnabled()) {
                            log.debug("Adding complex " + complexElement);
                        }
                        complexElements.add(innerComplex);
                    }
                }
            }
        }
    }

    return complexElement;
}

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

@Override
public LogicalNode visitCreateTable(PlanContext context, Stack<Expr> stack, CreateTable expr)
        throws PlanningException {

    CreateTableNode createTableNode = context.queryBlock.getNodeFromExpr(expr);
    createTableNode.setIfNotExists(expr.isIfNotExists());

    // Set a table name to be created.
    if (CatalogUtil.isFQTableName(expr.getTableName())) {
        createTableNode.setTableName(expr.getTableName());
    } else {//  ww w.j a v  a 2 s  . co  m
        createTableNode.setTableName(
                CatalogUtil.buildFQName(context.queryContext.getCurrentDatabase(), expr.getTableName()));
    }
    // This is CREATE TABLE <tablename> LIKE <parentTable>
    if (expr.getLikeParentTableName() != null)
        return handleCreateTableLike(context, expr, createTableNode);

    if (expr.hasStorageType()) { // If storage type (using clause) is specified
        createTableNode.setStorageType(CatalogUtil.getStoreType(expr.getStorageType()));
    } else { // otherwise, default type
        createTableNode.setStorageType(CatalogProtos.StoreType.CSV);
    }

    // Set default storage properties to be created.
    KeyValueSet keyValueSet = StorageUtil.newPhysicalProperties(createTableNode.getStorageType());
    if (expr.hasParams()) {
        keyValueSet.putAll(expr.getParams());
    }

    createTableNode.setOptions(keyValueSet);

    if (expr.hasPartition()) {
        if (expr.getPartitionMethod().getPartitionType().equals(PartitionType.COLUMN)) {
            createTableNode.setPartitionMethod(
                    getPartitionMethod(context, expr.getTableName(), expr.getPartitionMethod()));
        } else {
            throw new PlanningException(String.format("Not supported PartitonType: %s",
                    expr.getPartitionMethod().getPartitionType()));
        }
    }

    if (expr.hasSubQuery()) { // CREATE TABLE .. AS SELECT
        stack.add(expr);
        LogicalNode subQuery = visit(context, stack, expr.getSubQuery());
        stack.pop();
        createTableNode.setChild(subQuery);
        createTableNode.setInSchema(subQuery.getOutSchema());

        // If the table schema is defined
        // ex) CREATE TABLE tbl(col1 type, col2 type) AS SELECT ...
        if (expr.hasTableElements()) {
            createTableNode.setOutSchema(convertTableElementsSchema(expr.getTableElements()));
            createTableNode.setTableSchema(convertTableElementsSchema(expr.getTableElements()));
        } else {
            // if no table definition, the select clause's output schema will be used.
            // ex) CREATE TABLE tbl AS SELECT ...

            if (expr.hasPartition()) {
                PartitionMethodDesc partitionMethod = createTableNode.getPartitionMethod();

                Schema queryOutputSchema = subQuery.getOutSchema();
                Schema partitionExpressionSchema = partitionMethod.getExpressionSchema();
                if (partitionMethod.getPartitionType() == CatalogProtos.PartitionType.COLUMN
                        && queryOutputSchema.size() < partitionExpressionSchema.size()) {
                    throw new VerifyException("Partition columns cannot be more than table columns.");
                }
                Schema tableSchema = new Schema();
                for (int i = 0; i < queryOutputSchema.size() - partitionExpressionSchema.size(); i++) {
                    tableSchema.addColumn(queryOutputSchema.getColumn(i));
                }
                createTableNode.setOutSchema(tableSchema);
                createTableNode.setTableSchema(tableSchema);
            } else {
                // Convert the schema of subquery into the target table's one.
                Schema schema = new Schema(subQuery.getOutSchema());
                schema.setQualifier(createTableNode.getTableName());
                createTableNode.setOutSchema(schema);
                createTableNode.setTableSchema(schema);
            }
        }

        return createTableNode;

    } else { // if CREATE AN EMPTY TABLE
        Schema tableSchema = convertColumnsToSchema(expr.getTableElements());
        createTableNode.setTableSchema(tableSchema);

        if (expr.isExternal()) {
            createTableNode.setExternal(true);
        }

        if (expr.hasLocation()) {
            createTableNode.setPath(new Path(expr.getLocation()));
        }

        return createTableNode;
    }
}

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

/**
 * Get keys of entities having certain property name assigned. 
 *  @param propertyName$ property name.//from w w w  .ja v a  2s.co m
 * @return array of entities keys.
 */
public String[] indx_listEntitiesAtPropertyName(String propertyName$) {
    if ("label".equals(propertyName$)) {
        return quickMap.elementListNoSorted("label");
    }
    try {
        String property$ = propertyIndex.getElementItemAt("property", propertyName$);

        if (property$ == null) {
            LOGGER.severe(":indx_listEntitiesAtPropertyName:cannot find property in property index  property ="
                    + propertyName$);
            return null;
        }
        Sack property = getMember("property.base", property$);
        if (property == null) {
            LOGGER.severe(":indx_listEntitiesAtPropertyName:cannot find property =" + property$);
            return null;
        }
        Stack<String> s = new Stack<String>();
        Stack<String> s2 = new Stack<String>();
        if ("label".equals(propertyName$)) {
            Core[] ca = property.elementGet("value");
            if (ca != null)
                for (Core aCa : ca)
                    if (aCa.value != null)
                        s.push(aCa.value);
        } else {
            String[] ma = property.elementList("value");
            if (ma == null) {
                LOGGER.severe(":indx_listEntitiesAtPropertyName:no values in property =" + property$);
                return null;
            }

            Sack map;
            String[] ea;
            for (int i = 0; i < ma.length; i++) {
                s2.clear();
                map = getMember("property.map.base", property.getElementItemAt("value", ma[i]));
                if (map == null) {
                    LOGGER.severe(":indx_listEntitiesAtPropertyName:cannot get map[" + i + "]=" + ma[i]);
                    continue;
                }
                ea = map.elementList("entity");
                if (ea == null) {
                    LOGGER.severe(":indx_listEntitiesAtPropertyName:empty map[" + i + "]=" + ma[i]);
                    continue;
                }
                for (String anEa : ea) {
                    if (!touchEntity(anEa))
                        s.push(anEa);
                }
            }
        }
        int cnt = s.size();
        if (cnt < 1) {
            LOGGER.severe(":indx_listEntitiesAtPropertyName:no entities found");
            return null;
        }
        String[] sa = new String[cnt];
        for (int i = 0; i < cnt; i++)
            sa[i] = s.pop();
        return sa;
    } catch (Exception e) {
        LOGGER.severe(":indx_listEntitiesAtPropertyName:" + e.toString());
        return null;
    }
}

From source file:org.apache.solr.handler.JsonLoader.java

SolrInputDocument parseDoc(int ev) throws IOException {
    Stack<Object> stack = new Stack<Object>();
    Object obj = null;//from   w w  w . ja v a 2s.  c  o m
    boolean inArray = false;

    if (ev != JSONParser.OBJECT_START) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "object should already be started");
    }

    while (true) {
        //System.out.println( ev + "["+JSONParser.getEventString(ev)+"] "+parser.wasKey() ); //+ parser.getString() );

        switch (ev) {
        case JSONParser.STRING:
            if (parser.wasKey()) {
                obj = stack.peek();
                String v = parser.getString();
                if (obj instanceof SolrInputField) {
                    SolrInputField field = (SolrInputField) obj;
                    if ("boost".equals(v)) {
                        ev = parser.nextEvent();
                        if (ev != JSONParser.NUMBER && ev != JSONParser.LONG && ev != JSONParser.BIGNUMBER) {
                            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                                    "boost should have number! " + JSONParser.getEventString(ev));
                        }
                        field.setBoost((float) parser.getDouble());
                    } else if ("value".equals(v)) {
                        // nothing special...
                        stack.push(field); // so it can be popped
                    } else {
                        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                                "invalid key: " + v + " [" + parser.getPosition() + "]");
                    }
                } else if (obj instanceof SolrInputDocument) {
                    SolrInputDocument doc = (SolrInputDocument) obj;
                    SolrInputField f = doc.get(v);
                    if (f == null) {
                        f = new SolrInputField(v);
                        doc.put(f.getName(), f);
                    }
                    stack.push(f);
                } else {
                    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                            "hymmm [" + parser.getPosition() + "]");
                }
            } else {
                addValToField(stack, parser.getString(), inArray, parser);
            }
            break;

        case JSONParser.LONG:
        case JSONParser.NUMBER:
        case JSONParser.BIGNUMBER:
            addValToField(stack, parser.getNumberChars().toString(), inArray, parser);
            break;

        case JSONParser.BOOLEAN:
            addValToField(stack, parser.getBoolean(), inArray, parser);
            break;

        case JSONParser.NULL:
            parser.getNull();
            /*** if we wanted to remove the field from the document now...
            if (!inArray) {
              Object o = stack.peek();
              // if null was only value in the field, then remove the field
              if (o instanceof SolrInputField) {
                SolrInputField sif = (SolrInputField)o;
                if (sif.getValueCount() == 0) {
                  sdoc.remove(sif.getName());
                }
              }
            }
            ***/

            addValToField(stack, null, inArray, parser);
            break;

        case JSONParser.OBJECT_START:
            if (stack.isEmpty()) {
                stack.push(new SolrInputDocument());
            } else {
                obj = stack.peek();
                if (obj instanceof SolrInputField) {
                    // should alreay be pushed...
                } else {
                    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                            "should not start new object with: " + obj + " [" + parser.getPosition() + "]");
                }
            }
            break;
        case JSONParser.OBJECT_END:
            obj = stack.pop();
            if (obj instanceof SolrInputDocument) {
                return (SolrInputDocument) obj;
            } else if (obj instanceof SolrInputField) {
                // should already be pushed...
            } else {
                throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                        "should not start new object with: " + obj + " [" + parser.getPosition() + "]");
            }
            break;

        case JSONParser.ARRAY_START:
            inArray = true;
            break;

        case JSONParser.ARRAY_END:
            inArray = false;
            stack.pop(); // the val should have done it...
            break;

        default:
            System.out.println("UNKNOWN_EVENT_ID:" + ev);
            break;
        }

        ev = parser.nextEvent();
        if (ev == JSONParser.EOF) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "should finish doc first!");
        }
    }
}

From source file:org.sakaiproject.lessonbuildertool.service.LessonBuilderEntityProducer.java

/**
 * {@inheritDoc}//from www.  j av  a2 s  .c o m
 */
public String archive(String siteId, Document doc, Stack stack, String archivePath, List attachments) {
    //prepare the buffer for the results log
    StringBuilder results = new StringBuilder();

    try {
        Site site = siteService.getSite(siteId);
        // start with an element with our very own (service) name         
        Element element = doc.createElement(serviceName());
        element.setAttribute(VERSION_ATTR, ARCHIVE_VERSION);
        ((Element) stack.peek()).appendChild(element);
        stack.push(element);

        Element lessonbuilder = doc.createElement(LESSONBUILDER);

        List<SimplePage> sitePages = simplePageToolDao.getSitePages(siteId);
        if (sitePages != null && !sitePages.isEmpty()) {
            for (SimplePage page : sitePages)
                addPage(doc, lessonbuilder, page, site);
        }

        Collection<ToolConfiguration> tools = site.getTools(myToolIds());
        int count = 0;
        if (tools != null && !tools.isEmpty()) {
            for (ToolConfiguration config : tools) {
                element = doc.createElement(LESSONBUILDER);

                addAttr(doc, element, "toolid", config.getPageId());
                addAttr(doc, element, "name", config.getContainingPage().getTitle());

                Properties props = config.getPlacementConfig();

                String roleList = props.getProperty("functions.require");
                if (roleList == null)
                    roleList = "";

                addAttr(doc, element, "functions.require", roleList);

                // should be impossible for these nulls, but we've seen it
                if (simplePageToolDao.getTopLevelPageId(config.getPageId()) != null)
                    addAttr(doc, element, "pageId",
                            Long.toString(simplePageToolDao.getTopLevelPageId(config.getPageId())));
                else
                    logger.warn("archive site " + siteId + " tool page " + config.getPageId() + " null lesson");
                // addPage(doc, element,  simplePageToolDao.getTopLevelPageId(config.getPageId()));

                lessonbuilder.appendChild(element);
                count++;
            }

            results.append("archiving " + count + " LessonBuilder instances.\n");

        } else {
            results.append("archiving no LessonBuilder instances.\n");
        }

        ((Element) stack.peek()).appendChild(lessonbuilder);
        stack.push(lessonbuilder);

        stack.pop();
    } catch (Exception any) {
        any.printStackTrace();
        logger.warn("archive: exception archiving service: " + any + " " + serviceName());
    }

    stack.pop();

    return results.toString();
}

From source file:HtmlEncoder.java

/**
 *  Do "smart" encodging on a string. This means that valid HTML entities and tags,
 *  Helma macros and HTML comments are passed through unescaped, while
 *  other occurrences of '<', '>' and '&' are encoded to HTML entities.
 *
 *  @param str the string to encode/*w  w w.j  av  a2  s. co m*/
 *  @param ret the string buffer to encode to
 *  @param paragraphs if true use p tags for paragraphs, otherwise just use br's
 *  @param allowedTags a set containing the names of allowed tags as strings. All other
 *                     tags will be escaped
 */
public final static void encode(String str, StringBuffer ret, boolean paragraphs, Set allowedTags) {
    if (str == null) {
        return;
    }

    int l = str.length();

    // where to insert the <p> tag in case we want to create a paragraph later on
    int paragraphStart = ret.length();

    // what kind of element/text are we leaving and entering?
    // this is one of TEXT|SEMIBLOCK|BLOCK|INTERNAL
    // depending on this information, we decide whether and how to insert
    // paragraphs and line breaks. "entering" a tag means we're at the '<'
    // and exiting means we're at the '>', not that it's a start or close tag.
    byte entering = TEXT;
    byte exiting = TEXT;

    Stack openTags = new Stack();

    // are we currently within a < and a > that consitute some kind of tag?
    // we use tag balancing to know whether we are inside a tag (and should
    // pass things through unchanged) or outside (and should encode stuff).
    boolean insideTag = false;

    // are we inside an HTML tag?
    boolean insideHtmlTag = false;
    boolean insideCloseTag = false;
    byte htmlTagMode = TAG_NAME;

    // if we are inside a <code> tag, we encode everything to make
    // documentation work easier
    boolean insideCodeTag = false;
    boolean insidePreTag = false;

    // are we within a Helma <% macro %> tag? We treat macro tags and
    // comments specially, since we can't rely on tag balancing
    // to know when we leave a macro tag or comment.
    boolean insideMacroTag = false;

    // are we inside an HTML comment?
    boolean insideComment = false;

    // the quotation mark we are in within an HTML or Macro tag, if any
    char htmlQuoteChar = '\u0000';
    char macroQuoteChar = '\u0000';

    // number of newlines met since the last non-whitespace character
    int linebreaks = 0;

    // did we meet a backslash escape?
    boolean escape = false;

    boolean triggerBreak = false;

    for (int i = 0; i < l; i++) {
        char c = str.charAt(i);

        // step one: check if this is the beginning of an HTML tag, comment or
        // Helma macro.
        if (c == '<') {
            if (i < (l - 2)) {
                if (!insideMacroTag && ('%' == str.charAt(i + 1))) {
                    // this is the beginning of a Helma macro tag
                    if (!insideCodeTag) {
                        insideMacroTag = insideTag = true;
                        macroQuoteChar = '\u0000';
                    }
                } else if (('!' == str.charAt(i + 1)) && ('-' == str.charAt(i + 2))) {
                    // the beginning of an HTML comment?
                    if (!insideCodeTag) {
                        insideComment = insideTag = ((i < (l - 3)) && ('-' == str.charAt(i + 3)));
                    }
                } else if (!insideTag) {
                    // check if this is a HTML tag.
                    insideCloseTag = ('/' == str.charAt(i + 1));
                    int tagStart = insideCloseTag ? (i + 2) : (i + 1);
                    int j = tagStart;

                    while ((j < l) && Character.isLetterOrDigit(str.charAt(j)))
                        j++;

                    if ((j > tagStart) && (j < l)) {
                        String tagName = str.substring(tagStart, j).toLowerCase();

                        if ("code".equals(tagName) && insideCloseTag && insideCodeTag) {
                            insideCodeTag = false;
                        }

                        if (((allowedTags == null) || allowedTags.contains(tagName))
                                && allTags.contains(tagName) && !insideCodeTag) {
                            insideHtmlTag = insideTag = true;
                            htmlQuoteChar = '\u0000';
                            htmlTagMode = TAG_NAME;

                            exiting = entering;
                            entering = TEXT;

                            if (internalTags.contains(tagName)) {
                                entering = INTERNAL;
                            } else if (blockTags.contains(tagName)) {
                                entering = BLOCK;
                            } else if (semiBlockTags.contains(tagName)) {
                                entering = paragraphs ? BLOCK : SEMIBLOCK;
                            }

                            if (entering > 0) {
                                triggerBreak = !insidePreTag;
                            }

                            if (insideCloseTag) {
                                int t = openTags.search(tagName);

                                if (t == -1) {
                                    i = j;
                                    insideHtmlTag = insideTag = false;

                                    continue;
                                } else if (t > 1) {
                                    for (int k = 1; k < t; k++) {
                                        Object tag = openTags.pop();
                                        if (!emptyTags.contains(tag)) {
                                            ret.append("</");
                                            ret.append(tag);
                                            ret.append(">");
                                        }
                                    }
                                }

                                openTags.pop();
                            } else {
                                openTags.push(tagName);
                            }

                            if ("code".equals(tagName) && !insideCloseTag) {
                                insideCodeTag = true;
                            }

                            if ("pre".equals(tagName)) {
                                insidePreTag = !insideCloseTag;
                            }
                        }
                    }
                }
            } // if (i < l-2)
        }

        if ((triggerBreak || linebreaks > 0) && !Character.isWhitespace(c)) {

            if (!insideTag) {
                exiting = entering;
                entering = TEXT;
                if (exiting >= SEMIBLOCK) {
                    paragraphStart = ret.length();
                }
            }

            if (entering != INTERNAL && exiting != INTERNAL) {
                int swallowBreaks = 0;
                if (paragraphs && (entering != BLOCK || exiting != BLOCK) && (exiting < BLOCK)
                        && (linebreaks > 1) && paragraphStart < ret.length()) {
                    ret.insert(paragraphStart, "<p>");
                    ret.append("</p>");
                    swallowBreaks = 2;
                }

                // treat entering a SEMIBLOCK as entering a TEXT 
                int _entering = entering == SEMIBLOCK ? TEXT : entering;
                for (int k = linebreaks - 1; k >= 0; k--) {
                    if (k >= swallowBreaks && k >= _entering && k >= exiting) {
                        ret.append("<br />");
                    }
                    ret.append(newLine);
                }
                if (exiting >= SEMIBLOCK || linebreaks > 1) {
                    paragraphStart = ret.length();
                }

            }

            linebreaks = 0;
            triggerBreak = false;
        }

        switch (c) {
        case '<':

            if (insideTag) {
                ret.append('<');
            } else {
                ret.append("&lt;");
            }

            break;

        case '&':

            // check if this is an HTML entity already,
            // in which case we pass it though unchanged
            if ((i < (l - 3)) && !insideCodeTag) {
                // is this a numeric entity?
                if (str.charAt(i + 1) == '#') {
                    int j = i + 2;

                    while ((j < l) && Character.isDigit(str.charAt(j)))
                        j++;

                    if ((j < l) && (str.charAt(j) == ';')) {
                        ret.append("&");

                        break;
                    }
                } else {
                    int j = i + 1;

                    while ((j < l) && Character.isLetterOrDigit(str.charAt(j)))
                        j++;

                    if ((j < l) && (str.charAt(j) == ';')) {
                        ret.append("&");

                        break;
                    }
                }
            }

            // we didn't reach a break, so encode the ampersand as HTML entity
            ret.append("&amp;");

            break;

        case '\\':
            ret.append(c);

            if (insideTag && !insideComment) {
                escape = !escape;
            }

            break;

        case '"':
        case '\'':
            ret.append(c);

            if (!insideComment) {
                // check if the quote is escaped
                if (insideMacroTag) {
                    if (escape) {
                        escape = false;
                    } else if (macroQuoteChar == c) {
                        macroQuoteChar = '\u0000';
                    } else if (macroQuoteChar == '\u0000') {
                        macroQuoteChar = c;
                    }
                } else if (insideHtmlTag) {
                    if (escape) {
                        escape = false;
                    } else if (htmlQuoteChar == c) {
                        htmlQuoteChar = '\u0000';
                        htmlTagMode = TAG_SPACE;
                    } else if (htmlQuoteChar == '\u0000') {
                        htmlQuoteChar = c;
                    }
                }
            }

            break;

        case '\n':
            if (insideTag || insidePreTag) {
                ret.append('\n');
            } else {
                linebreaks++;
            }

            break;
        case '\r':
            if (insideTag || insidePreTag) {
                ret.append('\r');
            }
            break;

        case '>':

            // For Helma macro tags and comments, we overrule tag balancing,
            // i.e. we don't require that '<' and '>' be balanced within
            // macros and comments. Rather, we check for the matching closing tag.
            if (insideComment) {
                ret.append('>');
                insideComment = !((str.charAt(i - 2) == '-') && (str.charAt(i - 1) == '-'));
            } else if (insideMacroTag) {
                ret.append('>');
                insideMacroTag = !((str.charAt(i - 1) == '%') && (macroQuoteChar == '\u0000'));
            } else if (insideHtmlTag) {
                ret.append('>');

                // only leave HTML tag if quotation marks are balanced
                // within that tag.
                insideHtmlTag = htmlQuoteChar != '\u0000';

                // Check if this is an empty tag so we don't generate an
                // additional </close> tag.
                if (str.charAt(i - 1) == '/') {
                    // this is to avoid misinterpreting tags like
                    // <a href=http://foo/> as empty
                    if (htmlTagMode != TAG_ATT_VAL && htmlTagMode != TAG_ATT_NAME) {
                        openTags.pop();
                    }
                }

                exiting = entering;
                if (exiting > 0) {
                    triggerBreak = !insidePreTag;
                }

            } else {
                ret.append("&gt;");
            }

            // check if we still are inside any kind of tag
            insideTag = insideComment || insideMacroTag || insideHtmlTag;
            insideCloseTag = insideTag;

            break;

        default:

            if (insideHtmlTag && !insideCloseTag) {
                switch (htmlTagMode) {
                case TAG_NAME:
                    if (!Character.isLetterOrDigit(c)) {
                        htmlTagMode = TAG_SPACE;
                    }
                    break;
                case TAG_SPACE:
                    if (Character.isLetterOrDigit(c)) {
                        htmlTagMode = TAG_ATT_NAME;
                    }
                    break;
                case TAG_ATT_NAME:
                    if (c == '=') {
                        htmlTagMode = TAG_ATT_VAL;
                    } else if (c == ' ') {
                        htmlTagMode = TAG_SPACE;
                    }
                    break;
                case TAG_ATT_VAL:
                    if (Character.isWhitespace(c) && htmlQuoteChar == '\u0000') {
                        htmlTagMode = TAG_SPACE;
                    }
                    break;
                }
            }
            if (c < 128) {
                ret.append(c);
            } else if ((c >= 128) && (c < 256)) {
                ret.append(transform[c - 128]);
            } else {
                ret.append("&#");
                ret.append((int) c);
                ret.append(";");
            }

            escape = false;
        }
    }

    // if tags were opened but not closed, close them.
    int o = openTags.size();

    if (o > 0) {
        for (int k = 0; k < o; k++) {
            Object tag = openTags.pop();
            if (!emptyTags.contains(tag)) {
                ret.append("</");
                ret.append(tag);
                ret.append(">");
            }
        }
    }

    // add remaining newlines we may have collected
    int swallowBreaks = 0;
    if (paragraphs && entering < BLOCK) {
        ret.insert(paragraphStart, "<p>");
        ret.append("</p>");
        swallowBreaks = 2;
    }

    if (linebreaks > 0) {
        for (int i = linebreaks - 1; i >= 0; i--) {
            if (i >= swallowBreaks && i > exiting) {
                ret.append("<br />");
            }
            ret.append(newLine);
        }
    }
}

From source file:edu.uci.ics.jung.algorithms.scoring.BetweennessCentrality.java

protected void computeBetweenness(Queue<V> queue, Transformer<E, ? extends Number> edge_weights) {
    for (V v : graph.getVertices()) {
        // initialize the betweenness data for this new vertex
        for (V s : graph.getVertices())
            this.vertex_data.put(s, new BetweennessData());

        //         if (v.equals(new Integer(0)))
        //            System.out.println("pause");

        vertex_data.get(v).numSPs = 1;/*from  w  w  w  . j  a va 2 s.  c o m*/
        vertex_data.get(v).distance = 0;

        Stack<V> stack = new Stack<V>();
        //            Buffer<V> queue = new UnboundedFifoBuffer<V>();
        //            queue.add(v);
        queue.offer(v);

        while (!queue.isEmpty()) {
            //                V w = queue.remove();
            V w = queue.poll();
            stack.push(w);
            BetweennessData w_data = vertex_data.get(w);

            for (E e : graph.getOutEdges(w)) {
                // TODO (jrtom): change this to getOtherVertices(w, e)
                V x = graph.getOpposite(w, e);
                if (x.equals(w))
                    continue;
                double wx_weight = edge_weights.transform(e).doubleValue();

                //                for(V x : graph.getSuccessors(w)) 
                //                {
                //                   if (x.equals(w))
                //                      continue;

                // FIXME: the other problem is that I need to 
                // keep putting the neighbors of things we've just 
                // discovered in the queue, if they're undiscovered or
                // at greater distance.

                // FIXME: this is the problem, right here, I think: 
                // need to update position in queue if distance changes
                // (which can only happen with weighted edges).
                // for each outgoing edge e from w, get other end x
                // if x not already visited (dist x < 0)
                //   set x's distance to w's dist + edge weight
                //   add x to queue; pri in queue is x's dist
                // if w's dist + edge weight < x's dist 
                //   update x's dist
                //   update x in queue (MapBinaryHeap)
                //   clear x's incoming edge list
                // if w's dist + edge weight = x's dist
                //   add e to x's incoming edge list

                BetweennessData x_data = vertex_data.get(x);
                double x_potential_dist = w_data.distance + wx_weight;

                if (x_data.distance < 0) {
                    //                        queue.add(x);
                    //                        vertex_data.get(x).distance = vertex_data.get(w).distance + 1;
                    x_data.distance = x_potential_dist;
                    queue.offer(x);
                }

                // note:
                // (1) this can only happen with weighted edges
                // (2) x's SP count and incoming edges are updated below 
                if (x_data.distance > x_potential_dist) {
                    x_data.distance = x_potential_dist;
                    // invalidate previously identified incoming edges
                    // (we have a new shortest path distance to x)
                    x_data.incomingEdges.clear();
                    // update x's position in queue
                    ((MapBinaryHeap<V>) queue).update(x);
                }
                //                  if (vertex_data.get(x).distance == vertex_data.get(w).distance + 1) 
                // 
                //                    if (x_data.distance == x_potential_dist) 
                //                    {
                //                        x_data.numSPs += w_data.numSPs;
                ////                        vertex_data.get(x).predecessors.add(w);
                //                        x_data.incomingEdges.add(e);
                //                    }
            }
            for (E e : graph.getOutEdges(w)) {
                V x = graph.getOpposite(w, e);
                if (x.equals(w))
                    continue;
                double e_weight = edge_weights.transform(e).doubleValue();
                BetweennessData x_data = vertex_data.get(x);
                double x_potential_dist = w_data.distance + e_weight;
                if (x_data.distance == x_potential_dist) {
                    x_data.numSPs += w_data.numSPs;
                    //                        vertex_data.get(x).predecessors.add(w);
                    x_data.incomingEdges.add(e);
                }
            }
        }
        while (!stack.isEmpty()) {
            V x = stack.pop();

            //              for (V w : vertex_data.get(x).predecessors) 
            for (E e : vertex_data.get(x).incomingEdges) {
                V w = graph.getOpposite(x, e);
                double partialDependency = vertex_data.get(w).numSPs / vertex_data.get(x).numSPs
                        * (1.0 + vertex_data.get(x).dependency);
                vertex_data.get(w).dependency += partialDependency;
                //                  E w_x = graph.findEdge(w, x);
                //                  double w_x_score = edge_scores.get(w_x).doubleValue();
                //                  w_x_score += partialDependency;
                //                  edge_scores.put(w_x, w_x_score);
                double e_score = edge_scores.get(e).doubleValue();
                edge_scores.put(e, e_score + partialDependency);
            }
            if (!x.equals(v)) {
                double x_score = vertex_scores.get(x).doubleValue();
                x_score += vertex_data.get(x).dependency;
                vertex_scores.put(x, x_score);
            }
        }
    }

    if (graph instanceof UndirectedGraph) {
        for (V v : graph.getVertices()) {
            double v_score = vertex_scores.get(v).doubleValue();
            v_score /= 2.0;
            vertex_scores.put(v, v_score);
        }
        for (E e : graph.getEdges()) {
            double e_score = edge_scores.get(e).doubleValue();
            e_score /= 2.0;
            edge_scores.put(e, e_score);
        }
    }

    vertex_data.clear();
}

From source file:net.sf.eventgraphj.centrality.EgoNetworkBetweennessCentrality.java

protected void computeBetweenness(Queue<V> queue, Transformer<E, ? extends Number> edge_weights) {
    for (V v : graph.getVertices()) {
        // initialize the betweenness data for this new vertex
        for (V s : graph.getVertices())
            this.vertex_data.put(s, new BetweennessData());

        //         if (v.equals(new Integer(0)))
        //            System.out.println("pause");

        vertex_data.get(v).numSPs = 1;//  w  ww  .jav  a 2  s .c o  m
        vertex_data.get(v).distance = 0;

        Stack<V> stack = new Stack<V>();
        //            Buffer<V> queue = new UnboundedFifoBuffer<V>();
        //            queue.add(v);
        queue.offer(v);

        while (!queue.isEmpty()) {
            //                V w = queue.remove();
            V w = queue.poll();
            stack.push(w);
            BetweennessData w_data = vertex_data.get(w);
            for (E e : graph.getOutEdges(w)) {
                // TODO (jrtom): change this to getOtherVertices(w, e)
                V x = graph.getOpposite(w, e);
                if (x.equals(w))
                    continue;
                double wx_weight = edge_weights.transform(e).doubleValue();

                //                for(V x : graph.getSuccessors(w)) 
                //                {
                //                   if (x.equals(w))
                //                      continue;

                // FIXME: the other problem is that I need to 
                // keep putting the neighbors of things we've just 
                // discovered in the queue, if they're undiscovered or
                // at greater distance.

                // FIXME: this is the problem, right here, I think: 
                // need to update position in queue if distance changes
                // (which can only happen with weighted edges).
                // for each outgoing edge e from w, get other end x
                // if x not already visited (dist x < 0)
                //   set x's distance to w's dist + edge weight
                //   add x to queue; pri in queue is x's dist
                // if w's dist + edge weight < x's dist 
                //   update x's dist
                //   update x in queue (MapBinaryHeap)
                //   clear x's incoming edge list
                // if w's dist + edge weight = x's dist
                //   add e to x's incoming edge list

                BetweennessData x_data = vertex_data.get(x);
                double x_potential_dist = w_data.distance + wx_weight;
                if (x_potential_dist > this.egoNetworkSize)
                    continue;

                if (x_data.distance < 0) {
                    //                        queue.add(x);
                    //                        vertex_data.get(x).distance = vertex_data.get(w).distance + 1;
                    x_data.distance = x_potential_dist;
                    queue.offer(x);
                }

                // note:
                // (1) this can only happen with weighted edges
                // (2) x's SP count and incoming edges are updated below 
                if (x_data.distance > x_potential_dist) {
                    x_data.distance = x_potential_dist;
                    // invalidate previously identified incoming edges
                    // (we have a new shortest path distance to x)
                    x_data.incomingEdges.clear();
                    // update x's position in queue
                    ((MapBinaryHeap<V>) queue).update(x);
                }
                //                  if (vertex_data.get(x).distance == vertex_data.get(w).distance + 1) 
                // 
                //                    if (x_data.distance == x_potential_dist) 
                //                    {
                //                        x_data.numSPs += w_data.numSPs;
                ////                        vertex_data.get(x).predecessors.add(w);
                //                        x_data.incomingEdges.add(e);
                //                    }
            }
            for (E e : graph.getOutEdges(w)) {
                V x = graph.getOpposite(w, e);
                if (x.equals(w))
                    continue;
                double e_weight = edge_weights.transform(e).doubleValue();
                BetweennessData x_data = vertex_data.get(x);
                double x_potential_dist = w_data.distance + e_weight;
                if (x_data.distance == x_potential_dist) {
                    x_data.numSPs += w_data.numSPs;
                    //                        vertex_data.get(x).predecessors.add(w);
                    x_data.incomingEdges.add(e);
                }
            }
        }
        while (!stack.isEmpty()) {
            V x = stack.pop();

            //              for (V w : vertex_data.get(x).predecessors) 
            for (E e : vertex_data.get(x).incomingEdges) {
                V w = graph.getOpposite(x, e);
                double partialDependency = vertex_data.get(w).numSPs / vertex_data.get(x).numSPs
                        * (1.0 + vertex_data.get(x).dependency);
                vertex_data.get(w).dependency += partialDependency;
                //                  E w_x = graph.findEdge(w, x);
                //                  double w_x_score = edge_scores.get(w_x).doubleValue();
                //                  w_x_score += partialDependency;
                //                  edge_scores.put(w_x, w_x_score);
                double e_score = edge_scores.get(e).doubleValue();
                edge_scores.put(e, e_score + partialDependency);
            }
            if (!x.equals(v)) {
                double x_score = vertex_scores.get(x).doubleValue();
                x_score += vertex_data.get(x).dependency;
                vertex_scores.put(x, x_score);
            }
        }
    }

    if (graph instanceof UndirectedGraph) {
        for (V v : graph.getVertices()) {
            double v_score = vertex_scores.get(v).doubleValue();
            v_score /= 2.0;
            vertex_scores.put(v, v_score);
        }
        for (E e : graph.getEdges()) {
            double e_score = edge_scores.get(e).doubleValue();
            e_score /= 2.0;
            edge_scores.put(e, e_score);
        }
    }

    vertex_data.clear();
}