Search in sources :

Example 21 with Configuration

use of freemarker.template.Configuration in project jmeter by apache.

the class HtmlTemplateExporter method export.

/*
     * (non-Javadoc)
     * 
     * @see
     * org.apache.jmeter.report.dashboard.DataExporter#Export(org.apache.jmeter
     * .report.processor.SampleContext,
     * org.apache.jmeter.report.config.ReportGeneratorConfiguration)
     */
@Override
public void export(SampleContext context, File file, ReportGeneratorConfiguration configuration) throws ExportException {
    Validate.notNull(context, MUST_NOT_BE_NULL, "context");
    Validate.notNull(file, MUST_NOT_BE_NULL, "file");
    Validate.notNull(configuration, MUST_NOT_BE_NULL, "configuration");
    log.debug("Start template processing");
    // Create data context and populate it
    DataContext dataContext = new DataContext();
    // Get the configuration of the current exporter
    final ExporterConfiguration exportCfg = configuration.getExportConfigurations().get(getName());
    // Get template directory property value
    File templateDirectory = getPropertyFromConfig(exportCfg, TEMPLATE_DIR, new File(JMeterUtils.getJMeterBinDir(), TEMPLATE_DIR_NAME_DEFAULT), File.class);
    if (!templateDirectory.isDirectory()) {
        String message = String.format(INVALID_TEMPLATE_DIRECTORY_FMT, templateDirectory.getAbsolutePath());
        log.error(message);
        throw new ExportException(message);
    }
    // Get output directory property value
    File outputDir = getPropertyFromConfig(exportCfg, OUTPUT_DIR, new File(JMeterUtils.getJMeterBinDir(), OUTPUT_DIR_NAME_DEFAULT), File.class);
    String globallyDefinedOutputDir = JMeterUtils.getProperty(JMeter.JMETER_REPORT_OUTPUT_DIR_PROPERTY);
    if (!StringUtils.isEmpty(globallyDefinedOutputDir)) {
        outputDir = new File(globallyDefinedOutputDir);
    }
    JOrphanUtils.canSafelyWriteToFolder(outputDir);
    if (log.isInfoEnabled()) {
        log.info("Will generate dashboard in folder: {}", outputDir.getAbsolutePath());
    }
    // Add the flag defining whether only sample series are filtered to the
    // context
    final boolean filtersOnlySampleSeries = exportCfg.filtersOnlySampleSeries();
    addToContext(DATA_CTX_FILTERS_ONLY_SAMPLE_SERIES, Boolean.valueOf(filtersOnlySampleSeries), dataContext);
    // Add the series filter to the context
    final String seriesFilter = exportCfg.getSeriesFilter();
    Pattern filterPattern = null;
    if (StringUtils.isNotBlank(seriesFilter)) {
        try {
            filterPattern = Pattern.compile(seriesFilter);
        } catch (PatternSyntaxException ex) {
            log.error("Invalid series filter: '{}', {}", seriesFilter, ex.getDescription());
        }
    }
    addToContext(DATA_CTX_SERIES_FILTER, seriesFilter, dataContext);
    // Add the flag defining whether only controller series are displayed
    final boolean showControllerSeriesOnly = exportCfg.showControllerSeriesOnly();
    addToContext(DATA_CTX_SHOW_CONTROLLERS_ONLY, Boolean.valueOf(showControllerSeriesOnly), dataContext);
    JsonizerVisitor jsonizer = new JsonizerVisitor();
    Map<String, Object> storedData = context.getData();
    // Add begin date consumer result to the data context
    addResultToContext(ReportGenerator.BEGIN_DATE_CONSUMER_NAME, storedData, dataContext, jsonizer);
    // Add end date summary consumer result to the data context
    addResultToContext(ReportGenerator.END_DATE_CONSUMER_NAME, storedData, dataContext, jsonizer);
    // Add Apdex summary consumer result to the data context
    addResultToContext(ReportGenerator.APDEX_SUMMARY_CONSUMER_NAME, storedData, dataContext, jsonizer);
    // Add errors summary consumer result to the data context
    addResultToContext(ReportGenerator.ERRORS_SUMMARY_CONSUMER_NAME, storedData, dataContext, jsonizer);
    // Add requests summary consumer result to the data context
    addResultToContext(ReportGenerator.REQUESTS_SUMMARY_CONSUMER_NAME, storedData, dataContext, jsonizer);
    // Add statistics summary consumer result to the data context
    addResultToContext(ReportGenerator.STATISTICS_SUMMARY_CONSUMER_NAME, storedData, dataContext, jsonizer);
    // Add Top 5 errors by sampler consumer result to the data context
    addResultToContext(ReportGenerator.TOP5_ERRORS_BY_SAMPLER_CONSUMER_NAME, storedData, dataContext, jsonizer);
    // Collect graph results from sample context and transform them into
    // Json strings to inject in the data context
    ExtraOptionsResultCustomizer customizer = new ExtraOptionsResultCustomizer();
    EmptyGraphChecker checker = new EmptyGraphChecker(filtersOnlySampleSeries, showControllerSeriesOnly, filterPattern);
    for (Map.Entry<String, GraphConfiguration> graphEntry : configuration.getGraphConfigurations().entrySet()) {
        final String graphId = graphEntry.getKey();
        final GraphConfiguration graphConfiguration = graphEntry.getValue();
        final SubConfiguration extraOptions = exportCfg.getGraphExtraConfigurations().get(graphId);
        // Initialize customizer and checker
        customizer.setExtraOptions(extraOptions);
        checker.setExcludesControllers(graphConfiguration.excludesControllers());
        checker.setGraphId(graphId);
        // Export graph data
        addResultToContext(graphId, storedData, dataContext, jsonizer, customizer, checker);
    }
    // Replace the begin date with its formatted string and store the old
    // timestamp
    long oldTimestamp = formatTimestamp(ReportGenerator.BEGIN_DATE_CONSUMER_NAME, dataContext);
    // Replace the end date with its formatted string
    formatTimestamp(ReportGenerator.END_DATE_CONSUMER_NAME, dataContext);
    // Add time zone offset (that matches the begin date) to the context
    TimeZone timezone = TimeZone.getDefault();
    addToContext(DATA_CTX_TIMEZONE_OFFSET, Integer.valueOf(timezone.getOffset(oldTimestamp)), dataContext);
    // Add report title to the context
    if (!StringUtils.isEmpty(configuration.getReportTitle())) {
        dataContext.put(DATA_CTX_REPORT_TITLE, StringEscapeUtils.escapeHtml4(configuration.getReportTitle()));
    }
    // Add the test file name to the context
    addToContext(DATA_CTX_TESTFILE, file.getName(), dataContext);
    // Add the overall filter property to the context
    addToContext(DATA_CTX_OVERALL_FILTER, configuration.getSampleFilter(), dataContext);
    // Walk template directory to copy files and process templated ones
    Configuration templateCfg = new Configuration(Configuration.getVersion());
    try {
        templateCfg.setDirectoryForTemplateLoading(templateDirectory);
        templateCfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        if (log.isInfoEnabled()) {
            log.info("Report will be generated in: {}, creating folder structure", outputDir.getAbsolutePath());
        }
        FileUtils.forceMkdir(outputDir);
        TemplateVisitor visitor = new TemplateVisitor(templateDirectory.toPath(), outputDir.toPath(), templateCfg, dataContext);
        Files.walkFileTree(templateDirectory.toPath(), visitor);
    } catch (IOException ex) {
        throw new ExportException("Unable to process template files.", ex);
    }
    log.debug("End of template processing");
}
Also used : Pattern(java.util.regex.Pattern) GraphConfiguration(org.apache.jmeter.report.config.GraphConfiguration) GraphConfiguration(org.apache.jmeter.report.config.GraphConfiguration) ReportGeneratorConfiguration(org.apache.jmeter.report.config.ReportGeneratorConfiguration) SubConfiguration(org.apache.jmeter.report.config.SubConfiguration) ExporterConfiguration(org.apache.jmeter.report.config.ExporterConfiguration) Configuration(freemarker.template.Configuration) IOException(java.io.IOException) DataContext(org.apache.jmeter.report.core.DataContext) ExporterConfiguration(org.apache.jmeter.report.config.ExporterConfiguration) TimeZone(java.util.TimeZone) SubConfiguration(org.apache.jmeter.report.config.SubConfiguration) File(java.io.File) Map(java.util.Map) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Example 22 with Configuration

