List of usage examples for java.util Stack Stack
public Stack()
From source file:com.tmh.web.filter.xss.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; } // STYLE SCRIPT style=xss:expression else if (styleScriptPattern.matcher(token).find()) { ret.val = ret.val + token; ret.invalidTags.add(token);// ww w. j a v a 2s .co m 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; } } 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: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. *//*ww w . ja va 2 s. c om*/ 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.bluepowermod.part.tube.TubeLogic.java
public void clearNodeCaches() { List<PneumaticTube> clearedTubes = new ArrayList<PneumaticTube>(); Stack<PneumaticTube> todoTubes = new Stack<PneumaticTube>(); clearNodeCache();//from w ww . j ava 2 s. c o m boolean firstRun = true; todoTubes.push(tube); while (!todoTubes.isEmpty()) { PneumaticTube tube = todoTubes.pop(); if (tube.getParent() != null && tube.getWorld() != null) { for (ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { PneumaticTube neighbor = tube.getPartCache(d); if (neighbor != null) { if (!clearedTubes.contains(neighbor)) { neighbor.getLogic().clearNodeCache(); clearedTubes.add(neighbor); if (firstRun || !neighbor.isCrossOver) todoTubes.push(neighbor); } } } } firstRun = false; } }
From source file:org.bpmscript.web.view.JavascriptView.java
/** * @see org.springframework.web.servlet.view.AbstractView#renderMergedOutputModel(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *//*from w w w. ja v a 2 s . co m*/ @SuppressWarnings("unchecked") @Override protected void renderMergedTemplateModel(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { Locale locale = RequestContextUtils.getLocale(request); Context cx = new ContextFactory().enterContext(); try { // create scripting environment (i.e. load everything) ScriptableObject scope = new Global(cx); cx.putThreadLocal(Global.LIBRARY_ASSOCIATION_QUEUE, libraryAssociationQueue); ScriptableObject.putProperty(scope, "log", Context.javaToJS(log, scope)); ScriptableObject.putProperty(scope, "request", Context.javaToJS(request, scope)); ScriptableObject.putProperty(scope, "response", Context.javaToJS(response, scope)); ScriptableObject.putProperty(scope, "base", Context.javaToJS(request.getContextPath(), scope)); ScriptableObject.putProperty(scope, "locale", Context.javaToJS(locale, scope)); Set<Map.Entry> entrySet = model.entrySet(); for (Map.Entry<String, Object> entry : entrySet) { ScriptableObject.putProperty(scope, entry.getKey(), mapToJsConverter.convertObject(scope, entry.getValue())); } Stack<String> sourceStack = new Stack<String>(); sourceStack.push(configResource); cx.putThreadLocal(Global.SOURCE_STACK, sourceStack); if (libraryAssociationQueue != null) { cx.putThreadLocal(Global.LIBRARY_ASSOCIATION_QUEUE, libraryAssociationQueue); } Script configScript = javascriptSourceCache.getScript( new String(StreamUtils .getBytes(getApplicationContext().getResource(configResource).getInputStream())), configResource); configScript.exec(cx, scope); sourceStack.pop(); sourceStack.push(getUrl()); Script script = javascriptSourceCache.getScript( new String( StreamUtils.getBytes(getApplicationContext().getResource(getUrl()).getInputStream())), getUrl()); Object result = script.exec(cx, scope); response.getWriter().write(result.toString()); // not sure if this is necessary response.getWriter().flush(); } finally { Context.exit(); } }
From source file:app.web.SeleniumPage.java
/** * This method is used internally only./*from w ww. ja va 2 s.c o m*/ * @param selenium seleniumBrowser * @param url the new current URL * @param actionStack the current action stack (history of past actions) */ private SeleniumPage(Selenium selenium, final String url, Stack<Action> actionStack) { this.selenium = selenium; this.actionStack = new Stack<Action>(); if (actionStack.isEmpty()) { this.actionStack.push(Action.open(url)); } else { this.actionStack.addAll(actionStack); // this.actionStack.push(Action.navigationNewPage("#target", url)); } currentPage = this; }
From source file:com.wavemaker.json.JSONMarshallerTest.java
public void testDoMarshal() throws Exception { JSONState jc = new JSONState(); StringWriter sw = new StringWriter(); TypeDefinition stringTypeDef = ReflectTypeUtils.getTypeDefinition(String.class, new ReflectTypeState(), false);/*from ww w. jav a 2 s . co m*/ TypeDefinition boolTypeDef = ReflectTypeUtils.getTypeDefinition(boolean.class, new ReflectTypeState(), false); JSONMarshaller.doMarshal(sw, "foo", "foo", jc, false, false, new Stack<Object>(), new Stack<String>(), new GenericFieldDefinition(stringTypeDef), 0, new ReflectTypeState(), false, 0, Logger.getLogger(JSONMarshaller.class)); assertEquals("\"foo\"", sw.toString()); sw = new StringWriter(); JSONMarshaller.doMarshal(sw, false, false, jc, false, false, new Stack<Object>(), new Stack<String>(), new GenericFieldDefinition(boolTypeDef), 0, new ReflectTypeState(), false, 0, Logger.getLogger(JSONMarshaller.class)); assertEquals("false", sw.toString()); sw = new StringWriter(); JSONMarshaller.doMarshal(sw, Boolean.TRUE, Boolean.TRUE, jc, false, false, new Stack<Object>(), new Stack<String>(), new GenericFieldDefinition(boolTypeDef), 0, new ReflectTypeState(), false, 0, Logger.getLogger(JSONMarshaller.class)); assertEquals("true", sw.toString()); }
From source file:com.sm.query.QueryListenerImpl.java
private void init() { if (!valueStack.isEmpty()) valueStack.empty();/*from w w w . j a va 2s . co m*/ if (!predicateStack.isEmpty()) predicateStack = new Stack<Predicate>(); }
From source file:com.altoukhov.svsync.fileviews.SmbFileSpace.java
@Override protected Snapshot scan(List<Pattern> filters) { try {/*from w ww . ja va2 s .co m*/ Map<String, FileSnapshot> files = new LinkedHashMap<>(); Set<String> dirs = new HashSet<>(); SmbFile root = new SmbFile(rootPath, auth); if (root.exists()) { Stack<SmbFile> stack = new Stack<>(); stack.push(root); dirs.add(""); while (!stack.isEmpty()) { SmbFile currentFolder = stack.pop(); for (final SmbFile file : listFiles(currentFolder)) { String path = file.getPath(); boolean isFile = isFile(file); boolean isDirectory = isDirectory(file); if (isFile && !isExcluded(path) && !isFiltered(toRelativePath(path), filters)) { FileSnapshot fileSnapshot = createFileSnapshot(file, path); files.put(fileSnapshot.getRelativePath(), fileSnapshot); } else if (isDirectory && !isExcluded(path) && !isFiltered(toRelativePath(path, true), filters)) { stack.push(file); dirs.add(toRelativePath(path)); System.out.println("Scanning " + path); } } } } Snapshot snapshot = new Snapshot(files, dirs); return snapshot; } catch (MalformedURLException | SmbException ex) { System.out.println("Failed to scan file space"); System.out.println(ex.getMessage()); System.out.println(ex); } return null; }
From source file:com.sencha.gxt.core.rebind.XTemplateParser.java
public TemplateModel parse(String template) throws UnableToCompleteException { // look for parameters or tags (Consider combining into one pattern) TemplateModel model = new TemplateModel(); Stack<ContainerTemplateChunk> stack = new Stack<ContainerTemplateChunk>(); stack.push(model);/*from ww w . j av a 2 s.com*/ Matcher m = NON_LITERAL_PATTERN.matcher(template); int lastMatchEnd = 0; while (m.find()) { // range of the current non-literal int begin = m.start(), end = m.end(); String currentMatch = template.substring(begin, end); // if there was content since the last non-literal chunk, track it if (lastMatchEnd < begin) { ContentChunk c = literal(template.substring(lastMatchEnd, begin)); stack.peek().children.add(c); log(c); } // move the last match pointer lastMatchEnd = end; // tpl tag starting Matcher tagOpenMatch = TAG_PATTERN.matcher(currentMatch); if (tagOpenMatch.matches()) { ControlChunk c = new ControlChunk(); c.controls = new HashMap<String, String>(); String attrs = tagOpenMatch.group(1).trim(); Matcher attrMatcher = ATTR_PATTERN.matcher(attrs); while (attrMatcher.find()) { // should be if or for String key = attrMatcher.group(1); // must be html-decoded String encodedValue = attrMatcher.group(2) == null ? attrMatcher.group(3) : attrMatcher.group(2); String value = StringEscapeUtils.unescapeXml(encodedValue); c.controls.put(key, value); } stack.peek().children.add(c); stack.push(c); log(c); continue; } // tpl tag ending Matcher tagCloseMatch = TAG_CLOSE_PATTERN.matcher(currentMatch); if (tagCloseMatch.matches()) { TemplateChunk c; try { c = stack.pop(); } catch (EmptyStackException ex) { logger.log(Type.ERROR, "Too many </tpl> tags"); throw new UnableToCompleteException(); } log(c); continue; } // reference (code) Matcher codeMatch = INVOKE_PATTERN.matcher(currentMatch); if (codeMatch.matches()) { ContentChunk c = new ContentChunk(); c.type = ContentType.CODE; c.content = codeMatch.group(1); stack.peek().children.add(c); log(c); continue; } // reference (param) Matcher paramMatch = PARAM_PATTERN.matcher(currentMatch); if (paramMatch.matches()) { ContentChunk c = new ContentChunk(); c.type = ContentType.REFERENCE; c.content = paramMatch.group(1); stack.peek().children.add(c); log(c); continue; } } // handle trailing content if (lastMatchEnd < template.length()) { ContentChunk c = literal(template.substring(lastMatchEnd)); log(c); model.children.add(c); } if (model != stack.peek()) { logger.log(Type.ERROR, "Too few </tpl> tags"); throw new UnableToCompleteException(); } return model; }
From source file:com.jetbrains.pluginUtils.xml.JDOMXIncluder.java
public static List<Content> resolve(@NotNull Element original, @Nullable String base) throws XIncludeException { Stack<String> bases = new Stack<String>(); if (base != null) bases.push(base);//from ww w .ja va 2 s .co m List<Content> result = resolve(original, bases); bases.pop(); return result; }