001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
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    }