use of freemarker.template.Configuration in project SpringStepByStep by JavaProgrammerLB.

the class SendHTMLEmailWithTemplate method main.

public static void main(String[] args) throws Exception {
    Properties props = new Properties();
    try {
        props.load(new FileInputStream(new File("settings.properties")));
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    Session session = Session.getDefaultInstance(props, new Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("username", "******");
        }
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("from@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
        message.setSubject("Testing Subject");
        BodyPart body = new MimeBodyPart();
        // freemarker stuff.
        Configuration cfg = new Configuration();
        Template template = cfg.getTemplate("html-mail-template.ftl");
        Map<String, String> rootMap = new HashMap<String, String>();
        rootMap.put("to", "liubei");
        rootMap.put("body", "Sample html email using freemarker");
        rootMap.put("from", "liubei");
        Writer out = new StringWriter();
        template.process(rootMap, out);
        // freemarker stuff ends.
        /* you can add html tags in your text to decorate it. */
        body.setContent(out.toString(), "text/html");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(body);
        body = new MimeBodyPart();
        String filename = "hello.txt";
        DataSource source = new FileDataSource(filename);
        body.setDataHandler(new DataHandler(source));
        body.setFileName(filename);
        multipart.addBodyPart(body);
        message.setContent(multipart, "text/html;charset=utf-8");
        Transport.send(message);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
    System.out.println("Done....");
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Configuration(freemarker.template.Configuration) HashMap(java.util.HashMap) FileNotFoundException(java.io.FileNotFoundException) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) Template(freemarker.template.Template) StringWriter(java.io.StringWriter) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) Authenticator(javax.mail.Authenticator) PasswordAuthentication(javax.mail.PasswordAuthentication) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File) StringWriter(java.io.StringWriter) Writer(java.io.Writer) Session(javax.mail.Session)

