public static void main(String[] args) throws IOException, TemplateException {
    Locale.setDefault(Locale.US);

    boolean simple = false;

    Configuration cfg = new Configuration();
    // Specify the data source where the template files come from.
    // Here I set a file directory for it:
    cfg.setDirectoryForTemplateLoading(new File("src/test/resources/templates"));

    // Specify how templates will see the data-model. This is an advanced topic...
    // but just use this:
    cfg.setObjectWrapper(new DefaultObjectWrapper());

    Template temp;
    String name;
    if (simple) {
      temp = cfg.getTemplate("simple.ftl");
      name = "simple";
    } else {
      temp = cfg.getTemplate("extended.ftl");
      name = "orders";
    }

    String path = "";

    write(temp, 1, path + name + "-1.xml", simple);
    write(temp, 50, path + name + "-50.xml", simple);
    write(temp, 500, path + name + "-500.xml", simple);
    write(temp, 5000, path + name + "-5000.xml", simple);
    write(temp, 50000, path + name + "-50000.xml", simple);
    write(temp, 500000, path + name + "-500000.xml", simple);

    System.out.println("done");
  }
  private String buildEmailAlarmContent(ThresholdAlarmMeta meta) {
    Map<Object, Object> root = new HashMap<Object, Object>();
    StringWriter sw = new StringWriter(5000);

    root.put("rule", buildRuleMeta(meta.getDuration()));
    root.put("count", meta.getRealCount());
    root.put("domain", meta.getDomain());
    root.put("date", meta.getDate());
    root.put("url", buildProblemUrl(meta.getBaseShowUrl(), meta.getDomain(), meta.getDate()));

    try {
      String type = meta.getType();

      if (type.equalsIgnoreCase(AlertInfo.EXCEPTION)) {
        Template t = m_configuration.getTemplate("exceptionAlarm.ftl");

        t.process(root, sw);
      } else if (type.equalsIgnoreCase(AlertInfo.SERVICE)) {
        Template t = m_configuration.getTemplate("serviceAlarm.ftl");

        t.process(root, sw);
      }
    } catch (Exception e) {
      Cat.logError(e);
    }
    return sw.toString();
  }
