/** * Set attribute with given key, value pair. Figures out a quote character to use if necessary. * * @param key The name of the attribute. * @param value The value of the attribute. */ public void setAttribute(String key, String value) { char ch; boolean needed; boolean singleq; boolean doubleq; String ref; StringBuffer buffer; char quote; Attribute attribute; // first determine if there's whitespace in the value // and while we'return at it find a suitable quote character needed = false; singleq = true; doubleq = true; if (null != value) for (int i = 0; i < value.length(); i++) { ch = value.charAt(i); if (Character.isWhitespace(ch)) needed = true; else if ('\'' == ch) singleq = false; else if ('"' == ch) doubleq = false; } // now apply quoting if (needed) { if (doubleq) quote = '"'; else if (singleq) quote = '\''; else { // uh-oh, we need to convert some quotes into character references // convert all double quotes into " quote = '"'; ref = """; // Translate.encode (quote); // JDK 1.4: value = value.replaceAll ("\"", ref); buffer = new StringBuffer(value.length() * 5); for (int i = 0; i < value.length(); i++) { ch = value.charAt(i); if (quote == ch) buffer.append(ref); else buffer.append(ch); } value = buffer.toString(); } } else quote = 0; attribute = getAttributeEx(key); if (null != attribute) { // see if we can splice it in rather than replace it attribute.setValue(value); if (0 != quote) attribute.setQuote(quote); } else setAttribute(key, value, quote); }
/** * Given a tag, check its attributes, removing those unwanted or not secure * * @param tag The tag to analyze * @param checkIfAttributeIsWelcome true if the attribute name should be matched against the list * of welcome attributes, set in the main configuration file. */ private void checkAndValidateAttributes(Tag tag, boolean checkIfAttributeIsWelcome) { Vector<Attribute> newAttributes = new Vector<Attribute>(); for (Iterator<?> iter = tag.getAttributesEx().iterator(); iter.hasNext(); ) { Attribute a = (Attribute) iter.next(); String name = a.getName(); if (name == null) { newAttributes.add(a); } else { name = name.toUpperCase(); if (a.getValue() == null) { newAttributes.add(a); continue; } String value = a.getValue().toLowerCase(); if (checkIfAttributeIsWelcome && !this.isAttributeWelcome(name)) { continue; } if (!this.isAttributeSafe(name, value)) { continue; } if (a.getValue().indexOf("&#") > -1) { a.setValue(a.getValue().replaceAll("&#", "&#")); } newAttributes.add(a); } } tag.setAttributesEx(newAttributes); }