1 7 package uk.ac.roe.antigen.builder; 8 9 import java.util.logging.Level ; 10 11 12 import java.io.StringWriter ; 13 import java.util.Enumeration ; 14 import java.util.Hashtable ; 15 import java.util.Properties ; 16 import java.util.logging.Logger ; 17 18 import org.apache.velocity.Template; 19 import org.apache.velocity.VelocityContext; 20 import org.apache.velocity.app.Velocity; 21 import org.apache.velocity.exception.MethodInvocationException; 22 import org.apache.velocity.exception.ParseErrorException; 23 import org.apache.velocity.exception.ResourceNotFoundException; 24 import org.apache.velocity.runtime.RuntimeConstants; 25 import org.apache.velocity.runtime.RuntimeServices; 26 import org.apache.velocity.runtime.RuntimeSingleton; 27 import org.apache.velocity.runtime.log.LogSystem; 28 import org.apache.velocity.runtime.log.NullLogSystem; 29 30 36 public class MessageProcessor { 37 42 public static class VelocityLoggerWrapper implements LogSystem { 43 46 private final Logger logger = Logger.getLogger(VelocityLoggerWrapper.class.getName()); 47 48 51 public void init(RuntimeServices arg0) throws Exception { 52 } 54 55 58 public void logVelocityMessage(int arg0, String arg1) { 59 logger.fine(arg1); 60 61 } 62 } 63 66 private static final Logger logger = Logger.getLogger(MessageProcessor.class.getName()); 67 68 71 72 73 public static void main(String [] args) { 74 } 75 76 77 80 static { 81 logger.fine("Initialising Velocity Engine"); 82 Properties velocityConfig = new Properties (); 83 velocityConfig.put("resource.loader","class"); 84 velocityConfig.put("class.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); 85 velocityConfig.put(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, VelocityLoggerWrapper.class.getName()); 86 try { 87 Velocity.init(velocityConfig); 88 } catch (Exception e) { 89 e.printStackTrace(); 91 } 92 } 93 102 public static String processMessage(Hashtable properties, String messageTemplate) throws Exception , ResourceNotFoundException, ParseErrorException, MethodInvocationException { 103 if (messageTemplate!=null) { 104 VelocityContext context = new VelocityContext(); 105 106 Template template = Velocity.getTemplate(messageTemplate); 107 108 StringWriter sw = new StringWriter (); 109 110 Enumeration enumer = properties.keys(); 111 logger.fine("Properties available to Velocity:"); 112 while (enumer.hasMoreElements()) { 113 String key = (String ) enumer.nextElement(); 114 Object value = properties.get(key); 115 key = key.replace('.','_'); logger.fine(key + "="+value); 117 context.put(key, value); 118 } 119 template.merge( context, sw ); 120 121 122 return sw.toString(); 123 } else { 124 return null; 125 } 126 } 127 } 128 | Popular Tags |