Search in sources :

Example 96 with Template

use of org.apache.velocity.Template in project hale by halestudio.

the class HtmlMappingExporter method execute.

@Override
protected IOReport execute(ProgressIndicator progress, IOReporter reporter) throws IOProviderConfigurationException, IOException {
    this.reporter = reporter;
    context = new VelocityContext();
    cellIds = new Identifiers<Cell>(Cell.class, false);
    alignment = getAlignment();
    // $NON-NLS-1$
    URL headlinePath = this.getClass().getResource("bg-headline.png");
    // $NON-NLS-1$
    URL cssPath = this.getClass().getResource("style.css");
    // $NON-NLS-1$
    URL linkPath = this.getClass().getResource("int_link.png");
    // $NON-NLS-1$
    URL tooltipIcon = this.getClass().getResource("tooltip.gif");
    final String filesSubDir = FilenameUtils.removeExtension(FilenameUtils.getName(getTarget().getLocation().getPath())) + // $NON-NLS-1$
    "_files";
    final File filesDir = new File(FilenameUtils.getFullPath(getTarget().getLocation().getPath()), filesSubDir);
    filesDir.mkdirs();
    context.put(FILE_DIRECTORY, filesSubDir);
    try {
        init();
    } catch (Exception e) {
        return reportError(reporter, "Initializing error", e);
    }
    File cssOutputFile = new File(filesDir, "style.css");
    FileUtils.copyFile(getInputFile(cssPath), cssOutputFile);
    // create headline picture
    // $NON-NLS-1$
    File headlineOutputFile = new File(filesDir, "bg-headline.png");
    FileUtils.copyFile(getInputFile(headlinePath), headlineOutputFile);
    // $NON-NLS-1$
    File linkOutputFile = new File(filesDir, "int_link.png");
    FileUtils.copyFile(getInputFile(linkPath), linkOutputFile);
    // $NON-NLS-1$
    File tooltipIconFile = new File(filesDir, "tooltip.png");
    FileUtils.copyFile(getInputFile(tooltipIcon), tooltipIconFile);
    File htmlExportFile = new File(getTarget().getLocation().getPath());
    if (projectInfo != null) {
        Date date = new Date();
        DateFormat dfm = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
        // associate variables with information data
        String exportDate = dfm.format(date);
        context.put(EXPORT_DATE, exportDate);
        if (projectInfo.getCreated() != null) {
            String created = dfm.format(projectInfo.getCreated());
            context.put(CREATED_DATE, created);
        }
        context.put(PROJECT_INFO, projectInfo);
    }
    if (alignment != null) {
        Collection<TypeCellInfo> typeCellInfos = new ArrayList<TypeCellInfo>();
        Collection<? extends Cell> cells = alignment.getTypeCells();
        Iterator<? extends Cell> it = cells.iterator();
        while (it.hasNext()) {
            final Cell cell = it.next();
            // this is the collection of type cell info
            TypeCellInfo typeCellInfo = new TypeCellInfo(cell, alignment, cellIds, filesSubDir);
            typeCellInfos.add(typeCellInfo);
        }
        // put the full collection of type cell info to the context (for the
        // template)
        context.put(TYPE_CELL_INFOS, typeCellInfos);
        createImages(filesDir);
    }
    context.put(TOOLTIP, getParameter(TOOLTIP).as(boolean.class));
    Template template;
    try {
        template = velocityEngine.getTemplate(templateFile.getName(), "UTF-8");
    } catch (Exception e) {
        return reportError(reporter, "Could not load template", e);
    }
    FileWriter fileWriter = new FileWriter(htmlExportFile);
    template.merge(context, fileWriter);
    fileWriter.close();
    reporter.setSuccess(true);
    return reporter;
}
Also used : VelocityContext(org.apache.velocity.VelocityContext) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) URL(java.net.URL) IOProviderConfigurationException(eu.esdihumboldt.hale.common.core.io.IOProviderConfigurationException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) Date(java.util.Date) Template(org.apache.velocity.Template) DateFormat(java.text.DateFormat) Cell(eu.esdihumboldt.hale.common.align.model.Cell) File(java.io.File)

Example 97 with Template

use of org.apache.velocity.Template in project hale by halestudio.

the class XsltGenerator method write.

