001/* 002 * (C) Copyright 2006-2007 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Jean-Marc Orliaguet, Chalmers 018 * 019 * $Id$ 020 */ 021 022package org.nuxeo.theme.html.filters.standalone; 023 024import java.util.regex.Matcher; 025import java.util.regex.Pattern; 026 027import org.nuxeo.theme.rendering.RenderingInfo; 028import org.nuxeo.theme.rendering.StandaloneFilter; 029 030public final class XmlNamespaces extends StandaloneFilter { 031 032 static final Pattern tagsPattern = Pattern.compile("(.*?)<([^/@!<>].*?)>(.*)", Pattern.DOTALL); 033 034 static final String xmlnsAttrStr = "xmlns[^\"]+\"([^\"]+)\""; 035 036 static final String spaceXmlnsAttrStr = " " + xmlnsAttrStr; 037 038 static final Pattern xmlnsAttrPattern = Pattern.compile(xmlnsAttrStr, Pattern.DOTALL); 039 040 @Override 041 public RenderingInfo process(final RenderingInfo info, final boolean cache) { 042 String markup = info.getMarkup(); 043 044 final Matcher attrMatcher = xmlnsAttrPattern.matcher(markup); 045 if (!attrMatcher.find()) { 046 return info; 047 } 048 049 final StringBuilder s = new StringBuilder(); 050 do { 051 final String attr = attrMatcher.group(0); 052 if (s.indexOf(attr) < 0) { 053 s.append(' '); 054 s.append(attr); 055 } 056 } while (attrMatcher.find()); 057 058 // remove existing uid attributes, if any 059 markup = markup.replaceAll(spaceXmlnsAttrStr, ""); 060 061 final Matcher firstMatcher = tagsPattern.matcher(markup); 062 if (!firstMatcher.find()) { 063 return info; 064 } 065 066 // write the final markup 067 final String f = String.format("%s<%s%s>%s", firstMatcher.group(1), firstMatcher.group(2), s.toString(), 068 firstMatcher.group(3)); 069 070 info.setMarkup(f); 071 return info; 072 } 073 074}