Example usage for java.util Stack Stack

List of usage examples for java.util Stack Stack

Introduction

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

Prototype

public Stack() 

Source Link

Document

Creates an empty Stack.

Usage

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

private static SchemaModel map(XSModel xsModel, int maxRecusiveDepth) {
    // get namespaces
    StringList namespaces = xsModel.getNamespaces();
    List<String> namesspaceList = new ArrayList<String>();
    for (int i = 0; i < namespaces.getLength(); i++) {
        namesspaceList.add(namespaces.item(i));
    }//from ww w .  j  a va2  s.  c om

    // get top-level complex elements
    XSNamedMap elements = xsModel.getComponents(XSConstants.ELEMENT_DECLARATION);
    List<SchemaElementComplex> components = new ArrayList<SchemaElementComplex>();

    for (int i = 0; i < elements.getLength(); i++) {
        XSObject object = elements.item(i);
        if (!(object instanceof XSElementDeclaration)) {
            continue;
        }

        XSElementDeclaration decl = (XSElementDeclaration) elements.item(i);
        if (!isComplexTypeCategory(decl.getTypeDefinition().getTypeCategory())) {
            continue;
        }

        XSComplexTypeDefinition complexActualElement = (XSComplexTypeDefinition) decl.getTypeDefinition();
        String name = object.getName();
        String namespace = object.getNamespace();
        Stack<NamespaceNamePair> nameNamespaceStack = new Stack<NamespaceNamePair>();
        NamespaceNamePair nameNamespace = new NamespaceNamePair(namespace, name);
        nameNamespaceStack.add(nameNamespace);

        if (log.isDebugEnabled()) {
            log.debug("Processing component " + namespace + " " + name);
        }

        SchemaElementComplex complexElement = process(name, namespace, complexActualElement, false,
                nameNamespaceStack, maxRecusiveDepth);

        if (log.isDebugEnabled()) {
            log.debug("Adding component " + namespace + " " + name);
        }
        components.add(complexElement);
    }

    return new SchemaModel(components, namesspaceList);
}

From source file:com.buildabrand.gsb.util.URLUtils.java

private String canonicalizePath(String path) {
    if (StringUtils.isEmpty(path)) {
        return "/";
    }/*  w w  w .  j a v  a2 s  .  c  o  m*/

    // There are some cases where the path will not start with '/'.  Example:
    // "ftp://host.com?q"  -- the hostname is 'host.com' and the path '%3Fq'.
    // Browsers typically do prepend a leading slash to the path in this case,
    // we'll do the same.
    if (!path.startsWith("/")) {
        path = "/" + path;
    }

    path = escape(path);

    Stack<String> pathComponents = new Stack<String>();
    for (String pathComponent : StringUtils.split(path, '/')) {
        // If the path component is '..' we skip it and remove the preceding path
        // component if there are any.
        if (pathComponent.equals("..")) {
            if (!pathComponents.isEmpty()) {
                pathComponents.pop();
            }
        } else if (!pathComponent.equals(".") && !pathComponent.equals("")) {
            // We skip empty path components to remove successive slashes (i.e.,
            // // -> /).  Note: this means that the leading and trailing slash will
            // also be removed and need to be re-added afterwards.
            //
            // If the path component is '.' we also skip it (i.e., /./ -> /).
            pathComponents.add(pathComponent);
        }
    }

    // Put the path components back together and re-add the leading slash which
    // got stripped by removing empty path components.
    String canonicalPath = "/" + StringUtils.join(pathComponents, "/");
    // If necessary we also re-add the trailing slash.
    if (path.endsWith("/") && !canonicalPath.endsWith("/")) {
        canonicalPath += "/";
    }

    return canonicalPath;
}

From source file:de.mpg.escidoc.services.citationmanager.utils.XsltHelper.java

/**
 * Check of the balanced tags sup/sub/*from  w  w  w  .j a v a2s. co  m*/
 * @param snippet
 * @return <code>true</code> if balanced, <code>false</code> otherwise 
 */
public static boolean isBalanced(String snippet) {
    if (snippet == null)
        return true; //????

    Stack<String> s = new Stack<String>();
    Matcher m = SUBS_OR_SUPS.matcher(snippet);
    while (m.find()) {
        String tag = m.group(1);
        if (tag.toLowerCase().startsWith("su")) {
            s.push(tag);
        } else {
            if (s.empty() || !tag.equals("/" + s.pop())) {
                return false;
            }
        }
    }

    return s.empty();
}

