Search in sources :

Example 96 with VelocityContext

use of org.apache.velocity.VelocityContext in project thingsboard by thingsboard.

the class SendMailAction method convert.

@Override
public Optional<RuleToPluginMsg> convert(RuleContext ctx, ToDeviceActorMsg toDeviceActorMsg, RuleProcessingMetaData metadata) {
    String sendFlag = configuration.getSendFlag();
    if (StringUtils.isEmpty(sendFlag) || (Boolean) metadata.get(sendFlag).orElse(Boolean.FALSE)) {
        VelocityContext context = VelocityUtils.createContext(metadata);
        SendMailActionMsg.SendMailActionMsgBuilder builder = SendMailActionMsg.builder();
        fromTemplate.ifPresent(t -> builder.from(VelocityUtils.merge(t, context)));
        toTemplate.ifPresent(t -> builder.to(VelocityUtils.merge(t, context)));
        ccTemplate.ifPresent(t -> builder.cc(VelocityUtils.merge(t, context)));
        bccTemplate.ifPresent(t -> builder.bcc(VelocityUtils.merge(t, context)));
        subjectTemplate.ifPresent(t -> builder.subject(VelocityUtils.merge(t, context)));
        bodyTemplate.ifPresent(t -> builder.body(VelocityUtils.merge(t, context)));
        return Optional.of(new SendMailRuleToPluginActionMsg(toDeviceActorMsg.getTenantId(), toDeviceActorMsg.getCustomerId(), toDeviceActorMsg.getDeviceId(), builder.build()));
    } else {
        return Optional.empty();
    }
}
Also used : VelocityContext(org.apache.velocity.VelocityContext)

Example 97 with VelocityContext

use of org.apache.velocity.VelocityContext in project thingsboard by thingsboard.

the class ServerSideRpcCallAction method convert.

@Override
public Optional<RuleToPluginMsg> convert(RuleContext ctx, ToDeviceActorMsg toDeviceActorMsg, RuleProcessingMetaData metadata) {
    String sendFlag = configuration.getSendFlag();
    if (StringUtils.isEmpty(sendFlag) || (Boolean) metadata.get(sendFlag).orElse(Boolean.FALSE)) {
        VelocityContext context = VelocityUtils.createContext(metadata);
        ServerSideRpcCallActionMsg.ServerSideRpcCallActionMsgBuilder builder = ServerSideRpcCallActionMsg.builder();
        deviceIdTemplate.ifPresent(t -> builder.deviceId(VelocityUtils.merge(t, context)));
        fromDeviceRelationTemplate.ifPresent(t -> builder.fromDeviceRelation(VelocityUtils.merge(t, context)));
        toDeviceRelationTemplate.ifPresent(t -> builder.toDeviceRelation(VelocityUtils.merge(t, context)));
        rpcCallMethodTemplate.ifPresent(t -> builder.rpcCallMethod(VelocityUtils.merge(t, context)));
        rpcCallBodyTemplate.ifPresent(t -> builder.rpcCallBody(VelocityUtils.merge(t, context)));
        builder.rpcCallTimeoutInSec(configuration.getRpcCallTimeoutInSec());
        return Optional.of(new ServerSideRpcCallRuleToPluginActionMsg(toDeviceActorMsg.getTenantId(), toDeviceActorMsg.getCustomerId(), toDeviceActorMsg.getDeviceId(), builder.build()));
    } else {
        return Optional.empty();
    }
}
Also used : VelocityContext(org.apache.velocity.VelocityContext)

Example 98 with VelocityContext

use of org.apache.velocity.VelocityContext in project thingsboard by thingsboard.

the class AlarmProcessor method process.

@Override
public RuleProcessingMetaData process(RuleContext ctx, ToDeviceActorMsg wrapper) throws RuleException {
    RuleProcessingMetaData md = new RuleProcessingMetaData();
    FromDeviceMsg msg = wrapper.getPayload();
    Bindings bindings = buildBindings(ctx, msg);
    boolean isActiveAlarm;
    boolean isClearedAlarm;
    VelocityContext context = VelocityUtils.createContext(ctx.getDeviceMetaData(), msg);
    for (Object key : context.getKeys()) {
        md.put(key.toString(), context.get(key.toString()));
    }
    try {
        isActiveAlarm = newAlarmEvaluator.execute(bindings);
        isClearedAlarm = clearAlarmEvaluator.execute(bindings);
    } catch (ScriptException e) {
        log.debug("[{}] Failed to evaluate alarm expressions!", ctx.getRuleId(), e);
        throw new RuleException("Failed to evaluate alarm expressions!", e);
    }
    if (!isActiveAlarm && !isClearedAlarm) {
        log.debug("[{}] Incoming message do not trigger alarm", ctx.getRuleId());
        return md;
    }
    Alarm existing;
    if (isActiveAlarm) {
        existing = processActiveAlarm(ctx, msg, md);
    } else {
        existing = processInactiveAlarm(ctx, md, context);
    }
    if (existing != null) {
        md.put("alarmId", existing.getId().getId());
        md.put("alarmType", existing.getType());
        md.put("alarmSeverity", existing.getSeverity());
        try {
            if (!StringUtils.isEmpty(existing.getDetails())) {
                md.put("alarmDetails", mapper.writeValueAsString(existing.getDetails()));
            } else {
                md.put("alarmDetails", "{}");
            }
        } catch (JsonProcessingException e) {
            throw new RuleException("Failed to serialize alarm details", e);
        }
    }
    return md;
}
Also used : FromDeviceMsg(org.thingsboard.server.common.msg.session.FromDeviceMsg) ScriptException(javax.script.ScriptException) VelocityContext(org.apache.velocity.VelocityContext) RuleProcessingMetaData(org.thingsboard.server.extensions.api.rules.RuleProcessingMetaData) Alarm(org.thingsboard.server.common.data.alarm.Alarm) RuleException(org.thingsboard.server.extensions.api.rules.RuleException) Bindings(javax.script.Bindings) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 99 with VelocityContext