/**
 * Generate the XSLT transformation and write it to the given target.
 *
 * @param target the target output supplier
 * @return the report
 * @throws Exception if a unrecoverable error occurs during the process
 */
public IOReport write(LocatableOutputSupplier<? extends OutputStream> target) throws Exception {
    Template root = ve.getTemplate(Templates.ROOT, "UTF-8");
    VelocityContext context = XslTransformationUtil.createStrictVelocityContext();
    // project info
    context.put("info", ProjectXslInfo.getInfo(projectInfo));
    // collects IDs of type cells
    Set<String> typeIds = new HashSet<String>();
    // type cells
    for (Cell typeCell : alignment.getTypeCells()) {
        if (typeCell.getTransformationMode() != TransformationMode.disabled) {
            // ignore disabled cells
            Entity targetEntity = CellUtil.getFirstEntity(typeCell.getTarget());
            if (targetEntity != null) {
                // assign identifiers for type transformations
                String targetName = targetEntity.getDefinition().getDefinition().getName().getLocalPart();
                String id = cellIdentifiers.getId(typeCell, targetName);
                typeIds.add(id);
            } else {
                reporter.warn(new IOMessageImpl("Ignoring type relation without target type", null));
            }
        }
    }
    // collects IDs of type cells mapped to target element names
    Map<String, QName> targetElements = new HashMap<String, QName>();
    // container
    File container = new File(workDir, "container.xsl");
    progress.setCurrentTask("Generating container");
    generateContainer(typeIds, container, targetElements);
    Set<String> passiveCellIds = new HashSet<String>(typeIds);
    progress.setCurrentTask("Generate type transformations");
    // all active cells templates
    for (Entry<String, QName> entry : targetElements.entrySet()) {
        // generate XSL fragments for type transformations
        String id = entry.getKey();
        QName elementName = entry.getValue();
        Cell typeCell = cellIdentifiers.getObject(id);
        // this is not a passive cell
        passiveCellIds.remove(id);
        XmlElement targetElement = targetSchema.getElements().get(elementName);
        String filename = "_" + id + ".xsl";
        File file = new File(workDir, filename);
        includes.add(filename);
        generateTypeTransformation(id, targetElement, typeCell, file);
    }
    // all passive cell templates
    for (String passiveId : passiveCellIds) {
        Cell typeCell = cellIdentifiers.getObject(passiveId);
        String filename = "_" + passiveId + ".xsl";
        File file = new File(workDir, filename);
        includes.add(filename);
        // XXX dummy target element
        XmlElement targetElement = new XmlElement(new QName(NS_XSL_DEFINITIONS, "dummy"), null, null);
        generateTypeTransformation(passiveId, targetElement, typeCell, file);
        // for passive cells no variables should be created
        typeIds.remove(passiveId);
    }
    // namespaces that occur additionally to the fixed namespaces
    Map<String, String> additionalNamespaces = new HashMap<String, String>(prefixes.asMap());
    for (String fixedPrefix : FIXED_PREFIXES.keySet()) {
        additionalNamespaces.remove(fixedPrefix);
    }
    context.put("additionalNamespaces", additionalNamespaces);
    // types cells
    /*
		 * The type identifiers are used as variable name to store the result of
		 * the equally named template.
		 */
    context.put("targets", typeIds);
    // includes
    // TODO check if files to include are actually there?
    context.put("includes", includes);
    OutputStream out = target.getOutput();
    XMLPrettyPrinter printer = new XMLPrettyPrinter(out);
    Future<?> ready = printer.start();
    Writer writer = new OutputStreamWriter(printer, "UTF-8");
    try {
        root.merge(context, writer);
        writer.flush();
    } finally {
        writer.close();
        ready.get();
        out.close();
    }
    reporter.setSuccess(reporter.getErrors().isEmpty());
    return reporter;
}
Also used : Entity(eu.esdihumboldt.hale.common.align.model.Entity) HashMap(java.util.HashMap) VelocityContext(org.apache.velocity.VelocityContext) QName(javax.xml.namespace.QName) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) IOMessageImpl(eu.esdihumboldt.hale.common.core.io.report.impl.IOMessageImpl) Template(org.apache.velocity.Template) XmlElement(eu.esdihumboldt.hale.io.xsd.model.XmlElement) OutputStreamWriter(java.io.OutputStreamWriter) Cell(eu.esdihumboldt.hale.common.align.model.Cell) File(java.io.File) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 98 with Template