From source file:com.linkedin.restli.tools.idlcheck.RestLiResourceModelCompatibilityChecker.java

/**
 * Check backwards compatibility between two idl (.restspec.json) files.
 *
 * @param prevRestspecPath previously existing idl file
 * @param currRestspecPath current idl file
 * @param compatLevel compatibility level which affects the return value
 * @return true if the check result conforms the compatibility level requirement
 *         e.g. false if backwards compatible changes are found but the level is equivalent
 *//*w w w  . j ava 2s.  c om*/
public boolean check(String prevRestspecPath, String currRestspecPath, CompatibilityLevel compatLevel) {
    _prevRestspecPath = prevRestspecPath;
    _currRestspecPath = currRestspecPath;

    Stack<Object> path = new Stack<Object>();
    path.push("");

    ResourceSchema prevRec = null;
    ResourceSchema currRec = null;

    try {
        prevRec = _codec.readResourceSchema(new FileInputStream(prevRestspecPath));
    } catch (FileNotFoundException e) {
        _infoMap.addRestSpecInfo(CompatibilityInfo.Type.RESOURCE_NEW, path, currRestspecPath);
    } catch (IOException e) {
        _infoMap.addRestSpecInfo(CompatibilityInfo.Type.OTHER_ERROR, path, e.getMessage());
    }

    try {
        currRec = _codec.readResourceSchema(new FileInputStream(currRestspecPath));
    } catch (FileNotFoundException e) {
        _infoMap.addRestSpecInfo(CompatibilityInfo.Type.RESOURCE_MISSING, path, prevRestspecPath);
    } catch (Exception e) {
        _infoMap.addRestSpecInfo(CompatibilityInfo.Type.OTHER_ERROR, path, e.getMessage());
    }

    if (prevRec == null || currRec == null) {
        return _infoMap.isCompatible(compatLevel);
    }

    final DataSchemaResolver resolver;
    if (_resolverPath == null) {
        resolver = new DefaultDataSchemaResolver();
    } else {
        resolver = new FileDataSchemaResolver(SchemaParserFactory.instance(), _resolverPath);
    }

    ResourceCompatibilityChecker checker = new ResourceCompatibilityChecker(prevRec, resolver, currRec,
            resolver);
    boolean check = checker.check(compatLevel);
    _infoMap.addAll(checker.getInfoMap());
    return check;
}

From source file:com.consol.citrus.Citrus.java

/**
 * Method to retrieve the full class name for a test.
 * Hierarchy of folders is supported, too.
 *
 * @param startDir directory where to start the search
 * @param testName test name to search for
 * @throws CitrusRuntimeException//from  w  w w  .j  av a  2 s. c  o  m
 * @return the class name of the test
 */
private String getClassNameForTest(final String startDir, final String testName) throws FileNotFoundException {
    /* Stack to hold potential sub directories */
    final Stack<File> dirs = new Stack<File>();
    /* start directory */
    final File startdir = new File(startDir);

    if (startdir.isDirectory()) {
        dirs.push(startdir);
    }

    log.info("Starting test search in dir: " + startdir.getAbsolutePath());

    /* walk through the directories */
    while (dirs.size() > 0) {
        File file = dirs.pop();
        File[] found = file.listFiles(new TestCaseFileNameFilter());

        for (int i = 0; i < found.length; i++) {
            /* Subfolder support */
            if (found[i].isDirectory()) {
                dirs.push(found[i]);
            } else {
                if ((testName + XML_FILE_EXTENSION).equalsIgnoreCase(found[i].getName())) {
                    String fileName = found[i].getPath();
                    fileName = fileName.substring(0, (fileName.length() - XML_FILE_EXTENSION.length()));

                    if (fileName.startsWith(File.separator)) {
                        fileName = fileName.substring(File.separator.length());
                    }

                    //replace operating system path separator and translate to class package string
                    fileName = fileName.substring(
                            startDir.startsWith(File.separator) ? startDir.length() - 1 : startDir.length())
                            .replace(File.separatorChar, '.');

                    if (log.isDebugEnabled()) {
                        log.debug("Found test '" + fileName + "'");
                    }

                    return fileName;
                }
            }
        }
    }

    throw new CitrusRuntimeException(
            "Could not find test with name '" + testName + "'. Test directory is: " + startDir);
}

