Search in sources :

Example 6 with Resource

use of org.bndtools.templating.Resource in project bndtools by bndtools.

the class StringTemplateEngine method getTemplateParameters.

@Override
public Map<String, String> getTemplateParameters(ResourceMap inputs, IProgressMonitor monitor) throws Exception {
    Map<String, String> params = new HashMap<>();
    // Initialise the engine
    TemplateSettings settings = readSettings(inputs);
    STGroup stg = new STGroup(settings.leftDelim, settings.rightDelim);
    // Assemble a mapping properties file of outputPath=sourcePath
    String mappingTemplate = loadMappingTemplate(inputs, settings, stg);
    extractAttrs(compile(stg, "_mapping", new StringResource(mappingTemplate)), params);
    // Iterate the entries
    Properties contentProps = new Properties();
    contentProps.load(new StringReader(mappingTemplate));
    @SuppressWarnings("unchecked") Enumeration<String> contentEnum = (Enumeration<String>) contentProps.propertyNames();
    while (contentEnum.hasMoreElements()) {
        String outputPath = contentEnum.nextElement().trim();
        String sourcePath = contentProps.getProperty(outputPath);
        Resource source = inputs.get(sourcePath);
        if (source == null)
            throw new RuntimeException(String.format("Internal error in template engine: could not find input resource '%s'", sourcePath));
        if (settings.ignore == null || !settings.ignore.matches(sourcePath)) {
            if (source.getType() == ResourceType.File) {
                if (settings.preprocessMatch.matches(sourcePath)) {
                    extractAttrs(compile(stg, sourcePath, source), params);
                }
            }
        }
    }
    return params;
}
Also used : Enumeration(java.util.Enumeration) STGroup(org.stringtemplate.v4.STGroup) HashMap(java.util.HashMap) StringResource(org.bndtools.templating.StringResource) Resource(org.bndtools.templating.Resource) Properties(java.util.Properties) StringResource(org.bndtools.templating.StringResource) StringReader(java.io.StringReader)

Example 7 with Resource

use of org.bndtools.templating.Resource in project bndtools by bndtools.

the class StringTemplateEngine method generateOutputs.

@Override
public ResourceMap generateOutputs(ResourceMap inputs, Map<String, List<Object>> parameters, IProgressMonitor monitor) throws Exception {
    TemplateSettings settings = readSettings(inputs);
    STGroup stg = new STGroup(settings.leftDelim, settings.rightDelim);
    // Assemble a mapping properties file of outputPath=sourcePath
    String mappingTemplate = loadMappingTemplate(inputs, settings, stg);
    String renderedMapping = render(compile(stg, "_mapping", new StringResource(mappingTemplate)), parameters);
    Properties contentProps = new Properties();
    contentProps.load(new StringReader(renderedMapping));
    // Iterate the content entries
    ResourceMap outputs = new ResourceMap();
    @SuppressWarnings("unchecked") Enumeration<String> contentEnum = (Enumeration<String>) contentProps.propertyNames();
    while (contentEnum.hasMoreElements()) {
        String outputName = contentEnum.nextElement().trim();
        String sourceName = contentProps.getProperty(outputName, "").trim();
        Resource source = inputs.get(sourceName);
        if (source == null)
            throw new RuntimeException(String.format("Internal error in template engine: could not find input resource '%s'", sourceName));
        Resource output;
        if (settings.ignore == null || !settings.ignore.matches(sourceName)) {
            if (source.getType() == ResourceType.Folder) {
                output = source;
            } else if (settings.preprocessMatch.matches(sourceName)) {
                // This file is a candidate for preprocessing with ST
                String rendered = render(compile(stg, sourceName, source), parameters);
                output = new StringResource(rendered);
            } else {
                // This file should be directly copied
                output = source;
            }
            outputs.put(outputName, output);
        }
    }
    return outputs;
}
Also used : ResourceMap(org.bndtools.templating.ResourceMap) StringResource(org.bndtools.templating.StringResource) Enumeration(java.util.Enumeration) STGroup(org.stringtemplate.v4.STGroup) StringReader(java.io.StringReader) StringResource(org.bndtools.templating.StringResource) Resource(org.bndtools.templating.Resource) Properties(java.util.Properties)

Example 8 with Resource

use of org.bndtools.templating.Resource in project bndtools by bndtools.

the class NewBndProjectWizard method generateProjectContent.

