List of usage examples for java.util Stack peek
public synchronized E peek()
From source file:org.alfresco.web.app.AlfrescoNavigationHandler.java
/** * Adds the current view to the stack (if required). * If the current view is already the top of the stack it is not added again * to stop the stack from growing and growing. * //from w ww . j a va2 s .c o m * @param context FacesContext */ @SuppressWarnings("unchecked") protected void addCurrentViewToStack(FacesContext context) { // if the current viewId is either the dialog or wizard container page // we need to save the state of the current dialog or wizard to the stack // If the current view is a normal page and it is not the same as the // view currently at the top of the stack (you can't launch a dialog from // the same page 2 times in a row so it must mean the user navigated away // from the first dialog) just add the viewId to the stack // work out what to add to the stack String viewId = context.getViewRoot().getViewId(); String dialogContainer = getDialogContainer(context); String wizardContainer = getWizardContainer(context); Object objectForStack = null; if (viewId.equals(dialogContainer)) { DialogManager dlgMgr = Application.getDialogManager(); objectForStack = dlgMgr.getState(); } else if (viewId.equals(wizardContainer)) { WizardManager wizMgr = Application.getWizardManager(); objectForStack = wizMgr.getState(); } else { objectForStack = viewId; } // if the stack is currently empty add the item Stack stack = getViewStack(context); if (stack.empty()) { stack.push(objectForStack); if (logger.isDebugEnabled()) logger.debug("Pushed item to view stack: " + objectForStack); } else { // if the item to go on to the stack and the top of // stack are both Strings and equals to each other // don't add anything to the stack to stop it // growing unecessarily Object topOfStack = stack.peek(); if (objectForStack instanceof String && topOfStack instanceof String && topOfStack.equals(objectForStack)) { if (logger.isDebugEnabled()) logger.debug("current view is already top of the view stack!"); } else { stack.push(objectForStack); if (logger.isDebugEnabled()) logger.debug("Pushed item to view stack: " + objectForStack); } } }
From source file:org.apache.fop.fo.FONode.java
/** * Conditionally add a new delimited text range to RANGES, where new range is * associated with current FONode. A new text range is added unless all of the following are * true:/*from ww w.j a va2 s . c o m*/ * <ul> * <li>there exists a current range RCUR in RANGES</li> * <li>RCUR is empty</li> * <li>the node of the RCUR is the same node as FN or a descendent node of FN</li> * </ul> * @param ranges stack of delimited text ranges * @return new range (if constructed and pushed onto stack) or current range (if any) or null */ private DelimitedTextRange maybeNewRange(Stack ranges) { DelimitedTextRange rCur = null; // current range (top of range stack) DelimitedTextRange rNew = null; // new range to be pushed onto range stack if (ranges.empty()) { if (isBidiRangeBlockItem()) { rNew = new DelimitedTextRange(this); } } else { rCur = (DelimitedTextRange) ranges.peek(); if (rCur != null) { if (!rCur.isEmpty() || !isSelfOrDescendent(rCur.getNode(), this)) { rNew = new DelimitedTextRange(this); } } } if (rNew != null) { ranges.push(rNew); } else { rNew = rCur; } return rNew; }
From source file:org.apache.tajo.engine.planner.rewrite.FilterPushDownRule.java
@Override public LogicalNode visitFilter(FilterPushDownContext context, LogicalPlan plan, LogicalPlan.QueryBlock block, SelectionNode selNode, Stack<LogicalNode> stack) throws PlanningException { context.pushingDownFilters/*from w w w . j av a 2s .c o m*/ .addAll(Sets.newHashSet(AlgebraicUtil.toConjunctiveNormalFormArray(selNode.getQual()))); stack.push(selNode); visit(context, plan, block, selNode.getChild(), stack); stack.pop(); if (context.pushingDownFilters.size() == 0) { // remove the selection operator if there is no search condition after selection push. LogicalNode node = stack.peek(); if (node instanceof UnaryNode) { UnaryNode unary = (UnaryNode) node; unary.setChild(selNode.getChild()); } else { throw new InvalidQueryException("Unexpected Logical Query Plan"); } } else { // if there remain search conditions // check if it can be evaluated here Set<EvalNode> matched = TUtil.newHashSet(); for (EvalNode eachEval : context.pushingDownFilters) { if (LogicalPlanner.checkIfBeEvaluatedAtThis(eachEval, selNode)) { matched.add(eachEval); } } // if there are search conditions which can be evaluated here, // push down them and remove them from context.pushingDownFilters. if (matched.size() > 0) { selNode.setQual( AlgebraicUtil.createSingletonExprFromCNF(matched.toArray(new EvalNode[matched.size()]))); context.pushingDownFilters.removeAll(matched); } } return selNode; }
From source file:org.apache.tajo.engine.planner.PhysicalPlannerImpl.java
private boolean checkIfSortEquivalance(TaskAttemptContext ctx, ScanNode scanNode, Stack<LogicalNode> node) { Enforcer enforcer = ctx.getEnforcer(); List<EnforceProperty> property = enforcer.getEnforceProperties(EnforceType.SORTED_INPUT); if (property != null && property.size() > 0 && node.peek().getType() == NodeType.SORT) { SortNode sortNode = (SortNode) node.peek(); SortedInputEnforce sortEnforcer = property.get(0).getSortedInput(); boolean condition = scanNode.getTableName().equals(sortEnforcer.getTableName()); SortSpec[] sortSpecs = LogicalNodeDeserializer.convertSortSpecs(sortEnforcer.getSortSpecsList()); return condition && TUtil.checkEquals(sortNode.getSortKeys(), sortSpecs); } else {// ww w . j a v a 2 s . com return false; } }
From source file:org.sakaiproject.authz.impl.BaseAuthzGroup.java
/** * {@inheritDoc}/* w ww .j a v a2s .co m*/ */ public Element toXml(Document doc, Stack stack) { if (m_lazy) baseAuthzGroupService.m_storage.completeGet(this); Element azGroup = doc.createElement("azGroup"); if (stack.isEmpty()) { doc.appendChild(azGroup); } else { ((Element) stack.peek()).appendChild(azGroup); } stack.push(azGroup); azGroup.setAttribute("id", getId()); if (m_providerRealmId != null) { azGroup.setAttribute("provider-id", m_providerRealmId); } if (m_maintainRole != null) { azGroup.setAttribute("maintain-role", m_maintainRole); } azGroup.setAttribute("created-id", m_createdUserId); azGroup.setAttribute("modified-id", m_lastModifiedUserId); azGroup.setAttribute("created-time", m_createdTime.toString()); azGroup.setAttribute("modified-time", m_lastModifiedTime.toString()); // properties getProperties().toXml(doc, stack); // roles (write before grants!) for (Iterator i = m_roles.values().iterator(); i.hasNext();) { BaseRole role = (BaseRole) i.next(); role.toXml(doc, stack); } // user - role grants for (Iterator i = m_userGrants.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); BaseMember grant = (BaseMember) entry.getValue(); String user = (String) entry.getKey(); Element element = doc.createElement("grant"); azGroup.appendChild(element); element.setAttribute("user", user); element.setAttribute("role", grant.role.getId()); element.setAttribute("active", Boolean.valueOf(grant.active).toString()); element.setAttribute("provided", Boolean.valueOf(grant.provided).toString()); } stack.pop(); return azGroup; }
From source file:ro.uaic.info.nlptools.ggs.engine.core.StateMachine.java
private List<State> findEmptyMatchingPath(State curentState, List<State> curentPath, Stack<GraphNode> callStack) throws GGSNullMatchException { if (curentState.index == terminalStateIndex) return curentPath; if (verifiedStates.contains(curentState)) { //this path has been travelled before and it was ok return null; }//from www. j a v a 2s.com //do not continue on non empty path if (!curentState.condition.isEmpty) { return null; } //ussing a callStack to correctly follow paths for jump transitions if (curentState.isGraphNodeEntry) { callStack.push(curentState.parentGraphNode); } if (curentState.isGraphNodeExit) { if (curentState.parentGraphNode != callStack.peek()) { return null; // this path is not valid according to the jumps/call stack } callStack.pop(); } List<State> newPath = new ArrayList<State>(curentPath); newPath.add(curentState); for (int childStateIndex : curentState.childStatesIndexes) { List<State> foundPath = findEmptyMatchingPath(states.get(childStateIndex), newPath, callStack); if (foundPath != null) return foundPath; } if (curentState.isGraphNodeEntry) { verifiedStates.add(curentState); } return null; }
From source file:org.sakaiproject.news.impl.BasicNewsService.java
/** * {@inheritDoc}/*from w w w .j a va 2 s . c o m*/ */ public String archive(String siteId, Document doc, Stack stack, String arg3, List attachments) { StringBuilder results = new StringBuilder(); Base64 codec = new Base64(); try { int count = 0; results.append("archiving " + getLabel() + " context " + Entity.SEPARATOR + siteId + Entity.SEPARATOR + SiteService.MAIN_CONTAINER + ".\n"); // get the default news url String defaultUrl = ServerConfigurationService.getString("news.feedURL", "http://sakaiproject.org/news-rss-feed"); // start with an element with our very own (service) name Element element = doc.createElement(SERVICE_NAME); element.setAttribute(VERSION_ATTR, ARCHIVE_VERSION); ((Element) stack.peek()).appendChild(element); stack.push(element); if (siteId != null && siteId.trim().length() > 0) { Element newsEl = doc.createElement(NEWS); Site site = SiteService.getSite(siteId); List sitePages = site.getPages(); if (sitePages != null && !sitePages.isEmpty()) { Iterator pageIter = sitePages.iterator(); while (pageIter.hasNext()) { SitePage currPage = (SitePage) pageIter.next(); List toolList = currPage.getTools(); Iterator toolIter = toolList.iterator(); while (toolIter.hasNext()) { ToolConfiguration toolConfig = (ToolConfiguration) toolIter.next(); if (toolConfig.getToolId().equals(TOOL_ID)) { Element newsData = doc.createElement(NEWS_ITEM); count++; //There will only be a url property if the user updated the default URL String newsUrl = toolConfig.getPlacementConfig().getProperty(NEWS_URL_PROP); if (newsUrl == null || newsUrl.length() <= 0) { // news item is using default url newsUrl = defaultUrl; } String toolTitle = toolConfig.getTitle(); String pageTitle = currPage.getTitle(); try { String encoded = new String(codec.encode(newsUrl.getBytes("UTF-8")), "UTF-8"); newsData.setAttribute(NEWS_URL, encoded); } catch (Exception e) { M_log.warn("Encode News URL - " + e); } try { String encoded = new String(codec.encode(toolTitle.getBytes("UTF-8")), "UTF-8"); newsData.setAttribute(TOOL_TITLE, encoded); } catch (Exception e) { M_log.warn("Encode News Tool Title - " + e); } try { String encoded = new String(codec.encode(pageTitle.getBytes("UTF-8")), "UTF-8"); newsData.setAttribute(PAGE_TITLE, encoded); } catch (Exception e) { M_log.warn("Encode News Page Title - " + e); } newsEl.appendChild(newsData); } } } results.append( "archiving " + getLabel() + ": (" + count + ") news items archived successfully.\n"); } else { results.append("archiving " + getLabel() + ": empty news archived.\n"); } ((Element) stack.peek()).appendChild(newsEl); stack.push(newsEl); } stack.pop(); } catch (DOMException e) { M_log.error(e.getMessage(), e); } catch (IdUnusedException e) { M_log.error(e.getMessage(), e); } catch (Exception e) { M_log.error(e.getMessage(), e); } return results.toString(); }
From source file:com.amalto.core.storage.StorageMetadataUtils.java
private static void _path(ComplexTypeMetadata type, FieldMetadata target, Stack<FieldMetadata> path, Set<ComplexTypeMetadata> processedTypes, boolean includeReferences) { // Various optimizations for very simple cases if (type == null) { throw new IllegalArgumentException("Origin can not be null"); }// w w w .j av a2s .co m if (target == null) { throw new IllegalArgumentException("Target field can not be null"); } if (Storage.PROJECTION_TYPE.equals(type.getName()) && type.hasField(target.getName())) { path.push(type.getField(target.getName())); } if (target.getContainingType() instanceof ContainedComplexTypeMetadata) { String targetPath = target.getPath(); if (type.hasField(targetPath)) { StringTokenizer tokenizer = new StringTokenizer(targetPath, "/"); //$NON-NLS-1$ StringBuilder currentPath = new StringBuilder(); while (tokenizer.hasMoreTokens()) { currentPath.append(tokenizer.nextToken()).append('/'); path.add(type.getField(currentPath.toString())); } return; } } // if (processedTypes.contains(type)) { return; } processedTypes.add(type); Collection<FieldMetadata> fields = type.getFields(); for (FieldMetadata current : fields) { path.push(current); if (current.equals(target)) { return; } if (current instanceof ContainedTypeFieldMetadata) { ComplexTypeMetadata containedType = ((ContainedTypeFieldMetadata) current).getContainedType(); _path(containedType, target, path, processedTypes, includeReferences); if (path.peek().equals(target)) { return; } for (ComplexTypeMetadata subType : containedType.getSubTypes()) { for (FieldMetadata field : subType.getFields()) { if (field.getDeclaringType() == subType) { _path(subType, target, path, processedTypes, includeReferences); if (path.peek().equals(target)) { return; } } } } } else if (current instanceof ReferenceFieldMetadata) { if (includeReferences) { ComplexTypeMetadata referencedType = ((ReferenceFieldMetadata) current).getReferencedType(); _path(referencedType, target, path, processedTypes, true); if (path.peek().equals(target)) { return; } for (ComplexTypeMetadata subType : referencedType.getSubTypes()) { for (FieldMetadata field : subType.getFields()) { if (field.getDeclaringType() == subType) { _path(subType, target, path, processedTypes, true); if (path.peek().equals(target)) { return; } } } } } } path.pop(); } }
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// w w w . j a v a2s .c om * @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:org.apache.tajo.plan.rewrite.rules.FilterPushDownRule.java
private SelectionNode createSelectionParentForNonEquiThetaJoinQuals(LogicalPlan plan, QueryBlock block, Stack<LogicalNode> stack, JoinNode joinNode, List<EvalNode> nonEquiThetaJoinQuals) { SelectionNode selectionNode = plan.createNode(SelectionNode.class); selectionNode.setInSchema(joinNode.getOutSchema()); selectionNode.setOutSchema(joinNode.getOutSchema()); selectionNode.setQual(AlgebraicUtil.createSingletonExprFromCNF(nonEquiThetaJoinQuals)); block.registerNode(selectionNode);/*from ww w . ja v a 2 s .c om*/ LogicalNode parent = stack.peek(); if (parent instanceof UnaryNode) { ((UnaryNode) parent).setChild(selectionNode); } else if (parent instanceof BinaryNode) { BinaryNode binaryParent = (BinaryNode) parent; if (binaryParent.getLeftChild().getPID() == joinNode.getPID()) { binaryParent.setLeftChild(selectionNode); } else if (binaryParent.getRightChild().getPID() == joinNode.getPID()) { binaryParent.setRightChild(selectionNode); } } else if (parent instanceof TableSubQueryNode) { ((TableSubQueryNode) parent).setSubQuery(selectionNode); } selectionNode.setChild(joinNode); return selectionNode; }