From source file:com.symbian.driver.core.report.Result.java

/**  
 * //from  w  w  w  . j a va2 s  .co  m
 * @param aVisitor
 * @param aTask
 * @param aIsPcVisitor
 * @return 
 */
public boolean initResult(final Visitor aVisitor, final Task aTask, boolean aIsPcVisitor) {

    boolean lReturn = true;
    // Setup listener to the Visitor
    aVisitor.addVisitorListener(new IVisitorEventListener() {

        private Stack<Long> iTimerStack = new Stack<Long>();

        public void taskFinished(TaskFinishedEvent aVisitorEvent) {
            iTaskFinishedEvent = aVisitorEvent;

            long lDuration = 0;
            if (!iTimerStack.isEmpty()) {
                lDuration = iTimerStack.pop().longValue();
            }

            getReport(lDuration);
        }

        public void taskStarted(TaskStartedEvent aVisitorEvent) {
            iTimerStack.push(new Long(System.currentTimeMillis()));
        }
    });

    try {
        TDConfig CONFIG = TDConfig.getInstance();
        //set XML output location
        sOutputPath = new File(
                (aIsPcVisitor ? CONFIG.getPreferenceFile(TDConfig.REPOSITORY_ROOT)
                        : CONFIG.getPreferenceFile(TDConfig.RESULT_ROOT)),
                ModelUtils.getBaseDirectory(
                        (aIsPcVisitor ? -1 : CONFIG.getPreferenceInteger(TDConfig.RUN_NUMBER))));

        iReportName = (aIsPcVisitor ? "build" : "run" + CONFIG.getPreferenceInteger(TDConfig.RUN_NUMBER)) + "_"
                + CONFIG.getPreference(TDConfig.BUILD_NUMBER);
        iReportXml = new File(sOutputPath, iReportName + ".xml");

        setReportHeader(aTask, aIsPcVisitor);

    } catch (ParseException lParseException) {
        LOGGER.log(Level.SEVERE, "Could not get the configuration", lParseException);
        lReturn = false;
    } catch (SecurityException lSecurityException) {
        lReturn = false;
        LOGGER.log(Level.SEVERE, "Sercurity exception while adding logging handler", lSecurityException);
    }
    return lReturn;
}

From source file:com.thoughtworks.go.util.FileUtil.java

public static File normalize(final String path) {
    Stack s = new Stack();
    String[] dissect = dissect(path);
    s.push(dissect[0]);/* ww w.j a va2  s.  c o m*/

    StringTokenizer tok = new StringTokenizer(dissect[1], File.separator);
    while (tok.hasMoreTokens()) {
        String thisToken = tok.nextToken();
        if (".".equals(thisToken)) {
            continue;
        }
        if ("..".equals(thisToken)) {
            if (s.size() < 2) {
                // Cannot resolve it, so skip it.
                return new File(path);
            }
            s.pop();
        } else { // plain component
            s.push(thisToken);
        }
    }
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.size(); i++) {
        if (i > 1) {
            // not before the filesystem root and not after it, since root
            // already contains one
            sb.append(File.separatorChar);
        }
        sb.append(s.elementAt(i));
    }
    return new File(sb.toString());
}

From source file:org.springjutsu.validation.ValidationEvaluationContext.java

/**
 * Constructs a new ValidationEvaluationContext.
 * There will be a single ValidationEvalautionContext created
 * for each model validation performed.  
 * @param model The object to validate/* w  w  w . j  a  v  a 2s  .  com*/
 * @param errors The errors object on which to record errors
 * @param validationHints Any JSR-303 validation groups to activate
 */
public ValidationEvaluationContext(Object model, Errors errors, Object... validationHints) {
    this.modelWrapper = model == null ? null : new BeanWrapperImpl(model);
    this.errors = errors;
    this.validationHints = new String[validationHints.length];
    for (int i = 0; i < validationHints.length; i++) {
        this.validationHints[i] = (validationHints[i] instanceof Class<?>)
                ? ((Class<?>) validationHints[i]).getCanonicalName()
                : String.valueOf(validationHints[i]);
    }
    this.spelResolver = new SPELResolver(model);
    this.spelResolver.getScopedContext().addPropertyAccessor(new CurrentModelPropertyAccessor());
    this.spelResolver.getScopedContext().addContext("currentModel", this.new CurrentModelAccessor());
    this.nestedPath = new Stack<String>();
    this.checkedModelHashes = new Stack<List<Integer>>();
    this.checkedModelHashes.push(new ArrayList<Integer>());
    this.templateNames = new Stack<String>();
    this.templateBasePaths = new Stack<String>();
    this.collectionPathReplacements = new LinkedHashMap<String, String>();
}

