Search in sources :

Example 1 with Template

use of io.quarkus.qute.Template in project camel-quarkus by apache.

the class QuteEndpoint method onExchange.

@Override
protected void onExchange(Exchange exchange) throws Exception {
    String path = getResourceUri();
    ObjectHelper.notNull(path, "resourceUri");
    if (allowTemplateFromHeader) {
        String newResourceUri = exchange.getIn().getHeader(QuteConstants.QUTE_RESOURCE_URI, String.class);
        if (newResourceUri != null) {
            exchange.getIn().removeHeader(QuteConstants.QUTE_RESOURCE_URI);
            log.debug("{} set to {} creating new endpoint to handle exchange", QuteConstants.QUTE_RESOURCE_URI, newResourceUri);
            QuteEndpoint newEndpoint = findOrCreateEndpoint(getEndpointUri(), newResourceUri);
            newEndpoint.onExchange(exchange);
            return;
        }
    }
    String content = null;
    if (allowTemplateFromHeader) {
        content = exchange.getIn().getHeader(QuteConstants.QUTE_TEMPLATE, String.class);
        if (content != null) {
            // remove the header to avoid it being propagated in the routing
            exchange.getIn().removeHeader(QuteConstants.QUTE_TEMPLATE);
        }
    }
    TemplateInstance instance = null;
    if (allowTemplateFromHeader) {
        instance = exchange.getIn().getHeader(QuteConstants.QUTE_TEMPLATE_INSTANCE, TemplateInstance.class);
    }
    if (instance != null) {
        // use template instance from header
        if (log.isDebugEnabled()) {
            log.debug("Qute template instance is from header {} for endpoint {}", QuteConstants.QUTE_TEMPLATE_INSTANCE, getEndpointUri());
        }
        exchange.getIn().removeHeader(QuteConstants.QUTE_TEMPLATE_INSTANCE);
    } else {
        Template template;
        Engine engine = getQuteEngine();
        if (content == null) {
            template = engine.getTemplate(path);
            if (template == null) {
                throw new TemplateException("Unable to parse Qute template from path: " + path);
            }
        } else {
            // This is the first time to parse the content
            template = engine.parse(content);
            if (template == null) {
                throw new TemplateException("Unable to parse Qute template");
            }
        }
        instance = template.instance();
    }
    ExchangeHelper.createVariableMap(exchange, isAllowContextMapAll()).forEach(instance::data);
    Map<String, Object> map = exchange.getIn().getHeader(QuteConstants.QUTE_TEMPLATE_DATA, Map.class);
    if (map != null) {
        map.forEach(instance::data);
    }
    exchange.getMessage().setBody(instance.render().trim());
}
Also used : TemplateException(io.quarkus.qute.TemplateException) Engine(io.quarkus.qute.Engine) TemplateInstance(io.quarkus.qute.TemplateInstance) Template(io.quarkus.qute.Template)

Example 2 with Template

use of io.quarkus.qute.Template in project jbang by jbangdev.

the class BaseBuilder method generatePom.

protected Path generatePom(File tmpJarDir) throws IOException {
    Template pomTemplate = TemplateEngine.instance().getTemplate("pom.qute.xml");
    Path pomPath = null;
    if (pomTemplate == null) {
        // ignore
        Util.warnMsg("Could not locate pom.xml template");
    } else {
        String baseName = Util.getBaseName(ss.getResourceRef().getFile().getName());
        String group = "group";
        String artifact = baseName;
        String version = "999-SNAPSHOT";
        if (ss.getGav().isPresent()) {
            MavenCoordinate coord = DependencyUtil.depIdToArtifact(DependencyUtil.gavWithVersion(ss.getGav().get()));
            group = coord.getGroupId();
            artifact = coord.getArtifactId();
            version = coord.getVersion();
        }
        String pomfile = pomTemplate.data("baseName", baseName).data("group", group).data("artifact", artifact).data("version", version).data("description", ss.getDescription().orElse("")).data("dependencies", ss.getClassPath().getArtifacts()).render();
        pomPath = new File(tmpJarDir, "META-INF/maven/" + group.replace(".", "/") + "/pom.xml").toPath();
        Files.createDirectories(pomPath.getParent());
        Util.writeString(pomPath, pomfile);
    }
    return pomPath;
}
Also used : Path(java.nio.file.Path) MavenCoordinate(org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenCoordinate) Template(io.quarkus.qute.Template)

