Example #1
0
 /**
  * @Date:2014年4月26日 下午3:24:37
  *
  * @author 曹志飞
  * @param name 模板文件的名称
  * @param map 与模板内容转换对象
  * @return
  * @throws IOException
  * @throws TemplateException @Description:
  * @return String
  */
 public static String generateHtmlFromFtl(String name, Map<String, String> map)
     throws IOException, TemplateException {
   Writer out = new StringWriter(2048);
   Template temp = getTemplateByName(name);
   temp.setEncoding(ENCODING);
   temp.process(map, out);
   return out.toString();
 }
Example #2
0
 /**
  * 基于文件的输出
  *
  * @param root
  * @param fname
  * @param outpath
  */
 public void fprint(Map<String, Object> root, String fname, String outpath) {
   try {
     Template template = getTemplate(fname);
     template.setEncoding("utf-8");
     template.process(root, new FileWriterWithEncoding(outpath, "utf-8"));
   } catch (TemplateException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Example #3
0
 /**
  * 通过标准输出流输出模板的结果
  *
  * @param root 数据对象
  * @param fname 模板文件
  */
 public void sprint(Map<String, Object> root, String fname) {
   try {
     Template template = getTemplate(fname);
     template.setEncoding("utf-8");
     template.process(root, new PrintWriter(System.out));
   } catch (TemplateException e) {
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Example #4
0
 /**
  * 根据指定模板将内容输出到控制台 @Date:2014年4月26日 下午3:14:18
  *
  * @author 曹志飞
  * @param name 模板文件名称
  * @param map 与模板内容转换对象 @Description:
  * @return void
  */
 public static void outputToConsole(String name, Map<String, String> map) {
   try {
     // 通过Template可以将模板文件输出到相应的流
     Template temp = getTemplateByName(name);
     temp.setEncoding(ENCODING);
     temp.process(map, new PrintWriter(System.out));
   } catch (TemplateException e) {
     log.error(e.toString(), e);
   } catch (IOException e) {
     log.error(e.toString(), e);
   }
 }
Example #5
0
 /**
  * 生成文件
  *
  * @param templateName 模板文件
  * @param fileName 生成文件
  * @param root 参数
  */
 private static void buildFile(String templateName, String fileName, Map root) {
   Configuration freemarkerCfg = new Configuration();
   freemarkerCfg.setClassForTemplateLoading(GenerateJavaFile.class, "/");
   freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
   Template template;
   try {
     template = freemarkerCfg.getTemplate(templateName);
     template.setEncoding("UTF-8");
     File htmlFile = new File(fileName);
     Writer out =
         new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
     template.process(root, out);
     out.flush();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #6
0
 public static void writeFile(
     String configPath, String tempFilePath, String filePath, Map<String, ?> model) {
   Template template;
   try {
     Configuration cfg = FreeMarkers.buildConfiguration(configPath);
     template = cfg.getTemplate(tempFilePath);
     template.setEncoding("utf-8");
     template.process(
         model,
         new BufferedWriter(
             new OutputStreamWriter(new FileOutputStream(new File(filePath)), "utf-8")));
   } catch (IOException e) {
     logger.error("写入文件失败");
     e.printStackTrace();
   } catch (TemplateException e) {
     logger.error("写入文件失败");
     e.printStackTrace();
   }
 }
Example #7
0
 /**
  * 根据指定模板将内容直接输出到文件 @Date:2014年4月26日 下午3:20:15
  *
  * @author 曹志飞
  * @param name 模板文件名称
  * @param map 与模板内容转换对象
  * @param outFile 输出的文件绝对路径 @Description:
  * @return void
  */
 public static void outputToFile(String name, Map<String, String> map, String outFile) {
   FileWriter out = null;
   try {
     out = new FileWriter(new File(outFile));
     Template temp = getTemplateByName(name);
     temp.setEncoding(ENCODING);
     temp.process(map, out);
   } catch (IOException e) {
     log.error(e.toString(), e);
   } catch (TemplateException e) {
     log.error(e.toString(), e);
   } finally {
     try {
       if (out != null) out.close();
     } catch (IOException e) {
       log.error(e.toString(), e);
     }
   }
 }
  /**
   * Dispatch a request and response. A context map is provided for the BlojsomServlet to pass any
   * required information for use by the dispatcher. The dispatcher is also provided with the
   * template for the requested flavor along with the content type for the specific flavor.
   *
   * @param httpServletRequest Request
   * @param httpServletResponse Response
   * @param user {@link org.blojsom.blog.BlogUser} instance
   * @param context Context map
   * @param flavorTemplate Template to dispatch to for the requested flavor
   * @param flavorContentType Content type for the requested flavor
   * @throws java.io.IOException If there is an exception during IO
   * @throws javax.servlet.ServletException If there is an exception in dispatching the request
   */
  public void dispatch(
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      BlogUser user,
      Map context,
      String flavorTemplate,
      String flavorContentType)
      throws IOException, ServletException {
    httpServletResponse.setContentType(flavorContentType);

    String templatePath = getTemplatePath(user.getId());

    // Configure FreeMarker with the loaded properties
    Configuration freemarkerConfiguration = Configuration.getDefaultConfiguration();
    if (_freemarkerProperties != null) {
      try {
        freemarkerConfiguration.setSettings(_freemarkerProperties);
      } catch (TemplateException e) {
        _logger.error(e);
      }
    }
    freemarkerConfiguration.setDirectoryForTemplateLoading(new File(templatePath));

    BeansWrapper wrapper = new BeansWrapper();
    wrapper.setExposureLevel(BeansWrapper.EXPOSE_PROPERTIES_ONLY);
    wrapper.setSimpleMapWrapper(true);
    freemarkerConfiguration.setObjectWrapper(wrapper);

    Writer responseWriter = httpServletResponse.getWriter();
    String flavorTemplateForPage = null;

    if (BlojsomUtils.getRequestValue(PAGE_PARAM, httpServletRequest) != null) {
      flavorTemplateForPage =
          BlojsomUtils.getTemplateForPage(
              flavorTemplate, BlojsomUtils.getRequestValue(PAGE_PARAM, httpServletRequest));
      _logger.debug("Retrieved template for page: " + flavorTemplateForPage);
    }

    if (flavorTemplateForPage != null) {
      // Try and look for the flavor page template for the individual user
      try {
        Template template = freemarkerConfiguration.getTemplate(flavorTemplateForPage);
        template.setEncoding(UTF8);
        template.process(context, responseWriter);
      } catch (Exception e) {
        _logger.error(e);
        return;
      }

      _logger.debug("Dispatched to flavor page template: " + flavorTemplateForPage);
    } else {
      // Otherwise, fallback and look for the flavor template for the individual user
      try {
        Template template = freemarkerConfiguration.getTemplate(flavorTemplate);
        template.setEncoding(UTF8);
        template.process(context, responseWriter);
      } catch (Exception e) {
        _logger.error(e);
        return;
      }

      _logger.debug("Dispatched to flavor template: " + flavorTemplate);
    }

    responseWriter.flush();
  }
  /**
   * Sets the settings of the {@link Template} which are not yet set in the {@link Template} and are
   * set in this {@link TemplateConfigurer}, leaves the other settings as is. A setting is said to
   * be set in a {@link TemplateConfigurer} or {@link Template} if it was explicitly set via a
   * setter method on that object, as opposed to be inherited from the {@link Configuration}.
   *
   * <p>Note that the {@code encoding} setting of the {@link Template} counts as unset if it's
   * {@code null}, even if {@code null} was set via {@link Template#setEncoding(String)}.
   *
   * @throws IllegalStateException If the parent configuration wasn't yet set.
   */
  public void configure(Template template) {
    checkParentConfigurationSet();
    Configuration cfg = getParentConfiguration();
    if (template.getConfiguration() != cfg) {
      // This is actually not a problem right now, but for future BC we enforce this.
      throw new IllegalArgumentException(
          "The argument Template doesn't belong to the same Configuration as the TemplateConfigurer");
    }

    if (isAPIBuiltinEnabledSet() && !template.isAPIBuiltinEnabledSet()) {
      template.setAPIBuiltinEnabled(isAPIBuiltinEnabled());
    }
    if (isArithmeticEngineSet() && !template.isArithmeticEngineSet()) {
      template.setArithmeticEngine(getArithmeticEngine());
    }
    if (isAutoFlushSet() && !template.isAutoFlushSet()) {
      template.setAutoFlush(getAutoFlush());
    }
    if (isBooleanFormatSet() && !template.isBooleanFormatSet()) {
      template.setBooleanFormat(getBooleanFormat());
    }
    if (isClassicCompatibleSet() && !template.isClassicCompatibleSet()) {
      template.setClassicCompatibleAsInt(getClassicCompatibleAsInt());
    }
    if (isDateFormatSet() && !template.isDateFormatSet()) {
      template.setDateFormat(getDateFormat());
    }
    if (isDateTimeFormatSet() && !template.isDateTimeFormatSet()) {
      template.setDateTimeFormat(getDateTimeFormat());
    }
    if (isEncodingSet() && template.getEncoding() == null) {
      template.setEncoding(getEncoding());
    }
    if (isLocaleSet() && !template.isLocaleSet()) {
      template.setLocale(getLocale());
    }
    if (isLogTemplateExceptionsSet() && !template.isLogTemplateExceptionsSet()) {
      template.setLogTemplateExceptions(getLogTemplateExceptions());
    }
    if (isNewBuiltinClassResolverSet() && !template.isNewBuiltinClassResolverSet()) {
      template.setNewBuiltinClassResolver(getNewBuiltinClassResolver());
    }
    if (isNumberFormatSet() && !template.isNumberFormatSet()) {
      template.setNumberFormat(getNumberFormat());
    }
    if (isObjectWrapperSet() && !template.isObjectWrapperSet()) {
      template.setObjectWrapper(getObjectWrapper());
    }
    if (isOutputEncodingSet() && !template.isOutputEncodingSet()) {
      template.setOutputEncoding(getOutputEncoding());
    }
    if (isShowErrorTipsSet() && !template.isShowErrorTipsSet()) {
      template.setShowErrorTips(getShowErrorTips());
    }
    if (isSQLDateAndTimeTimeZoneSet() && !template.isSQLDateAndTimeTimeZoneSet()) {
      template.setSQLDateAndTimeTimeZone(getSQLDateAndTimeTimeZone());
    }
    if (isTemplateExceptionHandlerSet() && !template.isTemplateExceptionHandlerSet()) {
      template.setTemplateExceptionHandler(getTemplateExceptionHandler());
    }
    if (isTimeFormatSet() && !template.isTimeFormatSet()) {
      template.setTimeFormat(getTimeFormat());
    }
    if (isTimeZoneSet() && !template.isTimeZoneSet()) {
      template.setTimeZone(getTimeZone());
    }
    if (isURLEscapingCharsetSet() && !template.isURLEscapingCharsetSet()) {
      template.setURLEscapingCharset(getURLEscapingCharset());
    }

    copyDirectCustomAttributes(template, false);
  }
  private void handleResult() throws Exception {

    this.exeActionLog();

    if (retn == null) return;
    String baseUrl =
        (String) this.context.getServletContext().getAttribute(MVCConfigConstant.BASE_URL_KEY);
    if (File.class.isAssignableFrom(retn.getClass())) {
      File file = (File) retn;
      this.handleDownload(file);
      return;
    } else if (File[].class.isAssignableFrom(retn.getClass())) {
      File[] files = (File[]) retn;

      String fileName = CommonUtil.getNowTime("yyyyMMddHHmmss") + "_" + "download.zip";

      HttpServletResponse resp = this.context.getResponse();
      resp.reset();
      resp.setContentType("application/zip");
      resp.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

      ServletOutputStream outputStream = resp.getOutputStream();
      ZipOutputStream zip = new ZipOutputStream(outputStream);

      for (File file : files) {
        byte[] b = new byte[1024];
        int len;
        zip.putNextEntry(new ZipEntry(file.getName()));
        FileInputStream fis = new FileInputStream(file);
        while ((len = fis.read(b)) != -1) {
          zip.write(b, 0, len);
        }

        fis.close();
      }

      zip.flush();
      zip.close();
      outputStream.flush();

      return;
    }

    if (!String.class.isAssignableFrom(retn.getClass())) {
      String mimeType = null;
      Produces prod = this.method.getAnnotation(Produces.class);
      if (prod != null && prod.value() != null && prod.value().length > 0)
        mimeType = prod.value()[0];

      if (mimeType == null || mimeType.trim().length() == 0)
        mimeType =
            this.context.getRequest().getParameter(MVCConfigConstant.HTTP_HEADER_ACCEPT_PARAM);

      if (mimeType == null || mimeType.trim().length() == 0) {
        String contentType = this.context.getRequest().getContentType();
        if (contentType != null) {
          this.context.getResponse().setContentType(contentType);
          mimeType = contentType.split(";")[0];
        }
      }

      if (this.context.getWriter() == null)
        this.context.setWriter(this.context.getResponse().getWriter());

      if (MIMEType.JSON.equals(mimeType) || "json".equalsIgnoreCase(mimeType)) {
        this.context.getResponse().setContentType(MIMEType.JSON);
        this.context.getWriter().print(CommonUtil.toJson(retn));
      } else if (MIMEType.XML.equals(mimeType) || "xml".equalsIgnoreCase(mimeType)) {
        Class<?> cls = retn.getClass();
        if (Collection.class.isAssignableFrom(cls)) {
          Class<?> _cls = ClassUtil.getPojoClass(this.method);
          if (_cls != null) cls = _cls;
        }

        XMLWriter writer = BeanXMLUtil.getBeanXMLWriter(retn);
        writer.setCheckStatck(true);
        writer.setSubNameAuto(true);
        writer.setClass(cls);
        writer.setRootElementName(null);
        this.context.getResponse().setContentType(MIMEType.XML);
        this.context.getWriter().print(writer.toXml());
      } else {
        this.context.getWriter().print("暂时不支持JSON 、XML以外的表述形式");
      }

      this.context.getWriter().flush();

      return;
    }

    List<String> produces = this.context.getActionConfigBean().getProduces();
    if (produces != null && produces.size() > 0)
      for (String produce : produces) {
        this.context.getResponse().setContentType(produce);
        break;
      }

    String re = String.valueOf(retn);

    for (Field f : fields) {
      Method getter = ru.getGetter(f.getName());
      if (getter == null) continue;

      String name = f.getName();
      if (this.context.getModel().containsKey(name)) continue;

      this.context.getModel().put(name, getter.invoke(actionObject));
    }

    this.context.getModel().put(MVCConfigConstant.BASE_URL_KEY, baseUrl);

    // 客户端重定向
    if (re.startsWith(RenderType.REDIRECT + ":")) {
      String url = re.substring((RenderType.REDIRECT + ":").length());
      String location = url;

      this.context.getResponse().sendRedirect(CommonUtil.replaceChinese2Utf8(location));

      return;
    } else if (re.startsWith(RenderType.ACTION + ":")) {
      String path = re.substring((RenderType.ACTION + ":").length());
      // ACTION 重定向
      handleActionRedirect(context, path, baseUrl);

      return;
    } else if (re.startsWith(RenderType.OUT + ":")) {
      String location = re.substring((RenderType.OUT + ":").length());
      this.context.getWriter().print(location);
      this.context.getWriter().flush();

      return;
    } else if (re.startsWith(RenderType.FORWARD + ":")) {
      String location = re.substring((RenderType.FORWARD + ":").length());
      HttpServletRequest request = this.context.getRequest();
      request.setAttribute(MVCConfigConstant.REQ_PARAM_MAP_NAME, this.context.getQueryParamMap());

      for (Iterator<Entry<String, Object>> it = this.context.getModel().entrySet().iterator();
          it.hasNext(); ) {
        Entry<String, Object> entry = it.next();
        request.setAttribute(entry.getKey(), entry.getValue());
      }

      // 服务端跳转
      request
          .getRequestDispatcher(MVCConfigConstant.FORWARD_BASE_PATH + "/" + location)
          .forward(request, this.context.getResponse());

      return;
    } else if (re.startsWith(RenderType.FREEMARKER + ":")) {
      String location = re.substring((RenderType.FREEMARKER + ":").length());
      // FreeMarker 渲染
      Configuration cfg = new Configuration();
      // 指定模板从何处加载的数据源,这里设置成一个文件目录。
      cfg.setDirectoryForTemplateLoading(
          new File(ConfigConstant.ROOT_PATH + MVCConfigConstant.FORWARD_BASE_PATH));
      // 指定模板如何检索数据模型
      cfg.setObjectWrapper(new DefaultObjectWrapper());
      cfg.setDefaultEncoding("utf-8");

      Template template = cfg.getTemplate(location);
      template.setEncoding("utf-8");

      template.process(this.context.getModel(), this.context.getWriter());

      return;
    } else if (re.startsWith(RenderType.VELOCITY + ":")) {
      String location = re.substring((RenderType.VELOCITY + ":").length());
      File viewsDir = new File(ConfigConstant.ROOT_PATH + MVCConfigConstant.FORWARD_BASE_PATH);
      // 初始化Velocity模板引擎
      Properties p = new Properties();
      p.setProperty("resource.loader", "file");
      p.setProperty(
          "file.resource.loader.class",
          "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
      p.setProperty("file.resource.loader.path", viewsDir.getAbsolutePath());
      p.setProperty("file.resource.loader.cache", "true");
      p.setProperty("file.resource.loader.modificationCheckInterval", "2");
      p.setProperty("input.encoding", "utf-8");
      p.setProperty("output.encoding", "utf-8");
      VelocityEngine ve = new VelocityEngine(p);
      // Velocity获取模板文件,得到模板引用
      org.apache.velocity.Template t = ve.getTemplate(location);
      VelocityContext velocityCtx = new VelocityContext();
      for (Iterator<Entry<String, Object>> it = this.context.getModel().entrySet().iterator();
          it.hasNext(); ) {
        Entry<String, Object> e = it.next();
        velocityCtx.put(e.getKey(), e.getValue());
      }

      // 将环境变量和输出部分结合
      t.merge(velocityCtx, this.context.getWriter());
      this.context.getWriter().flush();
      return;
    } else {
      List<ResultConfigBean> results = this.context.getActionConfigBean().getResult();

      if (results == null || results.size() == 0) {
        this.context.getWriter().print(retn);
        this.context.getWriter().flush();
        return;
      }

      boolean isOut = true;
      for (ResultConfigBean r : results) {
        if (!"_props_".equals(r.getName()) && !r.getName().equals(re) && !"".equals(re)) {
          continue;
        }

        isOut = false;
        String type = r.getType();
        String location = r.getLocation();
        if (RenderType.REDIRECT.equalsIgnoreCase(type)) {
          this.context.getResponse().sendRedirect(CommonUtil.replaceChinese2Utf8(location));

          return;
        } else if (RenderType.FORWARD.equalsIgnoreCase(type)) {
          HttpServletRequest request = this.context.getRequest();
          request.setAttribute(
              MVCConfigConstant.REQ_PARAM_MAP_NAME, this.context.getQueryParamMap());

          fields = ru.getFields();
          if (fields == null) return;

          for (Iterator<Entry<String, Object>> it = this.context.getModel().entrySet().iterator();
              it.hasNext(); ) {
            Entry<String, Object> entry = it.next();
            request.setAttribute(entry.getKey(), entry.getValue());
          }
          // 服务端跳转
          request
              .getRequestDispatcher(MVCConfigConstant.FORWARD_BASE_PATH + location)
              .forward(request, this.context.getResponse());

          return;
        } else if (RenderType.FREEMARKER.equalsIgnoreCase(type)) {
          // FreeMarker 渲染
          Configuration cfg = new Configuration();
          // 指定模板从何处加载的数据源,这里设置成一个文件目录。
          cfg.setDirectoryForTemplateLoading(
              new File(ConfigConstant.ROOT_PATH + MVCConfigConstant.FORWARD_BASE_PATH));
          // 指定模板如何检索数据模型
          cfg.setObjectWrapper(new DefaultObjectWrapper());
          cfg.setDefaultEncoding("utf-8");

          Template template = cfg.getTemplate(location);
          template.setEncoding("utf-8");

          template.process(this.context.getModel(), this.context.getWriter());

          return;
        } else if (RenderType.ACTION.equalsIgnoreCase(type)) {
          // ACTION 重定向
          handleActionRedirect(context, location, baseUrl);

          return;
        } else if (RenderType.OUT.equalsIgnoreCase(type) || location.trim().length() == 0) {
          this.context.getWriter().print(location);
          this.context.getWriter().flush();

          return;
        }
      }

      if (isOut) {
        this.context.getWriter().print(retn);
        this.context.getWriter().flush();
      }
    }
  }