@Transactional(readOnly = true)
  public int build(String templatePath, String staticPath, Map<String, Object> model) {
    Assert.hasText(templatePath);
    Assert.hasText(staticPath);

    FileOutputStream fileOutputStream = null;
    OutputStreamWriter outputStreamWriter = null;
    Writer writer = null;
    try {
      freemarker.template.Template template =
          freeMarkerConfigurer.getConfiguration().getTemplate(templatePath);
      File staticFile = new File(servletContext.getRealPath(staticPath));
      File staticDirectory = staticFile.getParentFile();
      if (!staticDirectory.exists()) {
        staticDirectory.mkdirs();
      }
      fileOutputStream = new FileOutputStream(staticFile);
      outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
      writer = new BufferedWriter(outputStreamWriter);
      template.process(model, writer);
      writer.flush();
      return 1;
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      IOUtils.closeQuietly(writer);
      IOUtils.closeQuietly(outputStreamWriter);
      IOUtils.closeQuietly(fileOutputStream);
    }
    return 0;
  }
Example #2
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);
  }
Example #3
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;
    }
  }
Example #4
0
  /**
   * @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();
    }
  }
Example #5
0
  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();
  }
  @Override
  public void generate(Model model, MolgenisOptions options) throws Exception {
    if (options.generate_tests) {
    } else {
      Template template =
          this.createTemplate(this.getClass().getSimpleName() + getExtension() + ".ftl");
      Map<String, Object> templateArgs = createTemplateArguments(options);

      // apply generator to each entity
      for (Entity entity : model.getEntities()) {
        // calculate package from its own package
        String packageName =
            entity.getNamespace().toLowerCase()
                + this.getClass()
                    .getPackage()
                    .toString()
                    .substring(Generator.class.getPackage().toString().length());

        File targetDir =
            new File(
                (this.getSourcePath(options).endsWith("/")
                        ? this.getSourcePath(options)
                        : this.getSourcePath(options) + "/")
                    + packageName.replace(".", "/").replace("/cpp", ""));
        try {
          File targetFile =
              new File(
                  targetDir + "/" + GeneratorHelper.getJavaName(entity.getName()) + getExtension());
          boolean created = targetDir.mkdirs();
          if (!created && !targetDir.exists()) {
            throw new IOException("could not create " + targetDir);
          }

          // logger.debug("trying to generated "+targetFile);
          templateArgs.put("entity", entity);
          templateArgs.put("model", model);
          templateArgs.put("db_driver", options.db_driver);
          templateArgs.put("template", template.getName());
          templateArgs.put(
              "file",
              targetDir.getCanonicalPath().replace("\\", "/")
                  + "/"
                  + GeneratorHelper.firstToUpper(entity.getName())
                  + getType()
                  + getExtension());
          templateArgs.put("package", packageName);

          OutputStream targetOut = new FileOutputStream(targetFile);

          template.process(
              templateArgs, new OutputStreamWriter(targetOut, Charset.forName("UTF-8")));
          targetOut.close();
          logger.info("generated " + targetFile);
        } catch (Exception e) {
          logger.error("problem generating for " + entity.getName());
          throw e;
        }
      }
    }
  }
 private void readArrayField(Field field, ArrayType array) {
   String elTypeJavaName = TypeNameEmitter.getTypeName(array);
   if (elTypeJavaName.startsWith("ObjectArray")) {
     try {
       ArrayEmitter ae = new ArrayEmitter(field, array, this);
       Template tpl = global.getTemplateConfig().getTemplate("java/ArrayRead.ftl");
       tpl.process(ae, writer);
     } catch (TemplateException exc) {
       throw new DataScriptException(exc);
     } catch (IOException exc) {
       throw new DataScriptException(exc);
     }
   } else {
     Expression length = array.getLengthExpression();
     TypeInterface elType = array.getElementType();
     if (elType instanceof EnumType) {
       EnumType enumType = (EnumType) elType;
       readEnumField(field, enumType);
     } else {
       buffer.append(AccessorNameEmitter.getSetterName(field));
       buffer.append("(new ");
       buffer.append(elTypeJavaName);
       buffer.append("(__in, (int)(");
       buffer.append(getLengthExpression(length));
       buffer.append(")");
       if (elType instanceof BitFieldType) {
         BitFieldType bitField = (BitFieldType) elType;
         Expression numBits = bitField.getLengthExpression();
         buffer.append(", ");
         buffer.append(getLengthExpression(numBits));
       }
     }
     buffer.append("));");
   }
 }
Example #8
0
 /**
  * 读取邮件内容
  *
  * @param model
  * @param templateFile
  * @return
  */
 public String getTemplate(Map<String, Object> model, String templateFile, String templatePath) {
   Template temp = null;
   Writer out = null;
   try {
     temp = cfg(templatePath).getTemplate(templateFile);
     ByteArrayOutputStream bos = new ByteArrayOutputStream();
     out = new OutputStreamWriter(bos);
     temp.process(model, out);
     String content = bos.toString();
     out.close();
     return content;
   } catch (IOException e) {
     logger.error("IO错误", e);
   } catch (TemplateException e) {
     logger.error("模板错误", e);
   } finally {
     if (out != null) {
       try {
         out.close();
       } catch (IOException e) {
         logger.error("IO错误", e);
       }
     }
   }
   return "";
 }