Example 3 with Template

use of io.quarkus.qute.Template in project jbang by jbangdev.

the class Edit method renderTemplate.

private void renderTemplate(TemplateEngine engine, List<String> collectDependencies, String fullclassName, String baseName, List<String> resolvedDependencies, List<MavenRepo> repositories, String templateName, List<String> userParams, Path destination) throws IOException {
    Template template = engine.getTemplate(templateName);
    if (template == null)
        throw new ExitException(EXIT_INVALID_INPUT, "Could not locate template named: '" + templateName + "'");
    String result = template.data("repositories", repositories.stream().map(MavenRepo::getUrl).filter(s -> !"".equals(s))).data("dependencies", collectDependencies).data("gradledependencies", gradleify(collectDependencies)).data("baseName", baseName).data("fullClassName", fullclassName).data("classpath", resolvedDependencies.stream().filter(t -> !t.isEmpty()).collect(Collectors.toList())).data("userParams", String.join(" ", userParams)).data("cwd", System.getProperty("user.dir")).render();
    Util.writeString(destination, result);
}
Also used : java.util(java.util) MavenRepo(dev.jbang.dependencies.MavenRepo) System.out(java.lang.System.out) WatchKey(java.nio.file.WatchKey) dev.jbang.source(dev.jbang.source) StandardWatchEventKinds(java.nio.file.StandardWatchEventKinds) JitPackUtil(dev.jbang.dependencies.JitPackUtil) CP_SEPARATOR(dev.jbang.Settings.CP_SEPARATOR) Charset(java.nio.charset.Charset) EditorManager(dev.jbang.net.EditorManager) TemplateEngine(dev.jbang.util.TemplateEngine) Path(java.nio.file.Path) CommandLine(picocli.CommandLine) Util(dev.jbang.util.Util) Files(java.nio.file.Files) WatchEvent(java.nio.file.WatchEvent) DependencyUtil(dev.jbang.dependencies.DependencyUtil) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) Shell(dev.jbang.util.Util.Shell) File(java.io.File) WatchService(java.nio.file.WatchService) Template(io.quarkus.qute.Template) BaseBuilder.escapeOSArguments(dev.jbang.source.builders.BaseBuilder.escapeOSArguments) Settings(dev.jbang.Settings) Util.verboseMsg(dev.jbang.util.Util.verboseMsg) FileSystems(java.nio.file.FileSystems) Cache(dev.jbang.Cache) MavenRepo(dev.jbang.dependencies.MavenRepo) Template(io.quarkus.qute.Template)

Example 4 with Template

use of io.quarkus.qute.Template in project automatiko-engine by automatiko-io.

the class HumanTaskLifeCycleWithEmail method sendEmail.