@Override
protected void generateProjectContent(IProject project, IProgressMonitor monitor, Map<String, String> params) throws IOException {
    Map<String, List<Object>> templateParams = new HashMap<>();
    for (Entry<String, String> param : params.entrySet()) {
        templateParams.put(param.getKey(), Collections.<Object>singletonList(param.getValue()));
    }
    Template template = templatePage.getTemplate();
    try {
        ResourceMap outputs;
        if (template != null) {
            outputs = template.generateOutputs(templateParams);
        } else {
            // empty
            outputs = new ResourceMap();
        }
        SubMonitor progress = SubMonitor.convert(monitor, outputs.size() * 3);
        for (Entry<String, Resource> outputEntry : outputs.entries()) {
            String path = outputEntry.getKey();
            Resource resource = outputEntry.getValue();
            // Strip leading slashes from path
            while (path.startsWith("/")) path = path.substring(1);
            switch(resource.getType()) {
                case Folder:
                    if (!path.isEmpty()) {
                        IFolder folder = project.getFolder(path);
                        FileUtils.mkdirs(folder, progress.newChild(1, SubMonitor.SUPPRESS_ALL_LABELS));
                    }
                    break;
                case File:
                    IFile file = project.getFile(path);
                    FileUtils.mkdirs(file.getParent(), progress.newChild(1, SubMonitor.SUPPRESS_ALL_LABELS));
                    try (InputStream in = resource.getContent()) {
                        if (file.exists())
                            file.setContents(in, 0, progress.newChild(1, SubMonitor.SUPPRESS_NONE));
                        else
                            file.create(in, 0, progress.newChild(1, SubMonitor.SUPPRESS_NONE));
                        file.setCharset(resource.getTextEncoding(), progress.newChild(1));
                    }
                    break;
                default:
                    throw new IllegalArgumentException("Unknown resource type " + resource.getType());
            }
        }
    } catch (Exception e) {
        String message = MessageFormat.format("Error generating project contents from template \"{0}\": {1}", template != null ? template.getName() : "<null>", e.getMessage());
        throw new IOException(message);
    }
}
Also used : IFile(org.eclipse.core.resources.IFile) HashMap(java.util.HashMap) InputStream(java.io.InputStream) SubMonitor(org.eclipse.core.runtime.SubMonitor) StringResource(org.bndtools.templating.StringResource) Resource(org.bndtools.templating.Resource) IOException(java.io.IOException) IOException(java.io.IOException) BuiltInTemplate(org.bndtools.core.ui.wizards.shared.BuiltInTemplate) Template(org.bndtools.templating.Template) ResourceMap(org.bndtools.templating.ResourceMap) List(java.util.List) IFolder(org.eclipse.core.resources.IFolder)

Example 9 with Resource

use of org.bndtools.templating.Resource in project bndtools by bndtools.

the class BndRunFileWizard method getTemplateContents.

private InputStream getTemplateContents(String fileName) throws Exception {
    // Load properties
    Map<String, List<Object>> params = new HashMap<>();
    params.put(PROP_FILE_NAME, Collections.<Object>singletonList(fileName));
    params.put(PROP_FILE_BASE_NAME, Collections.<Object>singletonList(baseName(fileName)));
    IPath containerPath = mainPage.getContainerFullPath();
    if (containerPath != null) {
        IResource container = ResourcesPlugin.getWorkspace().getRoot().findMember(containerPath);
        if (container != null) {
            String projectName = container.getProject().getName();
            params.put(PROP_PROJECT_NAME, Collections.<Object>singletonList(projectName));
        }
    }
    Map<String, String> editedParams = paramsPage.getValues();
    for (Entry<String, String> editedParam : editedParams.entrySet()) {
        params.put(editedParam.getKey(), Collections.<Object>singletonList(editedParam.getValue()));
    }
    // Run the template processor
    Template template = templatePage.getTemplate();
    ResourceMap outputs;
    outputs = template.generateOutputs(params);
    Resource output = outputs.get(fileName);
    if (output == null) {
        throw new IllegalArgumentException(String.format("Template error: file '%s' not found in outputs. Available names: %s", fileName, outputs.getPaths()));
    }
    // Pull the generated content
    return output.getContent();
}
Also used : ResourceMap(org.bndtools.templating.ResourceMap) IPath(org.eclipse.core.runtime.IPath) HashMap(java.util.HashMap) StringResource(org.bndtools.templating.StringResource) Resource(org.bndtools.templating.Resource) IResource(org.eclipse.core.resources.IResource) List(java.util.List) IResource(org.eclipse.core.resources.IResource) BuiltInTemplate(org.bndtools.core.ui.wizards.shared.BuiltInTemplate) Template(org.bndtools.templating.Template)

Example 10 with Resource

use of org.bndtools.templating.Resource in project bndtools by bndtools.

the class ReposTemplateLoaderTest method testReferTemplateDefinitions.

public void testReferTemplateDefinitions() throws Exception {
    List<Template> templates = loader.findTemplates("test3", new ProgressMonitorReporter(new NullProgressMonitor(), "")).getValue();
    assertEquals(1, templates.size());
    Template template = templates.get(0);
    Map<String, List<Object>> parameters = new HashMap<>();
    parameters.put("name", Collections.<Object>singletonList("Homer Simpson"));
    ResourceMap outputs = template.generateOutputs(parameters);
    assertEquals(1, outputs.size());
    Iterator<Entry<String, Resource>> iter = outputs.entries().iterator();
    Entry<String, Resource> entry;
    entry = iter.next();
    assertEquals("example.html", entry.getKey());
    assertEquals("My name is <i>Homer Simpson</i>!", IO.collect(entry.getValue().getContent()));
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) ProgressMonitorReporter(org.bndtools.utils.progress.ProgressMonitorReporter) HashMap(java.util.HashMap) Resource(org.bndtools.templating.Resource) Template(org.bndtools.templating.Template) ResourceMap(org.bndtools.templating.ResourceMap) Entry(java.util.Map.Entry) List(java.util.List)

Aggregations

Resource (org.bndtools.templating.Resource)17 ResourceMap (org.bndtools.templating.ResourceMap)10 StringResource (org.bndtools.templating.StringResource)10 HashMap (java.util.HashMap)8 StringReader (java.io.StringReader)7 Properties (java.util.Properties)7 List (java.util.List)6 Template (org.bndtools.templating.Template)6 InputStreamReader (java.io.InputStreamReader)5 Entry (java.util.Map.Entry)5 ProgressMonitorReporter (org.bndtools.utils.progress.ProgressMonitorReporter)4 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)4 Reader (java.io.Reader)3 StringWriter (java.io.StringWriter)3 DigestInputStream (java.security.DigestInputStream)3 DefaultMustacheFactory (com.github.mustachejava.DefaultMustacheFactory)2 File (java.io.File)2 InputStream (java.io.InputStream)2 Enumeration (java.util.Enumeration)2 BuiltInTemplate (org.bndtools.core.ui.wizards.shared.BuiltInTemplate)2