List of usage examples for java.util Stack peek
public synchronized E peek()
From source file:org.apache.synapse.util.xpath.SynapseXPathVariableContext.java
/** * Gets the variable values resolved from the context. This includes the * <dl>/*ww w .j a v a 2s . co m*/ * <dt><tt>body</tt></dt> * <dd>The SOAP 1.1 or 1.2 body element.</dd> * <dt><tt>header</tt></dt> * <dd>The SOAP 1.1 or 1.2 header element.</dd> * </dl> * and the following variable prefixes * <dl> * <dt><tt>ctx</tt></dt> * <dd>Prefix for Synapse MessageContext properties</dd> * <dt><tt>axis2</tt></dt> * <dd>Prefix for Axis2 MessageContext properties</dd> * <dt><tt>trp</tt></dt> * <dd>Prefix for the transport headers</dd> * </dl> * If the variable is unknown, this method attempts to resolve it using * the parent variable context. * * @param namespaceURI namespaces for the variable resolution * @param prefix string prefix for the variable resolution * @param localName string local name for the variable resolution * @return Resolved variable value * @throws UnresolvableException if the variable specified does not found */ public Object getVariableValue(String namespaceURI, String prefix, String localName) throws UnresolvableException { if (namespaceURI == null) { if (env != null) { if (SynapseXPathConstants.SOAP_BODY_VARIABLE.equals(localName)) { return env.getBody(); } else if (SynapseXPathConstants.SOAP_HEADER_VARIABLE.equals(localName)) { return env.getHeader(); } else if (SynapseXPathConstants.SOAP_ENVELOPE_VARIABLE.equals(localName)) { return env; } } if (prefix != null && !"".equals(prefix) && synCtx != null) { if (SynapseXPathConstants.MESSAGE_CONTEXT_VARIABLE_PREFIX.equals(prefix)) { return synCtx.getProperty(localName); } else if (SynapseXPathConstants.AXIS2_CONTEXT_VARIABLE_PREFIX.equals(prefix)) { return ((Axis2MessageContext) synCtx).getAxis2MessageContext().getProperty(localName); } else if (SynapseXPathConstants.FUNC_CONTEXT_VARIABLE_PREFIX.equals(prefix)) { Stack<TemplateContext> functionStack = (Stack) synCtx .getProperty(SynapseConstants.SYNAPSE__FUNCTION__STACK); TemplateContext topCtxt = functionStack.peek(); if (topCtxt != null) { Object result = topCtxt.getParameterValue(localName); if (result != null && result instanceof SynapseXPath && env != null) { SynapseXPath expression = (SynapseXPath) topCtxt.getParameterValue(localName); try { return expression.evaluate(env); } catch (JaxenException e) { return null; } } else { return result; } } } else if (SynapseXPathConstants.TRANSPORT_VARIABLE_PREFIX.equals(prefix)) { org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) synCtx) .getAxis2MessageContext(); Object headers = axis2MessageContext .getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); if (headers != null && headers instanceof Map) { Map headersMap = (Map) headers; return headersMap.get(localName); } else { return null; } } else if (SynapseXPathConstants.URL_VARIABLE_PREFIX.equals(prefix)) { EndpointReference toEPR = synCtx.getTo(); if (toEPR != null) { String completeURL = toEPR.getAddress(); AxisBindingOperation axisBindingOperation = (AxisBindingOperation) ((Axis2MessageContext) synCtx) .getAxis2MessageContext().getProperty(Constants.AXIS_BINDING_OPERATION); String queryParameterSeparator = null; if (axisBindingOperation != null) { queryParameterSeparator = (String) axisBindingOperation .getProperty(WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR); } if (queryParameterSeparator == null) { queryParameterSeparator = WSDL20DefaultValueHolder.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR_DEFAULT; } int i = completeURL.indexOf("?"); if (i > -1) { String queryString = completeURL.substring(i + 1); if (queryString != null && !queryString.equals("")) { String params[] = queryString.split(queryParameterSeparator); if (params == null || params.length == 0) { return ""; } for (String param : params) { String temp[] = param.split("="); if (temp != null && temp.length >= 1) { if (temp[0].equalsIgnoreCase(localName)) { try { return temp.length > 1 ? URIEncoderDecoder.decode(temp[1]) : ""; } catch (UnsupportedEncodingException e) { String msg = "Couldn't decode the URL parameter " + "value " + temp[1] + " with name " + localName; log.error(msg, e); throw new UnresolvableException(msg + e.getMessage()); } } } } } } } return ""; } else { Object o = synCtx.getProperty(prefix); if (o instanceof Map) { Object valueObject = ((Map) o).get(localName); if (valueObject != null) { return valueObject.toString(); } } } } } //try resolving using available custom extensions Object obj = XpathExtensionUtil.resolveVariableContext(synCtx, namespaceURI, prefix, localName); if (obj != null) { return obj; } return parent.getVariableValue(namespaceURI, prefix, localName); }
From source file:org.apache.cloudstack.spring.module.model.impl.DefaultModuleDefinitionSet.java
protected void loadContexts() { withModule(new WithModule() { @Override//from www. ja va2 s.c om public void with(ModuleDefinition def, Stack<ModuleDefinition> parents) { try { ApplicationContext parent = getApplicationContext(parents.peek().getName()); loadContext(def, parent); } catch (EmptyStackException e) { // The root context is already loaded, so ignore the // exception } } }); }
From source file:org.sakaiproject.authz.impl.BaseRole.java
/** * {@inheritDoc}// w w w . ja va 2s.co m */ public Element toXml(Document doc, Stack stack) { Element role = doc.createElement("role"); if (stack.isEmpty()) { doc.appendChild(role); } else { ((Element) stack.peek()).appendChild(role); } stack.push(role); role.setAttribute("id", getId()); // encode the description if (m_description != null) Xml.encodeAttribute(role, "description-enc", m_description); // encode the provider only flag if (m_providerOnly) Xml.encodeAttribute(role, "provider-only", "true"); // locks for (Iterator a = m_locks.iterator(); a.hasNext();) { String lock = (String) a.next(); Element element = doc.createElement("ability"); role.appendChild(element); element.setAttribute("lock", lock); } stack.pop(); return role; }
From source file:org.sakaiproject.archive.impl.SiteArchiver.java
/** * Archive the site definition.// w ww .j a va2 s . c o m * @param site the site. * @param doc The document to contain the xml. * @param stack The stack of elements, the top of which will be the containing * element of the "site" element. */ protected String archiveSite(Site site, Document doc, Stack stack, String fromSystem) { Element element = doc.createElement(SiteService.APPLICATION_ID); ((Element) stack.peek()).appendChild(element); stack.push(element); Element siteNode = site.toXml(doc, stack); // By default, do not include fields that have secret or password in the name String filter = m_serverConfigurationService.getString("archive.toolproperties.excludefilter", "password|secret"); Pattern pattern = null; if ((!"none".equals(filter)) && filter.length() > 0) { try { pattern = Pattern.compile(filter); } catch (Exception e) { pattern = null; } } if (pattern != null) { NodeList nl = siteNode.getElementsByTagName("property"); List<Element> toRemove = new ArrayList<Element>(); for (int i = 0; i < nl.getLength(); i++) { Element proptag = (Element) nl.item(i); String propname = proptag.getAttribute("name"); if (propname == null) continue; propname = propname.toLowerCase(); Matcher matcher = pattern.matcher(propname); if (matcher.find()) { toRemove.add(proptag); } } for (Element proptag : toRemove) { proptag.getParentNode().removeChild(proptag); } } stack.push(siteNode); // to add the realm node with user list into site List roles = new Vector(); String realmId = m_siteService.siteReference(site.getId()); //SWG "/site/" + site.getId(); try { Role role = null; AuthzGroup realm = m_authzGroupService.getAuthzGroup(realmId); Element realmNode = doc.createElement("roles"); ((Element) stack.peek()).appendChild(realmNode); stack.push(realmNode); roles.addAll(realm.getRoles()); for (int i = 0; i < roles.size(); i++) { role = (Role) roles.get(i); String roleId = role.getId(); Element node = null; if (ArchiveService.FROM_SAKAI_2_8.equals(fromSystem)) { node = doc.createElement("role"); node.setAttribute("roleId", roleId); } else { node = doc.createElement(roleId); } realmNode.appendChild(node); List users = new Vector(); users.addAll(realm.getUsersHasRole(role.getId())); for (int j = 0; j < users.size(); j++) { Element abilityNode = doc.createElement("ability"); abilityNode.setAttribute("roleId", roleId); abilityNode.setAttribute("userId", ((String) users.get(j))); node.appendChild(abilityNode); } } } catch (Exception any) { M_log.warn("archve: exception archiving site: " + site.getId() + ": ", any); } stack.pop(); return "archiving Site: " + site.getId() + "\n"; }
From source file:csns.importer.parser.MFTScoreParser.java
public void parse(MFTScoreImporter importer) { Department department = importer.getDepartment(); Date date = importer.getDate(); Scanner scanner = new Scanner(importer.getText()); scanner.useDelimiter("\\s+|\\r\\n|\\r|\\n"); while (scanner.hasNext()) { // last name String lastName = scanner.next(); while (!lastName.endsWith(",")) lastName += " " + scanner.next(); lastName = lastName.substring(0, lastName.length() - 1); // first name String firstName = scanner.next(); // score/*ww w.jav a2 s .co m*/ Stack<String> stack = new Stack<String>(); String s = scanner.next(); while (!isScore(s)) { stack.push(s); s = scanner.next(); } int value = Integer.parseInt(s); // authorization code stack.pop(); // cin String cin = null; if (!stack.empty() && isCin(stack.peek())) cin = stack.pop(); // user User user = null; if (cin != null) user = userDao.getUserByCin(cin); else { List<User> users = userDao.getUsers(lastName, firstName); if (users.size() == 1) user = users.get(0); } if (user != null) { MFTScore score = mftScoreDao.getScore(department, date, user); if (score == null) { score = new MFTScore(); score.setDepartment(department); score.setDate(date); score.setUser(user); } else { logger.info(user.getId() + ": " + score.getValue() + " => " + value); } score.setValue(value); importer.getScores().add(score); } else { User failedUser = new User(); failedUser.setLastName(lastName); failedUser.setFirstName(firstName); failedUser.setCin(cin); importer.getFailedUsers().add(failedUser); } logger.debug(lastName + "," + firstName + "," + cin + "," + value); } scanner.close(); }
From source file:DOM2SAX.java
/** * Begin the scope of namespace prefix. Forward the event to the SAX handler * only if the prefix is unknown or it is mapped to a different URI. *///from w w w . ja va2 s . co m private boolean startPrefixMapping(String prefix, String uri) throws SAXException { boolean pushed = true; Stack uriStack = (Stack) prefixes.get(prefix); if (uriStack != null) { if (uriStack.isEmpty()) { contentHandler.startPrefixMapping(prefix, uri); uriStack.push(uri); } else { final String lastUri = (String) uriStack.peek(); if (!lastUri.equals(uri)) { contentHandler.startPrefixMapping(prefix, uri); uriStack.push(uri); } else { pushed = false; } } } else { contentHandler.startPrefixMapping(prefix, uri); uriStack = new Stack(); prefixes.put(prefix, uriStack); uriStack.push(uri); } return pushed; }
From source file:com.feilong.commons.core.util.CollectionsUtilTest.java
/** * TestCollectionsUtilTest.//from ww w . jav a 2 s . com */ @Test public void testCollectionsUtilTest2() { Stack<Object> stack = new Stack<Object>(); stack.add("1"); stack.add("2"); stack.add("3"); stack.add("4"); if (log.isDebugEnabled()) { log.debug("" + stack.firstElement()); log.debug("" + stack.peek()); log.debug("" + stack.pop()); log.debug(JsonUtil.format(stack)); } }
From source file:org.cvasilak.jboss.mobile.app.activities.JBossServerRootActivity.java
public void addFragment(Fragment fragment) { // Select proper stack ActionBar.Tab tab = getSupportActionBar().getSelectedTab(); Stack<String> backStack = backStacks.get(tab.getTag()); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); // Animate transfer to new fragment ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right); // Get topmost fragment String tag = backStack.peek(); Fragment top = getSupportFragmentManager().findFragmentByTag(tag); ft.detach(top);/*ww w. j a v a2s . c o m*/ // Add new fragment addFragment(fragment, backStack, ft); ft.commit(); }
From source file:eu.annocultor.utils.HierarchyTracingFilter.java
private Set<String> traceBroaderDepthFirst(RepositoryConnection connection, ValueFactory factory, List<StringInStack> topConcepts) throws Exception { // trace skos:broader tree top-down Stack<StringInStack> urlsToCheck = new Stack<StringInStack>(); urlsToCheck.addAll(topConcepts);//w w w . j av a 2s.c o m Set<String> passedUrls = new HashSet<String>(); while (!urlsToCheck.isEmpty()) { StringInStack url = urlsToCheck.pop(); if (!StringUtils.isEmpty(url.getString()) && passedUrls.add(url.getString())) { List<StringInStack> children = fetchNarrower(connection, factory, url, urlsToCheck.isEmpty() ? null : urlsToCheck.peek()); Collections.sort(children); urlsToCheck.addAll(children); } } return passedUrls; }
From source file:com.ikanow.infinit.e.application.utils.LogstashConfigUtils.java
public static BasicDBObject parseLogstashConfig(String configFile, StringBuffer error) { BasicDBObject tree = new BasicDBObject(); // Stage 0: remove escaped "s and 's (for the purpose of the validation): // (prevents tricksies with escaped "s and then #s) // (http://stackoverflow.com/questions/5082398/regex-to-replace-single-backslashes-excluding-those-followed-by-certain-chars) configFile = configFile.replaceAll("(?<!\\\\)(?:((\\\\\\\\)*)\\\\)[\"']", "X"); //TESTED (by hand - using last 2 fields of success_2_1) // Stage 1: remove #s, and anything in quotes (for the purpose of the validation) configFile = configFile.replaceAll("(?m)(?:([\"'])(?:(?!\\1).)*\\1)", "VALUE").replaceAll("(?m)(?:#.*$)", "");/*from w w w. j a v a 2 s .c o m*/ //TESTED (2_1 - including with a # inside the ""s - Event_Date -> Event_#Date) //TESTED (2_2 - various combinations of "s nested inside 's) ... yes that is a negative lookahead up there - yikes! // Stage 2: get a nested list of objects int depth = 0; int ifdepth = -1; Stack<Integer> ifStack = new Stack<Integer>(); BasicDBObject inputOrFilter = null; Matcher m = _navigateLogstash.matcher(configFile); // State: String currTopLevelBlockName = null; String currSecondLevelBlockName = null; BasicDBObject currSecondLevelBlock = null; while (m.find()) { boolean simpleField = false; //DEBUG //System.out.println("--DEPTH="+depth + " GROUP=" + m.group() + " IFS" + Arrays.toString(ifStack.toArray())); //System.out.println("STATES: " + currTopLevelBlockName + " AND " + currSecondLevelBlockName); if (m.group().equals("}")) { if (ifdepth == depth) { // closing an if statement ifStack.pop(); if (ifStack.isEmpty()) { ifdepth = -1; } else { ifdepth = ifStack.peek(); } } //TESTED (1_1bc, 2_1) else { // closing a processing block depth--; if (depth < 0) { // {} Mismatch error.append("{} Mismatch (})"); return null; } //TESTED (1_1abc) } } else { // new attribute! String typeName = m.group(1); if (null == typeName) { // it's an if statement or a string value typeName = m.group(4); if (null != typeName) { simpleField = true; } } else if (typeName.equalsIgnoreCase("else")) { // It's an if statement.. typeName = null; } if (null == typeName) { // if statement after all // Just keep track of ifs so we can ignore them ifStack.push(depth); ifdepth = depth; // (don't increment depth) } //TESTED (1_1bc, 2_1) else { // processing block String subTypeName = m.group(3); if (null != subTypeName) { // eg codec.multiline typeName = typeName + "." + subTypeName; } //TESTED (2_1, 2_3) if (depth == 0) { // has to be one of input/output/filter) String topLevelType = typeName.toLowerCase(); if (topLevelType.equalsIgnoreCase("input") || topLevelType.equalsIgnoreCase("filter")) { if (tree.containsField(topLevelType)) { error.append("Multiple input or filter blocks: " + topLevelType); return null; } //TESTED (1_3ab) else { inputOrFilter = new BasicDBObject(); tree.put(topLevelType, inputOrFilter); // Store state: currTopLevelBlockName = topLevelType; } //TESTED (*) } else { if (topLevelType.equalsIgnoreCase("output")) { error.append( "Not allowed output blocks - these are appended automatically by the logstash harvester"); } else { error.append("Unrecognized processing block: " + topLevelType); } return null; } //TESTED (1_4a) } else if (depth == 1) { // processing blocks String subElType = typeName.toLowerCase(); // Some validation: can't include a type called "filter" anywhere if ((null != currTopLevelBlockName) && currTopLevelBlockName.equals("input")) { if (subElType.equals("filter") || subElType.endsWith(".filter")) { error.append("Not allowed sub-elements of input called 'filter' (1)"); return null; } } //TESTED (1_5b) BasicDBList subElements = (BasicDBList) inputOrFilter.get(subElType); if (null == subElements) { subElements = new BasicDBList(); inputOrFilter.put(subElType, subElements); } BasicDBObject newEl = new BasicDBObject(); subElements.add(newEl); // Store state: currSecondLevelBlockName = subElType; currSecondLevelBlock = newEl; } //TESTED (*) else if (depth == 2) { // attributes of processing blocks // we'll just store the field names for these and do any simple validation that was too complicated for the regexes String subSubElType = typeName.toLowerCase(); // Validation: if (null != currTopLevelBlockName) { // 1] sincedb path if (currTopLevelBlockName.equals("input") && (null != currSecondLevelBlockName)) { // (don't care what the second level block name is - no sincedb allowed) if (subSubElType.equalsIgnoreCase("sincedb_path")) { error.append("Not allowed sincedb_path in input.* block"); return null; } //TESTED (1_5a) // 2] no sub-(-sub etc)-elements of input called filter if (subSubElType.equals("filter") || subSubElType.endsWith(".filter")) { error.append("Not allowed sub-elements of input called 'filter' (2)"); return null; } //TESTED (1_5c) } } // Store in map: if (null != currSecondLevelBlock) { currSecondLevelBlock.put(subSubElType, new BasicDBObject()); } } // (won't go any deeper than this) if (!simpleField) { depth++; } } } } if (0 != depth) { error.append("{} Mismatch ({)"); return null; } //TESTED (1_2a) return tree; }