From source file:com.spidertracks.datanucleus.query.runtime.EqualityOperand.java

@Override
public Operand optimizeDescriminator(Bytes descriminatorColumnValue, List<Bytes> possibleValues) {

    // the equality node is always a leaf, so we don't need to recurse

    if (possibleValues.size() == 1) {

        IndexExpression leaf = new IndexExpression();

        leaf.setColumn_name(descriminatorColumnValue.getBytes());

        leaf.setValue(possibleValues.get(0).getBytes());

        leaf.setOp(IndexOperator.EQ);// w  ww  . j  a v  a 2s . c  o  m

        // discriminator fields are always indexed.
        addExpression(leaf, true);

        return this;
    }

    Stack<EqualityOperand> eqOps = new Stack<EqualityOperand>();

    Stack<OrOperand> orOps = new Stack<OrOperand>();

    for (Bytes value : possibleValues) {

        if (orOps.size() == 2) {
            OrOperand orOp = new OrOperand();
            orOp.setLeft(orOps.pop());
            orOp.setRight(orOps.pop());

            orOps.push(orOp);
        }

        if (eqOps.size() == 2) {
            OrOperand orOp = new OrOperand();
            orOp.setLeft(eqOps.pop());
            orOp.setRight(eqOps.pop());
            orOps.push(orOp);
        }

        EqualityOperand subClass = new EqualityOperand(clause.getCount());

        // add the existing clause
        subClass.addAll(this.getIndexClause().getExpressions(), this.isIndexed());

        IndexExpression expression = new IndexExpression();

        expression.setColumn_name(descriminatorColumnValue.getBytes());

        expression.setValue(value.getBytes());

        expression.setOp(IndexOperator.EQ);

        // now add the discriminator, discriminator is always indexed.
        subClass.addExpression(expression, true);

        // push onto the stack
        eqOps.push(subClass);

    }

    // only rewritten without needing to OR to other clauses, short circuit

    while (eqOps.size() > 0) {

        OrOperand orOp = new OrOperand();

        if (eqOps.size() % 2 == 0) {
            orOp.setLeft(eqOps.pop());
            orOp.setRight(eqOps.pop());

        }

        else {
            orOp.setLeft(eqOps.pop());
            orOp.setRight(orOps.pop());
        }

        orOps.push(orOp);
    }

    while (orOps.size() > 1) {

        OrOperand orOp = new OrOperand();

        orOp.setLeft(orOps.pop());
        orOp.setRight(orOps.pop());

        orOps.push(orOp);
    }

    // check if there's anything left in the eqOps.

    return orOps.pop();

}

From source file:com._4dconcept.springframework.data.marklogic.core.query.QueryBuilder.java

@Nullable
private Criteria buildCriteria(Object bean, MarklogicPersistentEntity<?> entity) {
    Stack<Criteria> stack = new Stack<>();
    PersistentPropertyAccessor propertyAccessor = entity.getPropertyAccessor(bean);

    entity.doWithProperties((PropertyHandler<MarklogicPersistentProperty>) property -> {
        Object value = propertyAccessor.getProperty(property);
        if (hasContent(value)) {
            if (stack.empty()) {
                stack.push(buildCriteria(property, value));
            } else {
                Criteria criteria = stack.peek();
                if (criteria.getOperator() == null) {
                    Criteria andCriteria = new Criteria(Criteria.Operator.and,
                            new ArrayList<>(Arrays.asList(criteria, buildCriteria(property, value))));
                    stack.pop();// w  ww.  j a  v a 2 s  .c om
                    stack.push(andCriteria);
                } else {
                    Criteria subCriteria = buildCriteria(property, value);
                    if (subCriteria != null) {
                        criteria.add(subCriteria);
                    }
                }
            }
        }
    });

    return stack.empty() ? null : stack.peek();
}