Example #9
0
  /**
   * 根据模板内容生成Html内容
   *
   * @param templateContent freemarker模板内容
   * @param paramMap freemarker模板参数600876 600850
   * @return
   * @throws IOException
   * @throws TemplateException
   */
  @SuppressWarnings("unchecked")
  public static String parseTemplate(String templateContent, Map paramMap)
      throws IOException, TemplateException {
    Template template =
        new Template(null, new StringReader(templateContent), TemplateParser.cfg("/"));
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    OutputStreamWriter out = new OutputStreamWriter(bos);
    try {
      template.process(paramMap, out);
      return bos.toString();
    } catch (TemplateException e) {
      throw e;
    } catch (IOException e) {
      throw e;
    } finally {
      try {
        out.close();
      } catch (IOException e) {

      } finally {
        out = null;
      }

      try {
        bos.close();
      } catch (IOException e) {

      } finally {
        bos = null;
      }
    }
  }
Example #10
0
  // 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();
    }
  }
  private void displayStartupStatus(ServletRequest req, ServletResponse resp)
      throws IOException, ServletException {
    HttpServletResponse hresp = (HttpServletResponse) resp;
    HttpServletRequest hreq = (HttpServletRequest) req;

    try {
      Map<String, Object> bodyMap = new HashMap<String, Object>();
      bodyMap.put("status", ss);
      bodyMap.put("showLink", !isFatal());
      bodyMap.put("contextPath", getContextPath());
      bodyMap.put("applicationName", getApplicationName());

      String url = "";

      String path = hreq.getRequestURI();
      if (path != null) {
        url = path;
      }

      String query = hreq.getQueryString();
      if (!StringUtils.isEmpty(query)) {
        url = url + "?" + query;
      }

      bodyMap.put("url", url);

      hresp.setContentType("text/html;charset=UTF-8");
      hresp.setStatus(SC_INTERNAL_SERVER_ERROR);
      Template tpl = loadFreemarkerTemplate();
      tpl.process(bodyMap, hresp.getWriter());
    } catch (TemplateException e) {
      throw new ServletException("Problem with Freemarker Template", e);
    }
  }
Example #12
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);
    }
  }
Example #13
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);
  }
Example #14
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);
  }
  /**
   * @see org.opencms.frontend.layoutpage.I_CmsMacroWrapper#getResult(java.lang.String,
   *     java.lang.String[])
   */
  public String getResult(String macroName, String[] args) {

    Writer out = new StringWriter();
    boolean error = false;
    try {
      // get the macro object to process
      Macro macro = (Macro) m_template.getMacros().get(macroName);
      if (macro != null) {
        // found macro, put it context
        putContextVariable(MACRO_NAME, macro);
        // process the template
        m_template.process(getContext(), out);
      } else {
        // did not find macro
        error = true;
      }
    } catch (Exception e) {
      if (LOG.isErrorEnabled()) {
        LOG.error(e.getLocalizedMessage(), e);
      }
      error = true;
    } finally {
      try {
        out.close();
      } catch (Exception e) {
        // ignore exception when closing writer
      }
    }
    if (error) {
      return "";
    }
    return out.toString();
  }
Example #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) {
       }
     }
   }
 }
  protected boolean preTemplateProcess(Template template, TemplateModel model) throws IOException {
    Object attrContentType = template.getCustomAttribute("content_type");

    if (attrContentType != null) {
      ServletActionContext.getResponse().setContentType(attrContentType.toString());
    } else {
      String contentType = getContentType();

      if (contentType == null) {
        contentType = "text/html";
      }

      // webwork:
      //            String encoding = template.getEncoding();

      String encoding = template.getOutputEncoding();

      if (encoding != null) {
        contentType = contentType + "; charset=" + encoding;
      }

      ServletActionContext.getResponse().setContentType(contentType);
    }

    return true;
  }