use of org.apache.velocity.Template in project hale by halestudio.

the class AbstractVelocityXslTypeTransformation method generateTemplate.

@Override
public void generateTemplate(String templateName, XmlElement targetElement, Cell typeCell, LocatableOutputSupplier<? extends OutputStream> out) throws TransformationException {
    // load default template
    Template template = loadTemplate();
    // create velocity context
    VelocityContext context = XslTransformationUtil.createStrictVelocityContext();
    // set default parameters
    context.put(CONTEXT_PARAM_TEMPLATE_NAME, templateName);
    context.put(CONTEXT_PARAM_TARGET_ELEMENT, context().getNamespaceContext().getPrefix(targetElement.getName().getNamespaceURI()) + ":" + targetElement.getName().getLocalPart());
    context.put(CONTEXT_PARAM_COMMENT, CellXslInfo.getInfo(typeCell));
    // custom context configuration
    configureTemplate(context, typeCell);
    // write template file
    writeTemplate(template, context, out);
}
Also used : VelocityContext(org.apache.velocity.VelocityContext) Template(org.apache.velocity.Template)

Example 99 with Template

use of org.apache.velocity.Template in project kie-wb-common by kiegroup.

the class GenerationEngine method generateSubTemplateString.

// TODO We could dispense with the use of templates alltogether
public String generateSubTemplateString(GenerationContext generationContext, String template) throws Exception {
    StringWriter writer = new StringWriter();
    // This is necessary to cover possible included sub-templates
    generationContext.setCurrentOutput(writer);
    // read the template to use
    String templatePath = null;
    try {
        templatePath = getFullVelocityPath(generationContext.getTemplatesPath(), template);
        Template t = velocityEngine.getTemplate(templatePath);
        t.merge(generationContext.getVelocityContext(), writer);
    } catch (Exception e) {
        logger.error("An error was produced during template adf: template: " + template + ", templatePath: " + templatePath, e);
    }
    return writer.toString();
}
Also used : StringWriter(java.io.StringWriter) Template(org.apache.velocity.Template)

Example 100 with Template

use of org.apache.velocity.Template in project kie-wb-common by kiegroup.

the class GenerationEngine method generate.

/**
 * Runs the code adf.
 *
 * @param generationContext Context information for the adf.
 *
 * @throws Exception
 */
public void generate(GenerationContext generationContext) throws Exception {
    VelocityContext context = buildContext(generationContext);
    String templatesPath = generationContext.getTemplatesPath();
    String initialTemplate = generationContext.getInitialTemplate();
    if (logger.isDebugEnabled()) {
        logger.debug("Starting code adf with templatesPath: " + templatesPath + ", initialTemplate: " + initialTemplate);
    }
    // Always start by the initial template
    String templatePath = getFullVelocityPath(templatesPath, initialTemplate);
    if (logger.isDebugEnabled())
        logger.debug("Initial templatePath: " + templatePath);
    StringWriter writer = new StringWriter();
    Template t = velocityEngine.getTemplate(templatePath);
    t.merge(context, writer);
}
Also used : StringWriter(java.io.StringWriter) VelocityContext(org.apache.velocity.VelocityContext) Template(org.apache.velocity.Template)

Aggregations

Template (org.apache.velocity.Template)160 VelocityContext (org.apache.velocity.VelocityContext)118 StringWriter (java.io.StringWriter)76 VelocityEngine (org.apache.velocity.app.VelocityEngine)39 Test (org.junit.Test)33 File (java.io.File)21 IOException (java.io.IOException)19 ResourceNotFoundException (org.apache.velocity.exception.ResourceNotFoundException)17 Writer (java.io.Writer)14 FileWriter (java.io.FileWriter)12 ClasspathResourceLoader (org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader)12 ParseErrorException (org.apache.velocity.exception.ParseErrorException)11 MethodInvocationException (org.apache.velocity.exception.MethodInvocationException)9 APITemplateException (org.wso2.carbon.apimgt.impl.template.APITemplateException)9 FileOutputStream (java.io.FileOutputStream)8 PrintWriter (java.io.PrintWriter)8 Map (java.util.Map)8 Properties (java.util.Properties)8 VelocityException (org.apache.velocity.exception.VelocityException)7 OutputStreamWriter (java.io.OutputStreamWriter)6