001    /**
002     * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portlet.journal.util;
016    
017    import com.liferay.portal.kernel.log.Log;
018    import com.liferay.portal.kernel.log.LogFactoryUtil;
019    import com.liferay.portal.kernel.templateparser.BaseTransformerListener;
020    
021    import java.util.List;
022    import java.util.regex.Matcher;
023    import java.util.regex.Pattern;
024    
025    /**
026     * @author Brian Wing Shun Chan
027     */
028    public class RegexTransformerListener extends BaseTransformerListener {
029    
030            @Override
031            public String onOutput(String s) {
032                    if (_log.isDebugEnabled()) {
033                            _log.debug("onOutput");
034                    }
035    
036                    s = replace(s);
037    
038                    return s;
039            }
040    
041            @Override
042            public String onScript(String s) {
043                    if (_log.isDebugEnabled()) {
044                            _log.debug("onScript");
045                    }
046    
047                    s = replace(s);
048    
049                    return s;
050            }
051    
052            @Override
053            public String onXml(String s) {
054                    if (_log.isDebugEnabled()) {
055                            _log.debug("onXml");
056                    }
057    
058                    return s;
059            }
060    
061            protected String replace(String s) {
062                    if (s == null) {
063                            return s;
064                    }
065    
066                    List<Pattern> patterns = RegexTransformerUtil.getPatterns();
067                    List<String> replacements = RegexTransformerUtil.getReplacements();
068    
069                    for (int i = 0; i < patterns.size(); i++) {
070                            Pattern pattern = patterns.get(i);
071                            String replacement = replacements.get(i);
072    
073                            Matcher matcher = pattern.matcher(s);
074    
075                            s = matcher.replaceAll(replacement);
076                    }
077    
078                    return s;
079            }
080    
081            private static Log _log = LogFactoryUtil.getLog(
082                    RegexTransformerListener.class);
083    
084    }