Exemple #3
0
  /**
   * Description: 生成service相关类
   *
   * @throws Exception
   */
  public static void makeService() throws Exception {
    Configuration cfg = getCfg();
    // interface
    Template template = cfg.getTemplate("serviceInterface.html");

    // 生成文件设置
    String path =
        getJavaFileRoot()
            + File.separator
            + PropertyUtil.getValue("code.src.service.root")
            + File.separator
            + key;
    mkdirs(path);
    path += File.separator + "I" + upperKey + "Service.java";
    FileWriter sw = new FileWriter(new File(path));
    WeakHashMap<String, Object> data = new WeakHashMap<String, Object>();
    data.put("packageName", servicePackagePath); // 包名
    data.put("EntityClass", entityPackagePath + "." + upperKey + "Entity");
    data.put("key", key);
    data.put("UpperKey", upperKey);
    data.put("ZhKey", zhKey);
    data.put("primaryKey", primaryKey.getName());
    data.put("UpperPrimaryKey", StringUtil.upperFirst(primaryKey.getName()));
    data.put("PrimaryKeyType", StringUtil.upperFirst(primaryKey.getType()));
    data.put("author", author);
    data.put("createDate", createDate);

    template.process(data, sw);

    // impl
    Template implTemplate = cfg.getTemplate("service.html");
    String serviceImplPackagePath = servicePackagePath + ".impl";
    // 生成文件设置
    String implPath =
        getJavaFileRoot()
            + File.separator
            + PropertyUtil.getValue("code.src.service.root")
            + File.separator
            + key
            + File.separator
            + "impl";
    mkdirs(implPath);
    implPath += File.separator + upperKey + "ServiceImpl.java";
    FileWriter implWriter = new FileWriter(new File(implPath));
    WeakHashMap<String, Object> implData = new WeakHashMap<String, Object>();
    implData.put("packageName", serviceImplPackagePath); // 包名
    implData.put("key", key);
    implData.put("UpperKey", upperKey);
    implData.put("ZhKey", zhKey);
    implData.put("EntityClass", entityPackagePath + "." + upperKey + "Entity");
    implData.put("daoInterFace", daoPackagePath + ".I" + upperKey + "Dao");
    implData.put("serviceInterFace", servicePackagePath + ".I" + upperKey + "Service");
    implData.put("primaryKey", primaryKey.getName());
    implData.put("UpperPrimaryKey", StringUtil.upperFirst(primaryKey.getName()));
    implData.put("PrimaryKeyType", StringUtil.upperFirst(primaryKey.getType()));
    implData.put("author", author);
    implData.put("createDate", createDate);

    implTemplate.process(implData, implWriter);
  }
  /**
   * 创建历史成交数据
   *
   * @param buildingTab
   * @param estateTab
   */
  private void createChartXmlFile(
      TransanctionStatManager transanctionStatManager,
      String xmlFilePath,
      String xmlAvgPriceFile,
      String xmlCountFile,
      List tenYears) {
    try {
      // 生成所有交易年数据文件
      String filesp = File.separator;
      String templatePath =
          Constants.REALPATH
              + "WEB-INF"
              + filesp
              + "pages"
              + filesp
              + "maker"
              + filesp
              + "chart"
              + filesp;
      String templateAvgPriceFileName = "chart_avgprice_xml.ftl";
      String templateCountFileName = "chart_count_xml.ftl";

      Configuration cfg = new Configuration();
      cfg.setNumberFormat("0.######");
      cfg.setDirectoryForTemplateLoading(new File(templatePath));
      cfg.setObjectWrapper(new DefaultObjectWrapper());

      Map root = new HashMap();
      root.put("tenYears", tenYears);

      // 生成十年交易平均价格数据文件
      Template templateAvgPrice = cfg.getTemplate(templateAvgPriceFileName, "UTF-8");
      Writer avgpriceOut = new OutputStreamWriter(new FileOutputStream(xmlAvgPriceFile), "UTF-8");
      try {
        templateAvgPrice.process(root, avgpriceOut);
      } catch (TemplateException e) {
        e.printStackTrace();
      }
      avgpriceOut.flush();
      avgpriceOut.close();

      // 生成十年交易总数数据文件
      Template templateCount = cfg.getTemplate(templateCountFileName, "UTF-8");
      Writer countOut = new OutputStreamWriter(new FileOutputStream(xmlCountFile), "UTF-8");
      try {
        templateCount.process(root, countOut);
      } catch (TemplateException e) {
        e.printStackTrace();
      }
      countOut.flush();
      countOut.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public static void main(String[] args) throws Exception {

    /* You should do this ONLY ONCE in the whole application life-cycle: */

    /* Create and adjust the configuration singleton */
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
    cfg.setDirectoryForTemplateLoading(new File("/Users/ian.goldsmith/projects/freemarker"));
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

    /*
     * You usually do these for MULTIPLE TIMES in the application
     * life-cycle:
     */

    /* Create a data-model */
    Map message = new HashMap();
    message.put(
        "contentAsXml",
        freemarker.ext.dom.NodeModel.parse(
            new File("/Users/ian.goldsmith/projects/freemarker/test.xml")));

    Map root = new HashMap();
    root.put("message", message);

    /* Get the template (uses cache internally) */
    Template temp = cfg.getTemplate("testxml.ftl");

    /* Merge data-model with template */
    Writer out = new OutputStreamWriter(System.out);
    temp.process(root, out);
    // Note: Depending on what `out` is, you may need to call `out.close()`.
    // This is usually the case for file output, but not for servlet output.
  }
 public TemplateEngine(File outdir, File templatedir, String templatename) throws IOException {
   Configuration cfg = new Configuration();
   cfg.setDirectoryForTemplateLoading(templatedir);
   cfg.setObjectWrapper(new DefaultObjectWrapper());
   temp = cfg.getTemplate(templatename);
   this.out = outdir;
 }
  public static void process(HttpSession session, PrintWriter out, String template)
      throws TemplateException, IOException {
    // handle all button stuff, if user has loging, create logout button
    // if not, create login button
    if (!root.containsKey("button")) {
      if (session.getAttribute("user") == null) {
        root.put(
            "button",
            "<li><a href='login.html'><span class='glyphicon glyphicon-log-in'></span> Login</a></li>");
      } else {
        root.put(
            "button",
            "<li><a><span class='glyphicon'></span>Welcome, "
                + session.getAttribute("user")
                + "</a></li>"
                + "<li><a href='logout.html'><span class='glyphicon glyphicon-log-out'></span> Logout</a></li>");
      }
    }

    // set default value
    if (!root.containsKey("list")) root.put("list", "");
    if (!root.containsKey("menu")) root.put("menu", "");

    Template temp = cfg.getTemplate(template);
    temp.process(root, out);
    root = new HashMap();
  }
  public static LayoutContent displayHome(spark.Request request, Configuration cfg) {
    String html = "";
    Map<String, String> root = Tools.listLayoutMap();
    root.replace("msg", DBH.getMsg(request.session().id()));
    Template temp;
    try {
      temp = cfg.getTemplate("user-home.htm");
      Writer out = new StringWriter();
      temp.process(root, out);
      html = out.toString();
    } catch (IOException | TemplateException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      html = e.getMessage();
    }
    HashMap<String, String> options = new HashMap<String, String>();
    options.put("addBtn", Tools.getAddBtn("/tramites/agregar", "Iniciar Trámite"));
    options.put(
        "toolBar",
        Tools.getToolbarItem("/tramites/agregar", "Iniciar Trámite", "", "btn red darken-3")
            + Tools.getToolbarItem("/tramites", "Trámites", "", "btn green darken-3"));

    LayoutContent lc = new LayoutContent(html, options);
    return lc;
  }
  @Override
  public void sendPasswordResetLink(final AppUser user) {
    try {
      if (user.getPasswordResetToken() == null || user.getPasswordResetToken().isEmpty()) {
        return;
      }
      Template template = configuration.getTemplate("resetpassword.ftl");
      final Map model = new HashMap();
      model.put("name", user.getName());
      String password_reset_url = RESET_PASSWORD_URL + "?token=" + user.getPasswordResetToken();
      model.put("password_reset_url", password_reset_url);
      final String mailBody = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
      MimeMessagePreparator preparator =
          new MimeMessagePreparator() {

            public void prepare(MimeMessage mimeMessage) throws Exception {
              MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
              message.setTo(user.getEmail());
              message.setSubject("GWA-Portal password reset confirmation");
              message.setFrom(FROM);
              message.setText(mailBody, false);
            }
          };
      mailSender.send(preparator);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemple #10
0
  private String substituteParams(final Event e) {
    final Configuration cfg = new Configuration();
    final StringWriter writer = new StringWriter();
    String processedTemplate = null;
    // StringTemplateLoader Freemarker used to read the ResponseTemplate of
    // Event object
    final StringTemplateLoader stringLoader = new StringTemplateLoader();
    stringLoader.putTemplate("template", e.getResponseTemplate());
    cfg.setTemplateLoader(stringLoader);
    Template tpl;

    // Substitutes the ResponseTemplate variables with the values defined in
    // the map(params)
    try {
      tpl = cfg.getTemplate("template");
      tpl.process(e.getParams(), writer);
      processedTemplate = writer.toString();

    } catch (final IOException ex) {
      throw new EGOVRuntimeException(
          "Exception Occurred in EventProcessor while substituting Parameters" + ex);
    } catch (final TemplateException ex) {
      throw new EGOVRuntimeException(
          "Exception Occurred in EventProcessor while processing Template" + ex);
    }
    return processedTemplate;
  }
 public String produceFeatureElement(
     FeatureTreeNode feature, Map featureData, String templateFileName) {
   String output = "";
   try {
     if (featureElementTemplate == null) {
       featureElementTemplate = cfg.getTemplate(templateFileName);
     }
     featureData.putAll(produceBasicFeatureData(feature));
     FeatureTreeNode parentNode =
         (FeatureTreeNode) ((feature instanceof FeatureGroup) ? feature.getParent() : feature);
     List children = new ArrayList(parentNode.getChildCount());
     for (int i = 0; i < parentNode.getChildCount(); i++) {
       FeatureTreeNode childNode = (FeatureTreeNode) parentNode.getChildAt(i);
       if (childNode instanceof FeatureGroup) {
         for (int j = 0; j < childNode.getChildCount(); j++) {
           FeatureTreeNode groupedNode = (FeatureTreeNode) childNode.getChildAt(j);
           children.add(produceBasicFeatureData(groupedNode));
         }
       } else {
         children.add(produceBasicFeatureData(childNode));
       }
     }
     featureData.put("children", children);
     StringWriter outputWriter = new StringWriter();
     featureElementTemplate.process(featureData, outputWriter);
     output = outputWriter.toString();
   } catch (Exception e) {
     output = e.getMessage();
   }
   return output;
 }
  // templatePath模板文件存放路径
  // templateName 模板文件名称
  // filename 生成的文件名称
  public static void analysisTemplate(
      String templatePath, String templateName, String fileName, Map<?, ?> root) {
    try {

      Configuration config = new Configuration();
      // 设置要解析的模板所在的目录,并加载模板文件
      config.setDirectoryForTemplateLoading(new File(templatePath));
      // 设置包装器,并将对象包装为数据模型
      config.setObjectWrapper(new DefaultObjectWrapper());

      // 获取模板,并设置编码方式,这个编码必须要与页面中的编码格式一致
      // 否则会出现乱码
      Template template = config.getTemplate(templateName, "UTF-8");
      // 合并数据模型与模板
      FileOutputStream fos = new FileOutputStream(fileName);
      Writer out = new OutputStreamWriter(fos, "UTF-8");
      template.process(root, out);
      out.flush();
      out.close();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (TemplateException e) {
      e.printStackTrace();
    }
  }
Exemple #13
0
  public static void makeEntity() throws Exception {
    Configuration cfg = getCfg();
    Template template = cfg.getTemplate("entity.html");

    // 生成文件设置
    String path =
        getJavaFileRoot() + File.separator + PropertyUtil.getValue("code.src.entity.root");
    mkdirs(path);
    path += File.separator + upperKey + "Entity.java";
    FileWriter sw = new FileWriter(new File(path));
    WeakHashMap<String, Object> data = new WeakHashMap<String, Object>();
    data.put("packageName", entityPackagePath);
    data.put("key", key);
    data.put("UpperKey", upperKey);
    data.put("ZhKey", zhKey);
    data.put("author", author);
    data.put("createDate", createDate);

    List<Field> list = MysqlUtil.getInstance().getTableField();
    noCommonFieldList = removeCommonFields(list);
    data.put("fieldList", list);
    data.put("noCommonFieldList", noCommonFieldList);

    primaryKey = MysqlUtil.getInstance().getPrimaryKey(list);
    fieldList = list;

    String level = PropertyUtil.getValue("created.code.level");
    if (!levels.contains(level)) {
      level = "all";
    }
    if ("all".equals(level) || "entity".equals(level)) {
      template.process(data, sw);
    }
  }
Exemple #14
0
  /** Description: */
  public static void makeController() throws Exception {
    Configuration cfg = getCfg();
    Template template = cfg.getTemplate("controller.html");

    // 生成文件设置
    String path =
        getJavaFileRoot()
            + File.separator
            + PropertyUtil.getValue("code.src.controller.root")
            + File.separator
            + key;
    mkdirs(path);
    path += File.separator + upperKey + "Controller.java";
    FileWriter sw = new FileWriter(new File(path));
    WeakHashMap<String, Object> data = new WeakHashMap<String, Object>();
    data.put("packageName", controllerPackagePath); // 包名

    data.put("pagePrefix", urlPrefix.substring(1));

    data.put("urlPrefix", urlPrefix);
    data.put("key", key);
    data.put("UpperKey", upperKey);
    data.put("ZhKey", zhKey);
    data.put("author", author);
    data.put("createDate", createDate);

    data.put("EntityClass", entityPackagePath + "." + upperKey + "Entity");
    data.put("serviceInterFace", servicePackagePath + ".I" + upperKey + "Service");
    data.put("primaryKey", primaryKey.getName());
    data.put("UpperPrimaryKey", StringUtil.upperFirst(primaryKey.getName()));

    template.process(data, sw);
  }
  @Override
  public void render(
      RoutingContext context, String templateFileName, Handler<AsyncResult<Buffer>> handler) {
    try {
      Template template = cache.get(templateFileName);
      if (template == null) {
        // real compile
        synchronized (this) {
          loader.setVertx(context.vertx());
          // Compile
          template = config.getTemplate(adjustLocation(templateFileName));
        }
        cache.put(templateFileName, template);
      }

      Map<String, RoutingContext> variables = new HashMap<>(1);
      variables.put("context", context);

      try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        template.process(variables, new OutputStreamWriter(baos));
        handler.handle(Future.succeededFuture(Buffer.buffer(baos.toByteArray())));
      }

    } catch (Exception ex) {
      handler.handle(Future.failedFuture(ex));
    }
  }
Exemple #16
0
 /**
  * método que permite generar fichero index.html
  *
  * @throws Exception
  */
 private void generarIndex() throws Exception {
   FileOutputStream fo = null;
   Writer out = null;
   File index = null;
   Template temp;
   try {
     temp = cfg.getTemplate("index.ftl");
     index = new File(dirDestino + "/index.html");
     boolean creado = index.createNewFile();
     if (creado) {
       fo = new FileOutputStream(index);
       out = new OutputStreamWriter(fo);
       temp.process(root, out);
       out.flush();
     }
   } catch (Exception e) {
     if (logger.isDebugEnabled()) {
       logger.debug("Error en GeneradorHTML:generarIndex .. " + e.getMessage());
     }
     throw e;
   } finally {
     index = null;
     if (fo != null) {
       try {
         fo.close();
         out.close();
       } catch (IOException e) {
       }
     }
   }
 }
Exemple #17
0
 /**
  * 发送模板邮件
  *
  * @param toMailAddr 收信人地址
  * @param subject email主题
  * @param templatePath 模板地址
  * @param map 模板map
  */
 public static void sendFtlMail(
     String toMailAddr, String subject, String templatePath, Map<String, Object> map) {
   Template template = null;
   Configuration freeMarkerConfig = null;
   HtmlEmail hemail = new HtmlEmail();
   try {
     hemail.setHostName(getHost(from));
     hemail.setSmtpPort(getSmtpPort(from));
     hemail.setCharset(charSet);
     hemail.addTo(toMailAddr);
     hemail.setFrom(from, fromName);
     hemail.setAuthentication(username, password);
     hemail.setSubject(subject);
     freeMarkerConfig = new Configuration();
     freeMarkerConfig.setDirectoryForTemplateLoading(new File(getFilePath()));
     // 获取模板
     template =
         freeMarkerConfig.getTemplate(getFileName(templatePath), new Locale("Zh_cn"), "UTF-8");
     // 模板内容转换为string
     String htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
     System.out.println(htmlText);
     hemail.setMsg(htmlText);
     hemail.send();
     System.out.println("email send true!");
   } catch (Exception e) {
     e.printStackTrace();
     System.out.println("email send error!");
   }
 }
Exemple #18
0
 /**
  * テンプレートを取得します。
  *
  * @param name テンプレートの名前
  * @return テンプレート
  */
 protected Template getTemplate(String name) {
   try {
     return configuration.getTemplate(name);
   } catch (IOException e) {
     throw new GenException(Message.YUIGEN9001, e, e);
   }
 }
Exemple #19
0
  @Test
  public void testFreemarkerAccess() throws Exception {

    configuration = new Configuration();
    configuration.setDirectoryForTemplateLoading(new File("src/test/resources/"));

    Map<String, Object> model = new HashMap<String, Object>();

    UID homepageUID = new UID("foaf", "homepage");
    UID workpageUID = new UID("foaf", "workpage");

    UID documentUID = new UID("foaf", "mypage");

    DummyResource resource = new DummyResource();

    DummyProperty prop = new DummyProperty<UID>(homepageUID);
    prop.getLiteralsSet().add(new LIT("http://www.koti.com"));
    resource.getPropertiesMap().put(homepageUID, prop);
    prop.getReferencesSet().add(documentUID);

    prop = new DummyProperty<UID>(workpageUID);
    prop.getLiteralsSet().add(new LIT("http://www.mysema.com"));
    prop.getLiteralsSet().add(new LIT("http://www.mysema1.com"));
    resource.getPropertiesMap().put(workpageUID, prop);

    model.put("resource", resource);
    model.put("uid", homepageUID);

    Writer writer = new PrintWriter(System.out);
    configuration.getTemplate("freemarker_test.ftl").process(model, writer);
    // writer.close();
  }
Exemple #20
0
  @Override
  public String generateContent(AlertEntity alert) {
    Map<Object, Object> dataMap = generateExceptionMap(alert);
    StringWriter sw = new StringWriter(5000);

    try {
      Template t = m_configuration.getTemplate("exceptionAlert.ftl");
      t.process(dataMap, sw);
    } catch (Exception e) {
      Cat.logError("build exception content error:" + alert.toString(), e);
    }

    String alertContent = sw.toString();
    String summaryContext = "";

    try {
      summaryContext = m_executor.execute(alert.getDomain(), alert.getDate());
    } catch (Exception e) {
      Cat.logError(alert.toString(), e);
    }

    if (summaryContext != null) {
      return alertContent + "<br/>" + summaryContext;
    } else {
      return alertContent;
    }
  }
  @Override
  public void sendAsHtml(
      String subject, String html, Collection<String> recipients, Map<String, Object> htmlParams)
      throws Exception {
    Address[] addresses = new Address[recipients.size()];
    Iterator<String> iterator = recipients.iterator();
    int i = 0;
    while (iterator.hasNext()) {
      addresses[i] = new InternetAddress(iterator.next());
      i++;
    }

    Template template = configuration.getTemplate(html);
    Writer writer = new StringWriter();
    template.process(htmlParams, writer);

    BodyPart bodyPart = new MimeBodyPart();
    bodyPart.setContent(writer.toString(), "text/html");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(bodyPart);

    Message message = new MimeMessage(session);
    message.setFrom();
    message.setRecipients(Message.RecipientType.TO, addresses);
    message.setSubject(subject);
    message.setContent(multipart, "text/html");

    Transport.send(message);
  }
 /**
  * Creates a Freemarker template.
  *
  * @param templateName the template name, not null
  * @return the template, not null
  */
 public Template createTemplate(final String templateName) {
   try {
     return _configuration.getTemplate(templateName);
   } catch (IOException ex) {
     throw new RuntimeException(ex);
   }
 }
Exemple #23
0
  private void generateCode(Writer modelCodeWriter) throws IOException, TemplateException {
    Map<String, Object> modelProperties = Maps.newHashMap();
    List<Map<String, Object>> eventList = Lists.newLinkedList();
    modelProperties.put("modelName", modelName);
    modelProperties.put("events", eventList);
    modelProperties.put("variables", variableList);

    for (Event event : events) {
      EventBuilder eventBuilder = new EventBuilder();
      Event.EventState eventState = event.getEventState();
      Event.Function eventFunctionMatcher = new Event.Function(eventState.getFunctionBody());
      eventFunctionMatcher.process();

      eventBuilder.setName(eventState.getName());
      eventBuilder.setParameters(eventFunctionMatcher.getParameters());
      eventBuilder.setBody(eventFunctionMatcher.getBody());

      for (Map.Entry<Event, List<Edge>> targetEntry : adjacencyList.row(event).entrySet()) {
        List<Edge> edges = targetEntry.getValue();

        for (Edge edge : edges) {
          eventBuilder.addEdge(edge);
        }
      }

      eventList.add(eventBuilder.asMap());
    }

    Templates templatesInstance = Templates.getTemplatesInstance();
    Configuration templateConfiguration = templatesInstance.getConfiguration();
    Template modelTemplate = templateConfiguration.getTemplate("Simulation.java.ftl");

    modelTemplate.process(modelProperties, modelCodeWriter);
  }
 public void generatePropertiesClass(PropertiesClass propertiesClass, Writer out)
     throws IOException, TemplateException {
   Template template = cfg.getTemplate("properties_class.ftl");
   Environment env = template.createProcessingEnvironment(propertiesClass, out);
   env.setOutputEncoding(outputCharset);
   env.process();
 }
  public static void main(String[] args) {
    Writer out = null;
    String gAME_VERSION = "1";
    String tAG_VERSION = "195";
    String channelName = "ZHANGYUE";
    String cHANNEL_ID = "3058";
    String mEIDA_CHANNEL = "2011552002";

    Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
    try {
      cfg.setDirectoryForTemplateLoading(new File("./templates"));
      cfg.setDefaultEncoding("UTF-8");
      cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

      Map<String, Object> root = new HashMap<String, Object>();
      XMTLBBConfig xConfig =
          XTestMain.getConfigBean(
              channelName, cHANNEL_ID, gAME_VERSION, tAG_VERSION, mEIDA_CHANNEL);
      root.put("XMTLBB", xConfig);

      File target = new File("./target/" + cHANNEL_ID + "/config.properties");
      target.getParentFile().mkdirs();

      Template temp = cfg.getTemplate("config.ftl");
      out = new OutputStreamWriter(new FileOutputStream(target), "utf-8");
      temp.process(root, out);

      out.flush();
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  @Override
  public void run() {
    try {
      Template template = cfg.getTemplate("/reports/templates/classloader.ftl");

      ApplicationContext appCtx = new ApplicationContext(namingUtility.getApplicationName());

      ClassloaderReport report =
          new ClassloaderReport("Class Not Found", "Class Not Found", "Referenced By");

      // for each class leveraging a blacklist...
      for (JavaClass clz : javaClassDao.getAllClassNotFound()) {
        Name name =
            namingUtility.getReportJavaResource(runDirectory, reportReference.getParentFile(), clz);

        // get reference...
        ClassLoaderReportRow row = new ClassLoaderReportRow(name);
        addAll(row.getReferences(), clz.providesForJavaClass());

        report.getClasses().add(row);
      }

      Map<String, Object> objects = new HashMap<String, Object>();
      objects.put("application", appCtx);
      objects.put("classloader", report);

      template.process(objects, new FileWriter(reportReference));
    } catch (Exception e) {
      throw new RuntimeException("Exception processing report.", e);
    }
  }
  /**
   * @param templateName 模板文件名称
   * @param templateEncoding 模板文件的编码方式
   * @param root 数据模型根对象
   */
  public static void analysisTemplate(
      String templateName, String templateEncoding, Map<?, ?> root) {
    try {
      /** 创建Configuration对象 */
      Configuration config = new Configuration();
      /** 指定模板路径 */
      File file = new File("templates");
      /** 设置要解析的模板所在的目录,并加载模板文件 */
      config.setDirectoryForTemplateLoading(file);
      /** 设置包装器,并将对象包装为数据模型 */
      config.setObjectWrapper(new DefaultObjectWrapper());

      /** 获取模板,并设置编码方式,这个编码必须要与页面中的编码格式一致 */
      Template template = config.getTemplate(templateName, templateEncoding);
      /** 合并数据模型与模板 */
      Writer out = new OutputStreamWriter(System.out);
      template.process(root, out);
      out.flush();
      out.close();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (TemplateException e) {
      e.printStackTrace();
    }
  }
Exemple #28
0
  /**
   * método que permite generar fichero de metadatos en carpeta separada comprueba si el fichero
   * manifest tiene un lomes integrado o un metadato externo. si el ODE no tiene metadatos.. no
   * genera nada
   */
  private void obtenerLOMES(String lomFileName) throws Exception {
    FileOutputStream fo = null;
    FileInputStream fin = null;
    Writer out = null;
    File lomes = null;
    Template template;
    try {
      if (pathLomesExterno != null) {
        lomes = new File(dirDestino + File.separator + lomFileName);
        if (!lomes.exists()) lomes.createNewFile();
      }

      if (pathLomesExterno != null && pathLomesExterno.equals("")) {
        // tiene lomes y no es un fichero externo adlcp:location
        template = cfg.getTemplate("lomes.ftl");
        cfg.setDefaultEncoding("UTF-8");
        fo = new FileOutputStream(lomes);
        out = new OutputStreamWriter(fo, "UTF-8");
        Environment env = template.createProcessingEnvironment(root, out);
        env.setOutputEncoding("UTF-8");
        env.process();

        out.flush();

      } else if (pathLomesExterno != null
          && !pathLomesExterno.equals(
              "")) { // fichero externo.. por lo que solamente lo copio al destino
        File origen = new File(pathOde + "/" + pathLomesExterno);
        fin = new FileInputStream(origen);
        fo = new FileOutputStream(lomes);
        int c;
        while ((c = fin.read()) >= 0) {
          fo.write(c);
        }
        fin.close();
        fo.close();
        origen = null;
      }
    } catch (Exception e) {
      if (logger.isDebugEnabled()) {
        logger.debug("Error en GeneradorHTML:obtenerLOMES .. " + e.getMessage());
      }
      throw e;
    } finally {
      lomes = null;
      if (fo != null) {
        try {
          fo.close();
        } catch (IOException e) {
        }
      }
      if (fin != null) {
        try {
          fin.close();
        } catch (IOException e) {
        }
      }
    }
  }
 public void process(String resource, Map<String, Object> dataModel, Writer writer) {
   Configuration configuration = configuration();
   try {
     configuration.getTemplate(resource).process(dataModel, writer);
   } catch (Exception e) {
     throw new FreemarkerProcessingFailed(configuration, resource, dataModel, e);
   }
 }
 private Template getTemplate(String fname) {
   try {
     return cfg.getTemplate(fname);
   } catch (IOException e) {
     e.printStackTrace();
   }
   return null;
 }