use of org.apache.velocity.VelocityContext in project thingsboard by thingsboard.

the class AlarmProcessor method buildAlarm.

private Alarm buildAlarm(RuleContext ctx, FromDeviceMsg msg) throws RuleException {
    VelocityContext context = VelocityUtils.createContext(ctx.getDeviceMetaData(), msg);
    String alarmType = VelocityUtils.merge(alarmTypeTemplate, context);
    String alarmDetails = VelocityUtils.merge(alarmDetailsTemplate, context);
    Alarm alarm = new Alarm();
    alarm.setOriginator(ctx.getDeviceMetaData().getDeviceId());
    alarm.setType(alarmType);
    alarm.setStatus(status);
    alarm.setSeverity(severity);
    alarm.setPropagate(configuration.isAlarmPropagateFlag());
    try {
        alarm.setDetails(mapper.readTree(alarmDetails));
    } catch (IOException e) {
        log.debug("[{}] Failed to parse alarm details {} as json string after evaluation.", ctx.getRuleId(), e);
        throw new RuleException("Failed to parse alarm details as json string after evaluation!", e);
    }
    return alarm;
}
Also used : VelocityContext(org.apache.velocity.VelocityContext) Alarm(org.thingsboard.server.common.data.alarm.Alarm) IOException(java.io.IOException) RuleException(org.thingsboard.server.extensions.api.rules.RuleException)

Example 100 with VelocityContext

use of org.apache.velocity.VelocityContext in project embulk by embulk.

the class EmbulkNew method newPlugin.

