Java tutorial
/** * Copyright (c) 2011 Zauber S.A. <http://www.zaubersoftware.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zaubersoftware.mule.module.jenkins.template.velocity; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.util.Map; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.UnhandledException; import org.apache.commons.lang.Validate; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.springframework.core.io.Resource; import com.zaubersoftware.mule.module.jenkins.template.Template; /** * Velocity template * * @author Juan F. Codagnone * @since Mar 27, 2011 */ public class VelocityTemplate implements Template { static { try { Velocity.init(); } catch (final Exception e) { throw new UnhandledException(e); } } private final String message; /** * Creates the VelocityTemplate. * */ public VelocityTemplate(final Resource content, final String charset) { Validate.notNull(content); Validate.notNull(charset); InputStream is = null; try { is = content.getInputStream(); final ByteArrayOutputStream os = new ByteArrayOutputStream(); IOUtils.copy(is, os); os.close(); message = os.toString(charset); } catch (final IOException e) { throw new UnhandledException(e); } finally { IOUtils.closeQuietly(is); } } @Override public final String render(final Map<String, ?> model) { final StringWriter writer = new StringWriter(); final VelocityContext context = new VelocityContext(model); try { Velocity.evaluate(context, writer, "message", new StringReader(message)); } catch (final Exception e) { throw new RuntimeException(e); } return writer.toString(); } }