1 31 32 package org.opencms.util; 33 34 import org.opencms.main.CmsLog; 35 36 import org.apache.commons.logging.Log; 37 import org.apache.oro.text.PatternCache; 38 import org.apache.oro.text.PatternCacheFIFO; 39 import org.apache.oro.text.perl.MalformedPerl5PatternException; 40 import org.apache.oro.text.perl.Perl5Util; 41 import org.apache.oro.text.regex.MalformedPatternException; 42 43 87 public class CmsResourceTranslator { 88 89 90 private static final Log LOG = CmsLog.getLog(CmsResourceTranslator.class); 91 92 93 private boolean m_continueMatching; 94 95 96 private PatternCache m_perlPatternCache; 97 98 99 private Perl5Util m_perlUtil; 100 101 102 private String [] m_translations; 103 104 112 public CmsResourceTranslator(String [] translations, boolean continueMatching) { 113 114 super(); 115 m_translations = translations; 116 m_continueMatching = continueMatching; 117 m_perlPatternCache = new PatternCacheFIFO(m_translations.length + 1); 119 for (int i = 0; i < m_translations.length; i++) { 120 try { 121 m_perlPatternCache.addPattern(m_translations[i]); 122 } catch (MalformedPatternException e) { 123 LOG.error( 124 Messages.get().getBundle().key(Messages.LOG_MALFORMED_TRANSLATION_RULE_1, m_translations[i]), 125 e); 126 } 127 } 128 m_perlUtil = new Perl5Util(m_perlPatternCache); 130 if (LOG.isInfoEnabled()) { 131 LOG.info(Messages.get().getBundle().key( 132 Messages.LOG_NUM_TRANSLATION_RULES_INITIALIZED_1, 133 new Integer (translations.length))); 134 } 135 } 136 137 142 public String [] getTranslations() { 143 144 String [] copy = new String [m_translations.length]; 145 System.arraycopy(m_translations, 0, copy, 0, m_translations.length); 146 return copy; 147 } 148 149 157 public String translateResource(String resourceName) { 158 159 if (m_translations.length == 0) { 160 return resourceName; 162 } 163 if (resourceName == null) { 164 return null; 165 } 166 167 StringBuffer result; 168 String current = resourceName; 169 int size = current.length() * 2; 170 171 for (int i = 0; i < m_translations.length; i++) { 172 result = new StringBuffer (size); 173 try { 174 if (m_perlUtil.substitute(result, m_translations[i], current) != 0) { 175 176 if (m_continueMatching) { 177 current = result.toString(); 179 } else { 180 if (LOG.isDebugEnabled()) { 182 LOG.debug(Messages.get().getBundle().key( 183 Messages.LOG_TRANSLATION_MATCH_3, 184 new Integer (i), 185 resourceName, 186 result)); 187 } 188 return result.toString(); 190 } 191 } 192 } catch (MalformedPerl5PatternException e) { 193 LOG.error( 194 Messages.get().getBundle().key(Messages.LOG_MALFORMED_TRANSLATION_RULE_1, m_translations[i]), 195 e); 196 } 197 } 198 199 if (LOG.isDebugEnabled()) { 201 LOG.debug(Messages.get().getBundle().key(Messages.LOG_TRANSLATION_MATCH_2, resourceName, current)); 202 } 203 return current; 205 } 206 } | Popular Tags |