private void sendEmail(WorkItem workItem) {
    HumanTaskWorkItem humanTask = (HumanTaskWorkItem) workItem;
    List<String> users = new ArrayList<>();
    if (humanTask.getActualOwner() != null) {
        users.add(humanTask.getActualOwner());
    }
    if (humanTask.getPotentialUsers() != null) {
        users.addAll(humanTask.getPotentialUsers());
    }
    Map<String, String> addresses = emailAddressResolver.resolve(users, humanTask.getPotentialGroups());
    if (addresses.isEmpty()) {
        return;
    }
    String subject = "New task has been assigned to you (" + humanTask.getTaskName() + ")";
    Template template = getTemplate(humanTask.getProcessInstance().getProcess(), humanTask);
    if (template == null) {
        template = engine.getTemplate(DEFAULT_TEMPLATE);
    }
    Mail[] emails = new Mail[addresses.size()];
    Map<String, Object> templateData = new HashMap<>();
    templateData.put("name", humanTask.getTaskName());
    templateData.put("description", humanTask.getTaskDescription());
    templateData.put("taskId", humanTask.getId());
    templateData.put("instanceId", humanTask.getProcessInstanceId());
    templateData.put("processId", humanTask.getProcessInstance().getProcessId());
    templateData.put("inputs", humanTask.getParameters());
    int count = 0;
    for (Entry<String, String> address : addresses.entrySet()) {
        String dedicatedTo = "";
        if (users.contains(address.getKey())) {
            dedicatedTo = address.getKey();
        }
        String parentProcessInstanceId = humanTask.getProcessInstance().getParentProcessInstanceId();
        if (parentProcessInstanceId != null && !parentProcessInstanceId.isEmpty()) {
            parentProcessInstanceId += ":";
        } else {
            parentProcessInstanceId = "";
        }
        String version = version(humanTask.getProcessInstance().getProcess().getVersion());
        String encoded = Base64.getEncoder().encodeToString((humanTask.getProcessInstance().getProcessId() + version + "|" + parentProcessInstanceId + humanTask.getProcessInstance().getId() + "|" + humanTask.getId() + "|" + dedicatedTo).getBytes(StandardCharsets.UTF_8));
        String link = serviceUrl + "/management/tasks/link/" + encoded;
        templateData.put("link", link);
        String body = template.instance().data(templateData).render();
        emails[count] = Mail.withHtml(address.getValue(), subject, body);
        count++;
    }
    // send emails asynchronously
    CompletableFuture.runAsync(() -> {
        for (String to : addresses.values()) {
            mailer.send(emails);
            LOGGER.debug("Email sent to {} with new assigned task {}", to, humanTask.getName());
        }
    });
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Template(io.quarkus.qute.Template) HumanTaskWorkItem(io.automatiko.engine.api.runtime.process.HumanTaskWorkItem) Mail(io.quarkus.mailer.Mail)

Example 5 with Template

use of io.quarkus.qute.Template in project automatiko-engine by automatiko-io.

the class SendEmailService method sendCorrelatedWithCC.

/**
 * Sends email to the given list of recipients and cc recipients with given subject and body that is created based on the
 * given template.
 * Optionally given attachments will be put on the message as well
 *
 * In case of error a <code>ServiceExecutionError</code> will be thrown with error code set to <code>sendEmailFailure</code>
 * so it can be used within workflow definition to handle it
 *
 * In case template cannot be found with given name a <code>ServiceExecutionError</code> will
 * be thrown with error code set to <code>emailTemplateNotFound</code>
 *
 * @param correlation correlation information to be attached to the message
 * @param tos comma separated list of recipients
 * @param ccs comma separated list of CC recipients
 * @param subject subject of the email
 * @param templateName name of the email template to be used to create the body of the email message
 * @param body body of the email
 * @param attachments optional attachments
 */
public void sendCorrelatedWithCC(String correlation, String tos, String ccs, String subject, String templateName, Object body, File<byte[]>... attachments) {
    Template template = getTemplate(templateName);
    try {
        Map<String, Object> templateData = new HashMap<>();
        templateData.put("body", body);
        String content = template.instance().data(templateData).render();
        for (String to : tos.split(",")) {
            Mail mail = Mail.withHtml(to, subject, content);
            for (String cc : ccs.split(",")) {
                mail.addCc(cc);
            }
            for (File<byte[]> attachment : attachments) {
                if (attachment == null) {
                    continue;
                }
                mail.addAttachment(attachment.name(), attachment.content(), attachment.type());
            }
            mail.addHeader("Message-ID", EmailUtils.messageIdWithCorrelation(correlation, host.orElse("localhost")));
            mailer.send(mail);
        }
    } catch (Exception e) {
        throw new ServiceExecutionError("sendEmailFailure", e.getMessage(), e);
    }
}
Also used : ServiceExecutionError(io.automatiko.engine.api.workflow.ServiceExecutionError) Mail(io.quarkus.mailer.Mail) HashMap(java.util.HashMap) Template(io.quarkus.qute.Template)

Aggregations

Template (io.quarkus.qute.Template)16 HashMap (java.util.HashMap)8 Mail (io.quarkus.mailer.Mail)7 ServiceExecutionError (io.automatiko.engine.api.workflow.ServiceExecutionError)6 TemplateInstance (io.quarkus.qute.TemplateInstance)4 Path (java.nio.file.Path)4 IOException (java.io.IOException)3 TemplateEngine (dev.jbang.util.TemplateEngine)2 Util (dev.jbang.util.Util)2 BufferedWriter (java.io.BufferedWriter)2 File (java.io.File)2 Files (java.nio.file.Files)2 Optional (java.util.Optional)2 Collectors (java.util.stream.Collectors)2 CommandLine (picocli.CommandLine)2 Cache (dev.jbang.Cache)1 Settings (dev.jbang.Settings)1 CP_SEPARATOR (dev.jbang.Settings.CP_SEPARATOR)1 TemplateProperty (dev.jbang.catalog.TemplateProperty)1 ExitException (dev.jbang.cli.ExitException)1