public boolean newPlugin() throws IOException {
    if (Files.exists(this.pluginBasePath)) {
        throw new IOException("./" + this.fullProjectName + " already exists. Please delete it first.");
    }
    Files.createDirectories(this.pluginBasePath);
    System.out.println("Creating " + this.fullProjectName + "/");
    boolean success = false;
    try {
        // 
        // Generate gemspec
        // 
        final String author = getGitConfig("user.name", "YOUR_NAME");
        final String email = getGitConfig("user.email", "YOUR_NAME");
        final String expectedGitHubAccount = email.split("@")[0];
        // variables used in Velocity templates
        final String rubyClassName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name);
        final String javaClassName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name) + CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, category) + "Plugin";
        final String javaPackageName = "org.embulk." + embulkCategory + "." + name;
        final String displayName = getDisplayName(name);
        final String displayCategory = category.replace("_", " ");
        final HashMap<String, String> extraGuesses = new HashMap<String, String>();
        final String description;
        switch(category) {
            case "input":
                description = String.format("Loads records from %s.", displayName);
                break;
            case "file_input":
                description = String.format("Reads files stored on %s.", displayName);
                break;
            case "parser":
                description = String.format("Parses %s files read by other file input plugins.", displayName);
                extraGuesses.put("org/embulk/plugin/template/ruby/parser_guess.rb.vm", String.format("%s/guess/%s.rb", pluginDirectory, name));
                break;
            case "decoder":
                description = String.format("Decodes %s-encoded files read by other file input plugins.", displayName);
                extraGuesses.put("org/embulk/plugin/template/ruby/decoder_guess.rb.vm", String.format("%s/guess/%s.rb", pluginDirectory, name));
                break;
            case "output":
                description = String.format("Dumps records to %s.", displayName);
                break;
            case "file_output":
                description = String.format("Stores files on %s.", displayName);
                break;
            case "formatter":
                description = String.format("Formats %s files for other file output plugins.", displayName);
                break;
            case "encoder":
                description = String.format("Encodes files using %s for other file output plugins.", displayName);
                break;
            case "filter":
                description = String.format("%s", displayName);
                break;
            default:
                throw new RuntimeException("FATAL: Invalid plugin category.");
        }
        // 
        // Generate project repository
        // 
        final VelocityContext velocityContext = createVelocityContext(author, category, description, displayName, displayCategory, email, embulkCategory, this.embulkVersion, expectedGitHubAccount, fullProjectName, javaClassName, javaPackageName, ScriptingContainerDelegateImpl.getJRubyVersion(EmbulkNew.class.getClassLoader()), language, name, rubyClassName);
        copyTemplated("org/embulk/plugin/template/README.md.vm", "README.md", velocityContext);
        copy("org/embulk/plugin/template/LICENSE.txt", "LICENSE.txt");
        copyTemplated("org/embulk/plugin/template/gitignore.vm", ".gitignore", velocityContext);
        switch(language) {
            case "ruby":
                copy("org/embulk/plugin/template/ruby/Rakefile", "Rakefile");
                copy("org/embulk/plugin/template/ruby/Gemfile", "Gemfile");
                copyTemplated("org/embulk/plugin/template/ruby/.ruby-version", ".ruby-version", velocityContext);
                copyTemplated("org/embulk/plugin/template/ruby/gemspec.vm", fullProjectName + ".gemspec", velocityContext);
                copyTemplated(String.format("org/embulk/plugin/template/ruby/%s.rb.vm", category), this.pluginPath, velocityContext);
                break;
            case "java":
                copy("org/embulk/plugin/template/java/gradle/wrapper/gradle-wrapper.jar", "gradle/wrapper/gradle-wrapper.jar");
                copy("org/embulk/plugin/template/java/gradle/wrapper/gradle-wrapper.properties", "gradle/wrapper/gradle-wrapper.properties");
                copy("org/embulk/plugin/template/java/gradlew.bat", "gradlew.bat");
                copy("org/embulk/plugin/template/java/gradlew", "gradlew");
                setExecutable("gradlew");
                copy("org/embulk/plugin/template/java/config/checkstyle/checkstyle.xml", "config/checkstyle/checkstyle.xml");
                copy("org/embulk/plugin/template/java/config/checkstyle/default.xml", "config/checkstyle/default.xml");
                copyTemplated("org/embulk/plugin/template/java/build.gradle.vm", "build.gradle", velocityContext);
                copyTemplated("org/embulk/plugin/template/java/plugin_loader.rb.vm", this.pluginPath, velocityContext);
                copyTemplated(String.format("org/embulk/plugin/template/java/%s.java.vm", category), String.format("src/main/java/%s/%s.java", javaPackageName.replaceAll("\\.", "/"), javaClassName), velocityContext);
                copyTemplated("org/embulk/plugin/template/java/test.java.vm", String.format("src/test/java/%s/Test%s.java", javaPackageName.replaceAll("\\.", "/"), javaClassName), velocityContext);
                break;
            default:
                throw new RuntimeException("FATAL: Invalid plugin language.");
        }
        for (Map.Entry<String, String> entry : extraGuesses.entrySet()) {
            copyTemplated(entry.getKey(), entry.getValue(), velocityContext);
        }
        System.out.println("");
        System.out.println("Plugin template is successfully generated.");
        switch(language) {
            case "ruby":
                System.out.println("Next steps:");
                System.out.println("");
                System.out.printf("  $ cd %s\n", fullProjectName);
                System.out.println("  $ bundle install                      # install one using rbenv & rbenv-build");
                System.out.println("  $ bundle exec rake                    # build gem to be released");
                System.out.println("  $ bundle exec embulk run config.yml   # you can run plugin using this command");
                break;
            case "java":
                System.out.println("Next steps:");
                System.out.println("");
                System.out.printf("  $ cd %s\n", fullProjectName);
                System.out.println("  $ ./gradlew package");
                break;
            default:
                throw new RuntimeException("FATAL: Invalid plugin language.");
        }
        success = true;
        System.out.println("");
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (!success) {
            System.out.println("Failed. Removing the directory created.");
            deleteDirectoryTree(Paths.get(fullProjectName));
        }
    }
    return success;
}
Also used : HashMap(java.util.HashMap) VelocityContext(org.apache.velocity.VelocityContext) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map) IOException(java.io.IOException)

Aggregations

VelocityContext (org.apache.velocity.VelocityContext)492 StringWriter (java.io.StringWriter)156 Template (org.apache.velocity.Template)120 Test (org.junit.Test)72 IOException (java.io.IOException)60 VelocityEngine (org.apache.velocity.app.VelocityEngine)53 File (java.io.File)47 ArrayList (java.util.ArrayList)39 HashMap (java.util.HashMap)36 Map (java.util.Map)36 Identity (org.olat.core.id.Identity)36 Context (org.apache.velocity.context.Context)32 MailTemplate (org.olat.core.util.mail.MailTemplate)28 Writer (java.io.Writer)22 Properties (java.util.Properties)20 ResourceNotFoundException (org.apache.velocity.exception.ResourceNotFoundException)19 ParseErrorException (org.apache.velocity.exception.ParseErrorException)16 ClasspathResourceLoader (org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader)16 FileWriter (java.io.FileWriter)15 OutputStreamWriter (java.io.OutputStreamWriter)14