List of usage examples for java.util Stack search
public synchronized int search(Object o)
From source file:org.apache.roller.weblogger.util.HTMLSanitizer.java
public static SanitizeResult sanitizer(String html, Pattern allowedTags, Pattern forbiddenTags) { SanitizeResult ret = new SanitizeResult(); Stack<String> openTags = new Stack(); List<String> tokens = tokenize(html); // ------------------- LOOP for every token -------------------------- for (String token : tokens) { boolean isAcceptedToken = false; Matcher startMatcher = tagStartPattern.matcher(token); Matcher endMatcher = tagClosePattern.matcher(token); //-------------------------------------------------------------------------------- COMMENT <!-- ......... --> if (commentPattern.matcher(token).find()) { ret.val = ret.val + token + (token.endsWith("-->") ? "" : "-->"); ret.invalidTags.add(token + (token.endsWith("-->") ? "" : "-->")); continue; //-------------------------------------------------------------------------------- OPEN TAG <tag .........> } else if (startMatcher.find()) { //tag name extraction String tag = startMatcher.group(1).toLowerCase(); //----------------------------------------------------- FORBIDDEN TAG <script .........> if (forbiddenTags.matcher(tag).find()) { ret.invalidTags.add("<" + tag + ">"); continue; // -------------------------------------------------- WELL KNOWN TAG } else if (allowedTags.matcher(tag).find()) { String cleanToken = "<" + tag; String tokenBody = startMatcher.group(2); //first test table consistency //table tbody tfoot thead th tr td if ("thead".equals(tag) || "tbody".equals(tag) || "tfoot".equals(tag) || "tr".equals(tag)) { if (openTags.search("table") < 1) { ret.invalidTags.add("<" + tag + ">"); continue; }//from w ww. j a va2 s .c o m } else if ("td".equals(tag) || "th".equals(tag)) { if (openTags.search("tr") < 1) { ret.invalidTags.add("<" + tag + ">"); continue; } } // then test properties Matcher attributes = attributesPattern.matcher(tokenBody); boolean foundURL = false; // URL flag while (attributes.find()) { String attr = attributes.group(1).toLowerCase(); String val = attributes.group(2); // we will accept href in case of <A> if ("a".equals(tag) && "href".equals(attr)) { // <a href="......"> String[] customSchemes = { "http", "https" }; if (new UrlValidator(customSchemes).isValid(val)) { foundURL = true; } else { // may be it is a mailto? // case <a href="mailto:pippo@pippo.com?subject=...." if (val.toLowerCase().startsWith("mailto:") && val.indexOf('@') >= 0) { String val1 = "http://www." + val.substring(val.indexOf('@') + 1); if (new UrlValidator(customSchemes).isValid(val1)) { foundURL = true; } else { ret.invalidTags.add(attr + " " + val); val = ""; } } else { ret.invalidTags.add(attr + " " + val); val = ""; } } } else if (tag.matches("img|embed") && "src".equals(attr)) { // <img src="......"> String[] customSchemes = { "http", "https" }; if (new UrlValidator(customSchemes).isValid(val)) { foundURL = true; } else { ret.invalidTags.add(attr + " " + val); val = ""; } } else if ("href".equals(attr) || "src".equals(attr)) { // <tag src/href="......"> skipped ret.invalidTags.add(tag + " " + attr + " " + val); continue; } else if (attr.matches("width|height")) { // <tag width/height="......"> if (!val.toLowerCase().matches("\\d+%|\\d+$")) { // test numeric values ret.invalidTags.add(tag + " " + attr + " " + val); continue; } } else if ("style".equals(attr)) { // <tag style="......"> // then test properties Matcher styles = stylePattern.matcher(val); String cleanStyle = ""; while (styles.find()) { String styleName = styles.group(1).toLowerCase(); String styleValue = styles.group(2); // suppress invalid styles values if (forbiddenStylePattern.matcher(styleValue).find()) { ret.invalidTags.add(tag + " " + attr + " " + styleValue); continue; } // check if valid url Matcher urlStyleMatcher = urlStylePattern.matcher(styleValue); if (urlStyleMatcher.find()) { String[] customSchemes = { "http", "https" }; String url = urlStyleMatcher.group(1); if (!new UrlValidator(customSchemes).isValid(url)) { ret.invalidTags.add(tag + " " + attr + " " + styleValue); continue; } } cleanStyle = cleanStyle + styleName + ":" + encode(styleValue) + ";"; } val = cleanStyle; } else if (attr.startsWith("on")) { // skip all javascript events ret.invalidTags.add(tag + " " + attr + " " + val); continue; } else { // by default encode all properies val = encode(val); } cleanToken = cleanToken + " " + attr + "=\"" + val + "\""; } cleanToken = cleanToken + ">"; isAcceptedToken = true; // for <img> and <a> if (tag.matches("a|img|embed") && !foundURL) { isAcceptedToken = false; cleanToken = ""; } token = cleanToken; // push the tag if require closure and it is accepted (otherwirse is encoded) if (isAcceptedToken && !(standAloneTags.matcher(tag).find() || selfClosed.matcher(tag).find())) { openTags.push(tag); } // -------------------------------------------------------------------------------- UNKNOWN TAG } else { ret.invalidTags.add(token); ret.val = ret.val + token; continue; } // -------------------------------------------------------------------------------- CLOSE TAG </tag> } else if (endMatcher.find()) { String tag = endMatcher.group(1).toLowerCase(); //is self closing if (selfClosed.matcher(tag).find()) { ret.invalidTags.add(token); continue; } if (forbiddenTags.matcher(tag).find()) { ret.invalidTags.add("/" + tag); continue; } if (!allowedTags.matcher(tag).find()) { ret.invalidTags.add(token); ret.val = ret.val + token; continue; } else { String cleanToken = ""; // check tag position in the stack int pos = openTags.search(tag); // if found on top ok for (int i = 1; i <= pos; i++) { //pop all elements before tag and close it String poppedTag = openTags.pop(); cleanToken = cleanToken + "</" + poppedTag + ">"; isAcceptedToken = true; } token = cleanToken; } } ret.val = ret.val + token; if (isAcceptedToken) { ret.html = ret.html + token; //ret.text = ret.text + " "; } else { String sanToken = htmlEncodeApexesAndTags(token); ret.html = ret.html + sanToken; ret.text = ret.text + htmlEncodeApexesAndTags(removeLineFeed(token)); } } // must close remaining tags while (openTags.size() > 0) { //pop all elements before tag and close it String poppedTag = openTags.pop(); ret.html = ret.html + "</" + poppedTag + ">"; ret.val = ret.val + "</" + poppedTag + ">"; } //set boolean value ret.isValid = ret.invalidTags.size() == 0; return ret; }
From source file:org.apache.struts2.components.Component.java
/** * Finds the nearest ancestor of this component stack. * @param clazz the class to look for, or if assignable from. * @return the component if found, <tt>null</tt> if not. *//* w w w . j av a 2 s .com*/ protected Component findAncestor(Class clazz) { Stack componentStack = getComponentStack(); int currPosition = componentStack.search(this); if (currPosition >= 0) { int start = componentStack.size() - currPosition - 1; //for (int i = componentStack.size() - 2; i >= 0; i--) { for (int i = start; i >= 0; i--) { Component component = (Component) componentStack.get(i); if (clazz.isAssignableFrom(component.getClass()) && component != this) { return component; } } } return null; }
From source file:org.beangle.struts2.view.component.Component.java
/** * Finds the nearest ancestor of this component stack. * /* w w w.ja v a 2 s.co m*/ * @param clazz * the class to look for, or if assignable from. * @return the component if found, <tt>null</tt> if not. */ @SuppressWarnings("unchecked") protected <T extends Component> T findAncestor(Class<T> clazz) { Stack<? extends Component> componentStack = getComponentStack(); int currPosition = componentStack.search(this); if (currPosition >= 0) { int start = componentStack.size() - currPosition - 1; // for (int i = componentStack.size() - 2; i >= 0; i--) { for (int i = start; i >= 0; i--) { Component component = componentStack.get(i); if (clazz.isAssignableFrom(component.getClass()) && component != this) { return (T) component; } } } return null; }
From source file:org.jblooming.utilities.HtmlSanitizer.java
public static SanitizeResult sanitizer(String html, Pattern allowedTags, Pattern forbiddenTags) { SanitizeResult ret = new SanitizeResult(); Stack<String> openTags = new Stack(); List<String> tokens = tokenize(html); // ------------------- LOOP for every token -------------------------- for (String token : tokens) { boolean isAcceptedToken = false; Matcher startMatcher = tagStartPattern.matcher(token); Matcher endMatcher = tagClosePattern.matcher(token); //-------------------------------------------------------------------------------- COMMENT <!-- ......... --> if (commentPattern.matcher(token).find()) { ret.val = ret.val + token + (token.endsWith("-->") ? "" : "-->"); ret.invalidTags.add(token + (token.endsWith("-->") ? "" : "-->")); continue; //-------------------------------------------------------------------------------- OPEN TAG <tag .........> } else if (startMatcher.find()) { //tag name extraction String tag = startMatcher.group(1).toLowerCase(); //----------------------------------------------------- FORBIDDEN TAG <script .........> if (forbiddenTags.matcher(tag).find()) { ret.invalidTags.add("<" + tag + ">"); continue; // -------------------------------------------------- WELL KNOWN TAG } else if (allowedTags.matcher(tag).find()) { String cleanToken = "<" + tag; String tokenBody = startMatcher.group(2); //first test table consistency //table tbody tfoot thead th tr td if ("thead".equals(tag) || "tbody".equals(tag) || "tfoot".equals(tag) || "tr".equals(tag)) { if (openTags.search("table") < 1) { ret.invalidTags.add("<" + tag + ">"); continue; }/*from w w w.j a v a2 s . c o m*/ } else if ("td".equals(tag) || "th".equals(tag)) { if (openTags.search("tr") < 1) { ret.invalidTags.add("<" + tag + ">"); continue; } } // then test properties Matcher attributes = attributesPattern.matcher(tokenBody); boolean foundURL = false; // URL flag while (attributes.find()) { String attr = attributes.group(1).toLowerCase(); String val = attributes.group(2); // we will accept href in case of <A> if ("a".equals(tag) && "href".equals(attr)) { // <a href="......"> String[] customSchemes = { "http", "https" }; if (new UrlValidator(customSchemes).isValid(val)) { foundURL = true; } else { // may be it is a mailto? // case <a href="mailto:pippo@pippo.com?subject=...." if (val.toLowerCase().startsWith("mailto:") && val.indexOf("@") >= 0) { String val1 = "http://www." + val.substring(val.indexOf("@") + 1); if (new UrlValidator(customSchemes).isValid(val1)) { foundURL = true; } else { ret.invalidTags.add(attr + " " + val); val = ""; } } else { ret.invalidTags.add(attr + " " + val); val = ""; } } } else if (tag.matches("img|embed") && "src".equals(attr)) { // <img src="......"> String[] customSchemes = { "http", "https" }; if (new UrlValidator(customSchemes).isValid(val)) { foundURL = true; } else { ret.invalidTags.add(attr + " " + val); val = ""; } } else if ("href".equals(attr) || "src".equals(attr)) { // <tag src/href="......"> skipped ret.invalidTags.add(tag + " " + attr + " " + val); continue; } else if (attr.matches("width|height")) { // <tag width/height="......"> if (!val.toLowerCase().matches("\\d+%|\\d+$")) { // test numeric values ret.invalidTags.add(tag + " " + attr + " " + val); continue; } } else if ("style".equals(attr)) { // <tag style="......"> // then test properties Matcher styles = stylePattern.matcher(val); String cleanStyle = ""; while (styles.find()) { String styleName = styles.group(1).toLowerCase(); String styleValue = styles.group(2); // suppress invalid styles values if (forbiddenStylePattern.matcher(styleValue).find()) { ret.invalidTags.add(tag + " " + attr + " " + styleValue); continue; } // check if valid url Matcher urlStyleMatcher = urlStylePattern.matcher(styleValue); if (urlStyleMatcher.find()) { String[] customSchemes = { "http", "https" }; String url = urlStyleMatcher.group(1); if (!new UrlValidator(customSchemes).isValid(url)) { ret.invalidTags.add(tag + " " + attr + " " + styleValue); continue; } } cleanStyle = cleanStyle + styleName + ":" + JSP.encode(styleValue) + ";"; } val = cleanStyle; } else if (attr.startsWith("on")) { // skip all javascript events ret.invalidTags.add(tag + " " + attr + " " + val); continue; } else { // by default encode all properies val = JSP.encode(val); } cleanToken = cleanToken + " " + attr + "=\"" + val + "\""; } cleanToken = cleanToken + ">"; isAcceptedToken = true; // for <img> and <a> if (tag.matches("a|img|embed") && !foundURL) { isAcceptedToken = false; cleanToken = ""; } token = cleanToken; // push the tag if require closure and it is accepted (otherwirse is encoded) if (isAcceptedToken && !(standAloneTags.matcher(tag).find() || selfClosed.matcher(tag).find())) openTags.push(tag); // -------------------------------------------------------------------------------- UNKNOWN TAG } else { ret.invalidTags.add(token); ret.val = ret.val + token; continue; } // -------------------------------------------------------------------------------- CLOSE TAG </tag> } else if (endMatcher.find()) { String tag = endMatcher.group(1).toLowerCase(); //is self closing if (selfClosed.matcher(tag).find()) { ret.invalidTags.add(token); continue; } if (forbiddenTags.matcher(tag).find()) { ret.invalidTags.add("/" + tag); continue; } if (!allowedTags.matcher(tag).find()) { ret.invalidTags.add(token); ret.val = ret.val + token; continue; } else { String cleanToken = ""; // check tag position in the stack int pos = openTags.search(tag); // if found on top ok for (int i = 1; i <= pos; i++) { //pop all elements before tag and close it String poppedTag = openTags.pop(); cleanToken = cleanToken + "</" + poppedTag + ">"; isAcceptedToken = true; } token = cleanToken; } } ret.val = ret.val + token; if (isAcceptedToken) { ret.html = ret.html + token; //ret.text = ret.text + " "; } else { String sanToken = JSP.htmlEncodeApexesAndTags(token); ret.html = ret.html + sanToken; ret.text = ret.text + JSP.htmlEncodeApexesAndTags(JSP.removeLineFeed(token)); } } // must close remaining tags while (openTags.size() > 0) { //pop all elements before tag and close it String poppedTag = openTags.pop(); ret.html = ret.html + "</" + poppedTag + ">"; ret.val = ret.val + "</" + poppedTag + ">"; } //set boolean value ret.isValid = ret.invalidTags.size() == 0; return ret; }
From source file:org.mitre.scap.xccdf.XCCDFInterpreter.java
private void resolveItem(final ItemType item, Stack<ItemType> visitedItems) throws CircularReferenceException, ExtensionScopeException, Exception { /**// ww w .jav a 2 s.c o m * Loading.Resolve.Items (From the XCCDF Specification) * For each Item in the Benchmark that has an extends property, resolve it by using the following steps: * (1) If the Item is Group, resolve all the enclosed Items * (2) Resolve the extended Item * (3) Prepend the property sequence from the extended Item to the extending Item * (4) If the Item is a Group, assign values for the id properties of Items copied from the extended Group * (5) Remove duplicate properties and apply property overrides * (6) Remove the extends property. * * If any Items extends property identifier does not match the identifier of a visible Item of the same type, * then Loading fails. If the directed graph formed by the extends properties includes a loop, then Loading fails. * Otherwise, go to the next step: Loading.Resolve.Profiles. * * * Because all items are contained within the @itemMap member, we don't need to drop into Groups: that work has * already been done. **/ if (item.isSetExtends()) { if (isVerboseOutput()) { System.out.println("** resolving item extension for " + item.getClass().getCanonicalName() + ": " + item.getId()); } int position = visitedItems.search(item); if (position != -1) { CircularReferenceException e = new CircularReferenceException( "circular reference via profile extension"); // Cast to List to allow the type to be cast to List<Identifiable> List<ItemType> visited = visitedItems.subList(visitedItems.size() - position, visitedItems.size()); List<Identifiable> refList = new ArrayList<Identifiable>(visited.size()); for (ItemType i : visited) { refList.add(new ItemIdentifiableAdapter(i)); } e.setReferenceList(refList); throw (e); } final ItemType extended = this.lookupExtendedItem(item); if (extended == null) throw new ExtensionScopeException("Unable to locate extending item: Possibly out of scope"); visitedItems.push(item); resolveItem(extended, visitedItems); visitedItems.pop(); if (this.isVerboseOutput()) { System.out.println("** resolveItem(): " + item.getId() + " extends " + extended.getId()); } ItemPropertyExtensionResolver propertyResolver = null; if (item instanceof GroupType) { propertyResolver = new GroupPropertyExtensionResolver((GroupType) item, (GroupType) extended); } else if (item instanceof RuleType) { propertyResolver = new RulePropertyExtensionResolver((RuleType) item, (RuleType) extended); } else if (item instanceof ValueType) { propertyResolver = new ValuePropertyExtensionResolver((ValueType) item, (ValueType) extended); } else throw new Exception("Cannot resolve properties for object which does not extend ItemType"); propertyResolver.resolve(); item.unsetExtends(); } }
From source file:org.mitre.scap.xccdf.XCCDFInterpreter.java
protected void resolveProfile(final ProfileType profile, final Stack<ProfileType> visitedProfiles) throws CircularReferenceException { /*//from w w w . j av a 2 s . co m * 3b) Loading.Resolve.Profiles - For each Profile in the Benchmark that has * an extends property, resolve the set of properties in the extending Profile * by applying the following steps: * (1) resolve the extended Profile, * (2) prepend the property sequence from the extended Profile to that of * the extending Profile, * (3) remove all but the last instance of duplicate properties. * * If any Profile's extends property identifier does not match the identifier of * another Profile in the Benchmark, then Loading fails. If the directed graph * formed by the extends properties of Profiles includes a loop, then Loading * fails. Otherwise, go to Loading.Resolve.Abstract. */ // Once a profile is resolved the extends property is removed if (profile.isSetExtends()) { if (isVerboseOutput()) { System.out.println("** resolving profile extension for profile: " + profile.getId()); } // Check if the this Profile is on the visited stack int position = visitedProfiles.search(profile); if (position != -1) { // This profile is in the stack, throw an exception CircularReferenceException e = new CircularReferenceException( "circular reference via profile extension"); // Cast to List to allow the type to be cast to List<Identifiable> List<ProfileType> visited = visitedProfiles.subList(visitedProfiles.size() - position, visitedProfiles.size()); List<Identifiable> refList = new ArrayList<Identifiable>(visited.size()); for (ProfileType p : visited) { refList.add(new ProfileIdentifiableAdapter(p)); } e.setReferenceList(refList); throw (e); } final ProfileType extendedProfile = lookupProfile(profile.getExtends()); // Add this profile to the visited list to look for loops visitedProfiles.push(profile); // Resolve the extended profile resolveProfile(extendedProfile, visitedProfiles); // Pop this profile visitedProfiles.pop(); /* * Handle the extension * * There are five different inheritance processing models for Item * and Profile properties. * None the property value or values are not inherited. * * NOTE: These properties cannot be inherited at all; they * must be given explicitly * * Prepend the property values are inherited from the * extended object, but values on the extending object * come first, and inherited values follow. * * Append the property values are inherited from the extended * object; additional values may be defined on the * extending object. * * NOTE: Additional rules may apply during Benchmark * processing, tailoring, or report generation * * Profile Specific Actions: * - The set of platform, reference, and selector * properties of the extended Profile are prepended to * the list of properties of the extending Profile. * Inheritance of title, description, and reference * properties are handled in the same way as for Item * objects. * * Replace the property value is inherited; a property value * explicitly defined on the extending object replaces an * inherited value. * * NOTE: For the check property, checks from different * systems are considered different properties * * Override the property values are inherited from the * extended object; additional values may be defined on the * extending object. An additional value can override * (replace) an inherited value, if explicitly tagged as * 'override'. * * NOTE: For properties that have a locale (xml:lang * specified), values with different locales are considered * to be different properties */ // Attribute: id // Operation: None // Attribute: prohibitChanges, optional, default=false // Operation: Replace if (extendedProfile.isSetProhibitChanges() && !profile.isSetProhibitChanges()) { profile.setProhibitChanges(extendedProfile.getProhibitChanges()); } // Attribute: abstract // Operation: None // Attribute: note-tag, optional // Operation: Replace if (extendedProfile.isSetNoteTag() && !profile.isSetNoteTag()) { profile.setNoteTag(extendedProfile.getNoteTag()); } // Attribute: extends // Operation: None // Attribute: xml:base // Operation: ???None // Attribute: Id // Operation: None??? // Element: status // Operation: None // Element: version, optional // Operation: Replace if (extendedProfile.isSetVersion() && !profile.isSetVersion()) { profile.setVersion((VersionType) extendedProfile.getVersion().copy()); } // Element: title // Operation: Override PropertyExtensionResolver.getTextWithSubTypeResolver().resolve(profile.getTitleList(), extendedProfile.getTitleList(), PropertyExtensionResolver.Action.OVERRIDE); // Element: description // Operation: Override PropertyExtensionResolver.getHtmlTextWithSubTypeResolver().resolve(profile.getDescriptionList(), extendedProfile.getDescriptionList(), PropertyExtensionResolver.Action.OVERRIDE); // Element: reference // Operation: ???Override (What is the key for the override?) PropertyExtensionResolver.getReferenceTypeResolver().resolve(profile.getReferenceList(), extendedProfile.getReferenceList(), PropertyExtensionResolver.Action.OVERRIDE); // Element: platform // Operation: ???Override (Why is this an override?) PropertyExtensionResolver.getURIIdRefTypeResolver().resolve(profile.getPlatformList(), extendedProfile.getPlatformList(), PropertyExtensionResolver.Action.OVERRIDE); // Element: select, set-value, refine-value and refine-rule new ProfileSelectorResolver(profile, extendedProfile).resolve(); // Element: signature // Operation: None // Remove the extends property profile.unsetExtends(); } }