VelocityImpl.java [src/csip] Revision:   Date:
/*
 * $Id$
 *
 * This file is part of the Cloud Services Integration Platform (CSIP),
 * a Model-as-a-Service framework, API and application suite.
 *
 * 2012-2022, Olaf David and others, OMSLab, Colorado State University.
 *
 * OMSLab licenses this file to you under the MIT license.
 * See the LICENSE file in the project root for more information.
 */
package csip;

import csip.api.server.Velocity;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

/**
 * COSU support for services.
 *
 * @author od
 */
class VelocityImpl implements Velocity {

  private static VelocityEngine ve;


  private static synchronized VelocityEngine ve() {
    if (ve == null) {
      ve = new VelocityEngine();
      ve.setProperty("file.resource.loader.class",
          ClasspathResourceLoader.class.getName());
      ve.init();
    }
    return ve;
  }


  @Override
  public void merge(String tmpl, File out) throws IOException {
    merge(tmpl, out, null);
  }


  @Override
  public void merge(String tmpl, File out, Map<String, Object> properties) throws IOException {
    VelocityContext context = new VelocityContext();
    if (properties != null)
      for (Map.Entry<String, Object> entry : properties.entrySet()) {
        context.put(entry.getKey(), entry.getValue());
      }

    try (FileWriter w = new FileWriter(out)) {
      ve().getTemplate(tmpl, "UTF-8").merge(context, w);
    }
  }

}