001    /**
002     * Copyright (c) 2000-2013 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.Map;
023    import java.util.regex.Matcher;
024    import java.util.regex.Pattern;
025    
026    /**
027     * @author Brian Wing Shun Chan
028     */
029    public class RegexTransformerListener extends BaseTransformerListener {
030    
031            @Override
032            public String onOutput(
033                    String output, String languageId, Map<String, String> tokens) {
034    
035                    if (_log.isDebugEnabled()) {
036                            _log.debug("onOutput");
037                    }
038    
039                    return replace(output);
040            }
041    
042            @Override
043            public String onScript(
044                    String script, String xml, String languageId,
045                    Map<String, String> tokens) {
046    
047                    if (_log.isDebugEnabled()) {
048                            _log.debug("onScript");
049                    }
050    
051                    return replace(script);
052            }
053    
054            protected String replace(String s) {
055                    if (s == null) {
056                            return s;
057                    }
058    
059                    List<Pattern> patterns = RegexTransformerUtil.getPatterns();
060                    List<String> replacements = RegexTransformerUtil.getReplacements();
061    
062                    for (int i = 0; i < patterns.size(); i++) {
063                            Pattern pattern = patterns.get(i);
064                            String replacement = replacements.get(i);
065    
066                            Matcher matcher = pattern.matcher(s);
067    
068                            s = matcher.replaceAll(replacement);
069                    }
070    
071                    return s;
072            }
073    
074            private static Log _log = LogFactoryUtil.getLog(
075                    RegexTransformerListener.class);
076    
077    }