Example 23 with Configuration

use of freemarker.template.Configuration in project SpringStepByStep by JavaProgrammerLB.

the class FreemarkerTest method main.

public static void main(String[] args) {
    Configuration config = new Configuration();
    try {
        String path = new File("").getAbsolutePath();
        config.setDirectoryForTemplateLoading(new File(path));
        Template template = config.getTemplate("src/test.ftl", "UTF-8");
        // 创建数据模型
        Map root = new HashMap();
        List<User> users = new ArrayList<User>();
        User u1 = new User();
        u1.setId("123");
        u1.setName("王五");
        users.add(u1);
        User u2 = new User();
        u2.setId("423");
        u2.setName("李四");
        users.add(u2);
        User u3 = new User();
        u3.setId("333");
        u3.setName("张三");
        users.add(u3);
        root.put("userList", users);
        Map product = new HashMap();
        root.put("lastProduct", product);
        product.put("url", "www.baidu.com");
        product.put("name", "green hose");
        File file = new File(path + "\\src\\test.html");
        if (!file.exists()) {
            //System.out.println("file exist");  
            file.createNewFile();
        }
        Writer out = new BufferedWriter(new FileWriter(file));
        template.process(root, out);
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (TemplateException e) {
        e.printStackTrace();
    }
}
Also used : Configuration(freemarker.template.Configuration) HashMap(java.util.HashMap) TemplateException(freemarker.template.TemplateException) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Template(freemarker.template.Template) BufferedWriter(java.io.BufferedWriter) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) BufferedWriter(java.io.BufferedWriter) FileWriter(java.io.FileWriter) Writer(java.io.Writer)

Example 24 with Configuration

use of freemarker.template.Configuration in project SpringStepByStep by JavaProgrammerLB.

the class FreeMarkerTemplateEngine method createFreemarkerConfiguration.

private Configuration createFreemarkerConfiguration() {
    Configuration retVal = new Configuration();
    retVal.setClassForTemplateLoading(FreeMarkerTemplateEngine.class, "freemarker");
    return retVal;
}
Also used : Configuration(freemarker.template.Configuration)

Example 25 with Configuration

use of freemarker.template.Configuration in project stanbol by apache.

the class ViewableWriter method renderPojo.

/**
     * Old school classical freemarker rendering, no LD here
     */
public void renderPojo(Object pojo, final String templatePath, Writer out) {
    Configuration freemarker = new Configuration();
    freemarker.setDefaultEncoding("utf-8");
    freemarker.setOutputEncoding("utf-8");
    freemarker.setLocalizedLookup(false);
    freemarker.setObjectWrapper(new DefaultObjectWrapper());
    freemarker.setTemplateLoader(templateLoader);
    try {
        //should root be a map instead?
        freemarker.getTemplate(templatePath).process(pojo, out);
        out.flush();
    } catch (IOException e) {
        throw new RuntimeException("IOException while processing Template '" + templatePath + "' with Object '" + pojo + "' (class: " + pojo != null ? pojo.getClass().getName() : null + ")!", e);
    } catch (TemplateException e) {
        throw new RuntimeException(e);
    }
}
Also used : Configuration(freemarker.template.Configuration) TemplateException(freemarker.template.TemplateException) DefaultObjectWrapper(freemarker.template.DefaultObjectWrapper) IOException(java.io.IOException)

Aggregations

Configuration (freemarker.template.Configuration)56 Template (freemarker.template.Template)30 Writer (java.io.Writer)17 IOException (java.io.IOException)14 StringWriter (java.io.StringWriter)14 File (java.io.File)13 HashMap (java.util.HashMap)11 DefaultObjectWrapper (freemarker.template.DefaultObjectWrapper)8 TemplateException (freemarker.template.TemplateException)7 OutputStreamWriter (java.io.OutputStreamWriter)7 StringTemplateLoader (freemarker.cache.StringTemplateLoader)5 ThirdEyeAnomalyConfiguration (com.linkedin.thirdeye.anomaly.ThirdEyeAnomalyConfiguration)4 ClassTemplateLoader (freemarker.cache.ClassTemplateLoader)4 FileTemplateLoader (freemarker.cache.FileTemplateLoader)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 FileWriter (java.io.FileWriter)4 StringReader (java.io.StringReader)4 ArrayList (java.util.ArrayList)4 MultiTemplateLoader (freemarker.cache.MultiTemplateLoader)3 TemplateLoader (freemarker.cache.TemplateLoader)3