Example #18
0
  @Override
  public void generate(Model model, MolgenisOptions options) throws Exception {
    Template template = createTemplate("/" + this.getClass().getSimpleName() + ".java.ftl");
    Map<String, Object> templateArgs = createTemplateArguments(options);

    List<Entity> entityList = model.getEntities();
    entityList = MolgenisModel.sortEntitiesByDependency(entityList, model); // side
    // effect?

    File target = new File(this.getSourcePath(options) + "/test/TestDataSet.java");
    boolean created = target.getParentFile().mkdirs();
    if (!created && !target.getParentFile().exists()) {
      throw new IOException("could not create " + target.getParentFile());
    }

    String packageName = "test";

    templateArgs.put(
        "databaseImp",
        options.mapper_implementation.equals(MolgenisOptions.MapperImplementation.JPA)
            ? "jpa"
            : "jdbc");
    templateArgs.put("model", model);
    templateArgs.put("entities", entityList);
    templateArgs.put("package", packageName);

    OutputStream targetOut = new FileOutputStream(target);
    template.process(templateArgs, new OutputStreamWriter(targetOut, Charset.forName("UTF-8")));
    targetOut.close();

    logger.info("generated " + target);
  }
  @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));
    }
  }
Example #20
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;
  }
Example #21
0
  public String proessPageContent() {

    try {
      String name = this.clazz.getSimpleName();
      pageExt = pageExt == null ? ".html" : pageExt;
      name = this.pageName == null ? name : pageName;

      cfg = this.getCfg();
      cfg.setNumberFormat("0.##");
      Template temp = cfg.getTemplate(name + pageExt);
      ByteOutputStream stream = new ByteOutputStream();
      Writer out = new OutputStreamWriter(stream);
      temp.process(data, out);
      out.flush();
      String content = stream.toString();

      if (wrapPath) {
        // System.out.println("before:---------------------------");
        // System.out.println(content);

        content = EopUtil.wrapjavascript(content, this.getResPath());
        content = EopUtil.wrapcss(content, getResPath());
        // System.out.println("after:---------------------------");
        // System.out.println(content);
      }
      // content= StringUtil.compressHtml(content);
      return content;
    } catch (IOException e) {
      e.printStackTrace();
    } catch (TemplateException e) {
      e.printStackTrace();
    }

    return "widget  processor error";
  }
  /* (non-Javadoc)
   * @see org.alfresco.web.scripts.TemplateProcessor#processString(java.lang.String, java.lang.Object, java.io.Writer)
   */
  public void processString(String template, Object model, Writer out) {
    if (template == null || template.length() == 0) {
      throw new IllegalArgumentException("Template is mandatory.");
    }
    if (model == null) {
      throw new IllegalArgumentException("Model is mandatory.");
    }
    if (out == null) {
      throw new IllegalArgumentException("Output Writer is mandatory.");
    }

    long startTime = 0;
    if (logger.isDebugEnabled()) {
      logger.debug("Executing template: " + template);
      startTime = System.nanoTime();
    }

    addProcessorModelExtensions(model);

    try {
      Template t = new Template("name", new StringReader(template), stringConfig);
      t.process(model, out);

      if (logger.isDebugEnabled()) {
        long endTime = System.nanoTime();
        logger.debug("Time to execute template: " + (endTime - startTime) / 1000000f + "ms");
      }
    } catch (Throwable err) {
      throw new WebScriptException("Failed to process template " + template, err);
    }
  }
  @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);
    }
  }
  public String processarModelo(
      CpOrgaoUsuario ou, Map<String, Object> attrs, Map<String, Object> params) throws Exception {
    // Create the root hash
    Map root = new HashMap();
    root.put("root", root);

    root.putAll(attrs);
    root.put("param", params);

    String sTemplate = "[#compress]\n[#include \"GERAL\"]\n";
    if (ou != null) {
      sTemplate += "[#include \"" + ou.getAcronimoOrgaoUsu() + "\"]";
    }
    sTemplate += "\n" + (String) attrs.get("template") + "\n[/#compress]";

    Template temp = new Template((String) attrs.get("nmMod"), new StringReader(sTemplate), cfg);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Writer out = new OutputStreamWriter(baos);
    try {
      temp.process(root, out);
    } catch (TemplateException e) {
      return (e.getMessage() + "\n" + e.getFTLInstructionStack())
          .replace("\n", "<br/>")
          .replace("\r", "");
    } catch (IOException e) {
      return e.getMessage();
    }
    out.flush();
    return baos.toString();
  }
  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();
    }
  }
Example #26
0
  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;
  }
 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 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();
  }
  @Override
  @SuppressWarnings({"unchecked", "rawtypes"})
  public void render() {
    response.setContentType(CONTENT_TYPE);

    Enumeration<String> attrs = request.getAttributeNames();
    Map root = new HashMap();
    while (attrs.hasMoreElements()) {
      String attrName = attrs.nextElement();
      root.put(attrName, request.getAttribute(attrName));
    }

    Writer writer = null;
    try {
      writer = response.getWriter();
      Template template = getConfiguration().getTemplate(view);
      template.process(root, writer); // Merge the data-model and the template
    } catch (Exception e) {
      throw new RenderException(e);
    } finally {
      try {
        if (writer != null) {
          writer.close();
        }
      } catch (IOException e) {
        Throwables.propagate(e);
      }
    }
  }
Example #30
0
  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.
  }