/** Initialise FreeMarker Configuration */ protected void initConfig() { // construct template config Configuration config = new Configuration(); ObjectWrapper objectWrapper = new NonBlockingObjectWrapper(); config.setObjectWrapper(objectWrapper); config.setCacheStorage(new StrongCacheStorage()); config.setTemplateUpdateDelay(isDebugMode() == false ? updateDelay : 0); config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); config.setLocalizedLookup(false); config.setOutputEncoding("UTF-8"); if (defaultEncoding != null) { config.setDefaultEncoding(defaultEncoding); } config.setIncompatibleImprovements(new Version(2, 3, 20)); if (getTemplateLoader() != null) { config.setTemplateLoader(getTemplateLoader()); } config.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER); templateConfig = config; // construct string config stringConfig = new Configuration(); stringConfig.setObjectWrapper(objectWrapper); stringConfig.setCacheStorage(new MruCacheStorage(2, 0)); stringConfig.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); stringConfig.setOutputEncoding("UTF-8"); if (defaultEncoding != null) { stringConfig.setDefaultEncoding(defaultEncoding); } stringConfig.setIncompatibleImprovements(new Version(2, 3, 20)); stringConfig.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER); }
/** * 模版配置 * * @param resource * @return */ private static Configuration getConfig(String resource) { Configuration cfg = new Configuration(); cfg.setDefaultEncoding("UTF-8"); cfg.setClassForTemplateLoading(DbTableProcess.class, resource); return cfg; }
public static Configuration buildConfiguration(String directory) throws IOException { Configuration cfg = new Configuration(); Resource path = new DefaultResourceLoader().getResource(directory); cfg.setDirectoryForTemplateLoading(path.getFile()); cfg.setDefaultEncoding("utf-8"); return cfg; }
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(); } }
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 void generate() throws Exception { Configuration conf = new Configuration(); conf.setDefaultEncoding("UTF-8"); conf.setClassForTemplateLoading(this.getClass(), "../../../../../../"); Map root = new HashedMap(); Entity entity = (Entity) getModel(); root.put("entity", entity); File file = new File( System.getProperty("src.path") + StringUtils.replace(entity.getPackageDeclaration(), ".", File.separator)); if (!file.exists()) { file.mkdirs(); } getTemplate(conf) .process( root, new OutputStreamWriter( new FileOutputStream( file.getAbsolutePath() + File.separator + entity.getDeclarationName() + JAVA_EXTENSION), conf.getDefaultEncoding())); }
/** * 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 static FreemarkerUtil getInstance(String pname) { if (util == null) { cfg = new Configuration(); cfg.setClassForTemplateLoading(FreemarkerUtil.class, pname); cfg.setDefaultEncoding("utf-8"); util = new FreemarkerUtil(); } return util; }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ClassNotFoundException, SQLException, TemplateException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); Configuration c = new Configuration(); c.setDefaultEncoding("ISO-8859-1"); // setta il decoding della pagina in ingresso c.setOutputEncoding("ISO-8859-1"); // in output c.setNumberFormat(""); // per i numeri in virgola mobile e non c.setObjectWrapper( ObjectWrapper.BEANS_WRAPPER); // fa si che se voi passate al template un oggetto // viene visto come un associazione chiave valore da usare nel template c.setServletContextForTemplateLoading( getServletContext(), "templates"); // vatti a caricare questo template in base al contesto c c.setTemplateExceptionHandler( TemplateExceptionHandler .IGNORE_HANDLER); // handler di errori (default:statti zitto) cambia se vuoi debuggare // carica il template(il template non si reinderizza senza modellodati!) Template t = c.getTemplate("add_invitato.ftl.html"); Map<String, Object> data = new HashMap<String, Object>(); if (request.getSession(false) == null) { response.sendRedirect("index"); } if (request.getSession(false) != null) { data.put("login", 1); HttpSession s = request.getSession(false); int idtipo = (Integer) s.getAttribute("idtipo"); String username = (String) s.getAttribute("usersession"); int idutente = (Integer) s.getAttribute("idutente"); data.put("username", username); DataLayer dl = new DataLayerImpl(); UtenteDataLayer udl = dl.getUtenteDataLayer(dl.getC()); Utente utente = udl.readUtente(idutente); if (idtipo == 1) { data.put("tipo", "1"); // setta pannello admin } if (idtipo == 2) { data.put("tipo", "2"); // setta pannello organizzatore } String tmp = request.getParameter("id"); int idevento = Integer.parseInt(tmp); InvitatoDataLayer idl = dl.getInvitatoDataLayer(dl.getC()); List<Invitato> lista = idl.getRubricaAndInvitati(idutente, idevento); data.put("invitati", lista); data.put("idevento", idevento); } try { t.process(data, response.getWriter()); } finally { out.close(); } }
private FreemarkerHandler(HttpServlet servlet) throws IOException { this.servlet = servlet; this.root = new HashMap(); // initialization, do only once cfg = new Configuration(Configuration.VERSION_2_3_22); cfg.setDirectoryForTemplateLoading(new File(servlet.getServletContext().getRealPath("/"))); cfg.setDefaultEncoding("UTF-8"); }
@Override public void initialize() throws InitializationException { m_configuration = new Configuration(); m_configuration.setDefaultEncoding("UTF-8"); try { m_configuration.setClassForTemplateLoading(this.getClass(), "/freemaker"); } catch (Exception e) { Cat.logError(e); } }
public static Configuration getConfiguration(String templateDir) throws IOException { if (null == cfg) { cfg = new Configuration(); File templateDirFile = new File(templateDir); cfg.setDirectoryForTemplateLoading(templateDirFile); cfg.setLocale(Locale.CHINA); cfg.setDefaultEncoding("UTF-8"); } return cfg; }
public void render() throws IOException { Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); cfg.setClassLoaderForTemplateLoading(getClass().getClassLoader(), "/"); renderPersistence(cfg); renderContentProvider(cfg); renderDbHelper(cfg); renderModels(cfg); renderMappers(cfg); }
@Bean public freemarker.template.Configuration freemakerConfig() throws IOException, URISyntaxException { freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_22); cfg.setDirectoryForTemplateLoading( Paths.get(this.getClass().getClassLoader().getResource("/template").toURI()).toFile()); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); return cfg; }
public CCodeGenerator() throws TemplateModelException { config.setDefaultEncoding("UTF-8"); config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); config.setClassForTemplateLoading(CCodeGenerator.class, "/templates"); config.setSharedVariable("cTypeHelper", C_TypeHelper.getInstance()); config.setSharedVariable("enumHelper", EnumHelper.getInstance()); config.setSharedVariable("requestHelper", RequestHelper.getInstance()); config.setSharedVariable("helper", Helper.getInstance()); config.setSharedVariable("structHelper", StructHelper.getInstance()); config.setSharedVariable("structMemberHelper", StructMemberHelper.getInstance()); config.setSharedVariable("parameterHelper", ParameterHelper.getInstance()); }
@Test public void freeMarkerTest() throws IOException, TemplateException { Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); cfg.setDirectoryForTemplateLoading(new File("D:/template/")); cfg.setDefaultEncoding("UTF-8"); Template template = cfg.getTemplate("test.xml"); Writer writer = new FileWriter(new File("d:/test.xls")); Map<String, Object> data = new HashMap<>(); data.put("area", "A区"); data.put("code", "A001"); data.put("row", 2); template.process(data, writer); }
public Server(int port, String host) throws IOException { this.port = port; this.host = host; Configuration cfg = new Configuration(Configuration.VERSION_2_3_23); cfg.setClassLoaderForTemplateLoading(Server.class.getClassLoader(), "templates"); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER); indexTemplate = cfg.getTemplate("index.html"); messages = new ArrayList<Message>(); serializer = new Persister(); }
public static Configuration getConfiguration() throws SQLException, TemplateModelException, IOException { if (cfg == null) { cfg = new Configuration(new Version("2.3.23")); cfg.setDefaultEncoding("UTF-8"); cfg.setSharedVariable( "portalAddr", SystemConfigDao.getSystemConfig(Config.TemplateInfo.CONFIG_ID)); // 获取资源路径 String classPath = cfg.getClass().getResource("/").getFile().toString(); cfg.setDirectoryForTemplateLoading(new File(classPath)); } return cfg; }
public static Configuration getCfg() { if (cfg == null) { cfg = new Configuration(); cfg.setTemplateUpdateDelay(6000); cfg.setCacheStorage(new freemarker.cache.MruCacheStorage(20, 250)); DateFormateDirectiveModel df = new DateFormateDirectiveModel(); cfg.setSharedVariable("dateFormat", df); cfg.setObjectWrapper(new DefaultObjectWrapper()); cfg.setDefaultEncoding("UTF-8"); cfg.setLocale(java.util.Locale.CHINA); cfg.setEncoding(java.util.Locale.CHINA, "UTF-8"); } return cfg; }
@Override public void generate(Book book, File directory) throws IOException { Configuration cfg = new Configuration(); cfg.setDirectoryForTemplateLoading(templateDir); cfg.setObjectWrapper(new BeansWrapper()); cfg.setDefaultEncoding("UTF-8"); writeBibTex(directory); StringBuffer latex = new BookToLatex(parser).generateLatex(book, cfg, ifdefs); // print the latex document to an archive File fileBook = new File(directory, latexOutputFileName); PrintStream stream = new PrintStream(fileBook, "UTF-8"); stream.append(latex); stream.close(); copyResources(directory, book); }
private void writeHtmlOverviewFile() { File benchmarkReportDirectory = plannerBenchmarkResult.getBenchmarkReportDirectory(); WebsiteResourceUtils.copyResourcesTo(benchmarkReportDirectory); htmlOverviewFile = new File(benchmarkReportDirectory, "index.html"); Configuration freemarkerCfg = new Configuration(); freemarkerCfg.setDefaultEncoding("UTF-8"); freemarkerCfg.setLocale(locale); freemarkerCfg.setClassForTemplateLoading(BenchmarkReport.class, ""); String templateFilename = "benchmarkReport.html.ftl"; Map<String, Object> model = new HashMap<String, Object>(); model.put("benchmarkReport", this); model.put("reportHelper", new ReportHelper()); Writer writer = null; try { Template template = freemarkerCfg.getTemplate(templateFilename); writer = new OutputStreamWriter(new FileOutputStream(htmlOverviewFile), "UTF-8"); template.process(model, writer); } catch (IOException e) { throw new IllegalArgumentException( "Can not read templateFilename (" + templateFilename + ") or write htmlOverviewFile (" + htmlOverviewFile + ").", e); } catch (TemplateException e) { throw new IllegalArgumentException( "Can not process Freemarker templateFilename (" + templateFilename + ") to htmlOverviewFile (" + htmlOverviewFile + ").", e); } finally { IOUtils.closeQuietly(writer); } }
private Configuration getCfg() { if (cfg == null) { cfg = FreeMarkerUtil.getCfg(); } pathPrefix = pathPrefix == null ? "" : pathPrefix; if (pageFolder == null) { // 默认使用挂件所在文件夹 // System.out.println(" folder null use "+ this.clazz.getName() ); cfg.setClassForTemplateLoading(this.clazz, pathPrefix); } else { // System.out.println(" folder not null use "+ pageFolder); cfg.setServletContextForTemplateLoading( ThreadContextHolder.getHttpRequest().getSession().getServletContext(), pageFolder); } cfg.setObjectWrapper(new DefaultObjectWrapper()); cfg.setDefaultEncoding("UTF-8"); cfg.setLocale(java.util.Locale.CHINA); cfg.setEncoding(java.util.Locale.CHINA, "UTF-8"); return cfg; }
private void build(Writer writer) throws Exception { InputStream in = null; try { Configuration config = new Configuration(); config.setNumberFormat("#"); config.setDefaultEncoding("utf-8"); Map<String, Object> con = new HashMap<String, Object>(); StringWriter stringWriter = new StringWriter(); GridView gridView = getGridView(true); new GridViewWriter(stringWriter).writeGridView(gridView); con.put("content", stringWriter.toString()); con.put("mainViewId", gridView.getViewId()); in = TemplateManager.class .getClassLoader() .getResourceAsStream( "com/gree/mobile/wf/taskinfo/template/grid/billDetailTemplate.ftl"); Template tpl = new Template("", new InputStreamReader(in, "utf-8"), config, "utf-8"); tpl.process(con, writer); } finally { IOUtils.closeQuietly(in); } }
/** * FreeMarker template engine configuration * * @return configuration of FreeMarker */ private static Configuration createFreemarkerConfiguration() { Configuration cfg = new Configuration(Configuration.VERSION_2_3_23); cfg.setClassForTemplateLoading(MainController.class, "/freemarker"); cfg.setDefaultEncoding("UTF-8"); return cfg; }
public void init() throws ServletException { cfg = new Configuration(Configuration.VERSION_2_3_23); cfg.setServletContextForTemplateLoading(getServletContext(), "./"); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); }
@SuppressWarnings({"resource", "rawtypes", "unchecked"}) public static void main(String[] args) throws Exception { Configuration cfg = new Configuration(); // 设置FreeMarker的模版文件位置 cfg.setClassForTemplateLoading( SourceCodeFrameworkBuilder.class, "/lab/s2jh/tool/builder/freemarker"); cfg.setDefaultEncoding("UTF-8"); String rootPath = args[0]; Set<String> entityNames = new HashSet<String>(); String entityListFile = rootPath + "entity_list.properties"; BufferedReader reader = new BufferedReader(new FileReader(entityListFile)); String line; while ((line = reader.readLine()) != null) { if (StringUtils.isNotBlank(line) && !line.startsWith("#")) { entityNames.add(line); } } new File(rootPath + "\\codes").mkdir(); new File(rootPath + "\\codes\\integrate").mkdir(); new File(rootPath + "\\codes\\standalone").mkdir(); for (String entityName : entityNames) { String integrateRootPath = rootPath + "\\codes\\integrate\\"; String standaloneRootPath = rootPath + "\\codes\\standalone\\"; String rootPackage = StringUtils.substringBetween(entityName, "[", "]"); String rootPackagePath = StringUtils.replace(rootPackage, ".", "\\"); String className = StringUtils.substringAfterLast(entityName, "."); String classFullName = StringUtils.replaceEach(entityName, new String[] {"[", "]"}, new String[] {"", ""}); String modelName = StringUtils.substringBetween(entityName, "].", ".entity"); String modelPath = StringUtils.replace(modelName, ".", "/"); modelPath = "/" + modelPath; String modelPackagePath = StringUtils.replace(modelName, ".", "\\"); modelPackagePath = "\\" + modelPackagePath; Map<String, Object> root = new HashMap<String, Object>(); String nameField = propertyToField(StringUtils.uncapitalize(className)).toLowerCase(); root.put("model_name", modelName); root.put("model_path", modelPath); root.put("entity_name", className); root.put("entity_name_uncapitalize", StringUtils.uncapitalize(className)); root.put("entity_name_field", nameField); root.put("root_package", rootPackage + "." + modelName); root.put("action_package", rootPackage); root.put("table_name", "T_TODO_" + className.toUpperCase()); root.put("base", "${base}"); Class entityClass = Class.forName(classFullName); root.put("id_type", entityClass.getMethod("getId").getReturnType().getSimpleName()); MetaData classEntityComment = (MetaData) entityClass.getAnnotation(MetaData.class); if (classEntityComment != null) { root.put("model_title", classEntityComment.value()); } else { root.put("model_title", entityName); } debug("Entity Data Map=" + root); Set<Field> fields = new HashSet<Field>(); Field[] curfields = entityClass.getDeclaredFields(); for (Field field : curfields) { fields.add(field); } Class superClass = entityClass.getSuperclass(); while (superClass != null && !superClass.equals(BaseEntity.class)) { Field[] superfields = superClass.getDeclaredFields(); for (Field field : superfields) { fields.add(field); } superClass = superClass.getSuperclass(); } // 定义用于OneToOne关联对象的Fetch参数 Map<String, String> fetchJoinFields = Maps.newHashMap(); List<EntityCodeField> entityFields = new ArrayList<EntityCodeField>(); int cnt = 1; for (Field field : fields) { if ((field.getModifiers() & Modifier.FINAL) != 0 || "id".equals(field.getName())) { continue; } debug(" - Field=" + field); Class fieldType = field.getType(); EntityCodeField entityCodeField = null; if (fieldType.isEnum()) { entityCodeField = new EntityCodeField(); entityCodeField.setListFixed(true); entityCodeField.setListWidth(80); entityCodeField.setListAlign("center"); } else if (fieldType == Boolean.class) { entityCodeField = new EntityCodeField(); entityCodeField.setListFixed(true); entityCodeField.setListWidth(60); entityCodeField.setListAlign("center"); } else if (PersistableEntity.class.isAssignableFrom(fieldType)) { entityCodeField = new EntityCodeField(); entityCodeField.setFieldType("Entity"); } else if (Number.class.isAssignableFrom(fieldType)) { entityCodeField = new EntityCodeField(); entityCodeField.setListFixed(true); entityCodeField.setListWidth(60); entityCodeField.setListAlign("right"); } else if (fieldType == String.class) { entityCodeField = new EntityCodeField(); // 根据Hibernate注解的字符串类型和长度设定是否列表显示 Method getMethod = entityClass.getMethod("get" + StringUtils.capitalize(field.getName())); Column fieldColumn = getMethod.getAnnotation(Column.class); if (fieldColumn != null) { int length = fieldColumn.length(); if (length > 255) { entityCodeField.setList(false); entityCodeField.setListWidth(length); } } Lob fieldLob = getMethod.getAnnotation(Lob.class); if (fieldLob != null) { entityCodeField.setList(false); entityCodeField.setListWidth(Integer.MAX_VALUE); } } else if (fieldType == Date.class) { entityCodeField = new EntityCodeField(); entityCodeField.setListFixed(true); // 根据Json注解设定合理的列宽 entityCodeField.setListWidth(120); Method getMethod = entityClass.getMethod("get" + StringUtils.capitalize(field.getName())); JsonSerialize fieldJsonSerialize = getMethod.getAnnotation(JsonSerialize.class); if (fieldJsonSerialize != null) { if (DateJsonSerializer.class.equals(fieldJsonSerialize.using())) { entityCodeField.setListWidth(80); } } entityCodeField.setListAlign("center"); } if (entityCodeField != null) { if (fieldType.isEnum()) { entityCodeField.setEnumField(true); } if (StringUtils.isBlank(entityCodeField.getFieldType())) { entityCodeField.setFieldType(fieldType.getSimpleName()); } entityCodeField.setFieldName(field.getName()); EntityAutoCode entityAutoCode = field.getAnnotation(EntityAutoCode.class); if (entityAutoCode != null) { entityCodeField.setListHidden(entityAutoCode.listHidden()); entityCodeField.setEdit(entityAutoCode.edit()); entityCodeField.setList(entityAutoCode.listHidden() || entityAutoCode.listShow()); entityCodeField.setOrder(entityAutoCode.order()); } else { entityCodeField.setTitle(field.getName()); entityCodeField.setOrder(cnt++); } MetaData entityMetaData = field.getAnnotation(MetaData.class); if (entityMetaData != null) { entityCodeField.setTitle(entityMetaData.value()); } Method getMethod = entityClass.getMethod("get" + StringUtils.capitalize(field.getName())); JsonProperty fieldJsonProperty = getMethod.getAnnotation(JsonProperty.class); if (fieldJsonProperty != null) { entityCodeField.setList(true); } if (entityCodeField.getList() || entityCodeField.getListHidden()) { JoinColumn fieldJoinColumn = getMethod.getAnnotation(JoinColumn.class); if (fieldJoinColumn != null) { if (fieldJoinColumn.nullable() == false) { fetchJoinFields.put(field.getName(), "INNER"); } else { fetchJoinFields.put(field.getName(), "LEFT"); } } } entityFields.add(entityCodeField); } } Collections.sort(entityFields); root.put("entityFields", entityFields); if (fetchJoinFields.size() > 0) { root.put("fetchJoinFields", fetchJoinFields); } integrateRootPath = integrateRootPath + rootPackagePath + modelPackagePath; // process(cfg.getTemplate("Entity.ftl"), root, integrateRootPath + "\\entity\\", className + // ".java"); process( cfg.getTemplate("Dao.ftl"), root, integrateRootPath + "\\dao\\", className + "Dao.java"); process( cfg.getTemplate("Service.ftl"), root, integrateRootPath + "\\service\\", className + "Service.java"); process( cfg.getTemplate("Controller.ftl"), root, integrateRootPath + "\\web\\action\\", className + "Controller.java"); process( cfg.getTemplate("Test.ftl"), root, integrateRootPath + "\\test\\service\\", className + "ServiceTest.java"); process( cfg.getTemplate("JSP_Index.ftl"), root, integrateRootPath + "\\jsp\\", nameField + "-index.jsp"); process( cfg.getTemplate("JSP_Input_Tabs.ftl"), root, integrateRootPath + "\\jsp\\", nameField + "-inputTabs.jsp"); process( cfg.getTemplate("JSP_Input_Basic.ftl"), root, integrateRootPath + "\\jsp\\", nameField + "-inputBasic.jsp"); process( cfg.getTemplate("JSP_View_Tabs.ftl"), root, integrateRootPath + "\\jsp\\", nameField + "-viewTabs.jsp"); process( cfg.getTemplate("JSP_View_Basic.ftl"), root, integrateRootPath + "\\jsp\\", nameField + "-viewBasic.jsp"); standaloneRootPath = standaloneRootPath + rootPackagePath + modelPackagePath + "\\" + className; // process(cfg.getTemplate("Entity.ftl"), root, standaloneRootPath + "\\entity\\", className + // ".java"); process( cfg.getTemplate("Dao.ftl"), root, standaloneRootPath + "\\dao\\", className + "Dao.java"); process( cfg.getTemplate("Service.ftl"), root, standaloneRootPath + "\\service\\", className + "Service.java"); process( cfg.getTemplate("Controller.ftl"), root, standaloneRootPath + "\\web\\action\\", className + "Controller.java"); process( cfg.getTemplate("Test.ftl"), root, standaloneRootPath + "\\test\\service\\", className + "ServiceTest.java"); process( cfg.getTemplate("JSP_Index.ftl"), root, standaloneRootPath + "\\jsp\\", nameField + "-index.jsp"); process( cfg.getTemplate("JSP_Input_Tabs.ftl"), root, standaloneRootPath + "\\jsp\\", nameField + "-inputTabs.jsp"); process( cfg.getTemplate("JSP_Input_Basic.ftl"), root, standaloneRootPath + "\\jsp\\", nameField + "-inputBasic.jsp"); process( cfg.getTemplate("JSP_View_Tabs.ftl"), root, standaloneRootPath + "\\jsp\\", nameField + "-viewTabs.jsp"); process( cfg.getTemplate("JSP_View_Basic.ftl"), root, standaloneRootPath + "\\jsp\\", nameField + "-viewBasic.jsp"); } }
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(); } } }