コード例 #1
0
  /**
   * 模版配置
   *
   * @param resource
   * @return
   */
  private static Configuration getConfig(String resource) {

    Configuration cfg = new Configuration();
    cfg.setDefaultEncoding("UTF-8");
    cfg.setClassForTemplateLoading(DbTableProcess.class, resource);
    return cfg;
  }
コード例 #2
0
ファイル: HibernateTool.java プロジェクト: wys43cc/vwru
 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()));
 }
コード例 #3
0
  public static void main(String[] args) {
    final Configuration config = new Configuration();
    config.setClassForTemplateLoading(HelloWorldFreemarkerStyle.class, "/");

    Spark.get(
        new Route("/") {
          @Override
          public Object handle(final Request request, final Response response) {
            StringWriter writer = new StringWriter();
            try {
              Template hello = config.getTemplate("hello.ftl");

              Map<String, Object> map = new HashMap<String, Object>();
              map.put("name", "World");
              hello.process(map, writer);

            } catch (Exception e) {
              halt(500);
              e.printStackTrace();
            }

            return writer;
          }
        });
  }
コード例 #4
0
  public static void main(String[] args) {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(HelloSparkFreemarker.class, "/");

    Spark.get(
        "/",
        new Route() {
          public Object handle(Request request, Response response) throws Exception {
            try {
              Template template = configuration.getTemplate("hello.ftl");
              StringWriter writer = new StringWriter();

              Map<String, Object> helloMap = new HashMap<String, Object>();
              helloMap.put("name", "Giovanni");

              template.process(helloMap, writer);
              return writer;

            } catch (Exception e) {
              e.printStackTrace();
              return "Error 500";
            }
          }
        });
  }
コード例 #5
0
  private void initConfig() {
    if (cfg != null) return;

    cfg = new Configuration();
    cfg.setClassForTemplateLoading(DefaultHTMLEmitter.class, "/freemarker/");
    cfg.setObjectWrapper(new DefaultObjectWrapper());
  }
  /** @param args */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(HelloWorldFreeMarkerStyle.class, "/");

    Spark.get(
        new Route("/") {

          public Object handle(final Request request, final Response response) {

            StringWriter writer = new StringWriter();

            try {
              Template helloTemplate = configuration.getTemplate("hello.ftl");

              Map<String, Object> helloMap = new HashMap<String, Object>();
              helloMap.put("name", "Puneeth");
              // System.out.println(helloMap.get("name"));
              helloTemplate.process(helloMap, writer);
              // System.out.println(writer);

            } catch (Exception e) {
              // TODO: handle exception
              halt(500);
              e.printStackTrace();
            }
            return writer;
          }
        });
  }
コード例 #7
0
 static {
   /* Create and adjust freemarker configuration */
   cfg.setClassForTemplateLoading(
       PropertyClassGenerator.class, "/net/jangaroo/properties/templates");
   cfg.setObjectWrapper(new DefaultObjectWrapper());
   cfg.setOutputEncoding("UTF-8");
 }
コード例 #8
0
ファイル: TallyXMLGenerator.java プロジェクト: remtcs/head
 private static Configuration buildFreemarkerConfiguration() {
   if (freemarkerConfiguration == null) {
     freemarkerConfiguration = new Configuration();
     freemarkerConfiguration.setClassForTemplateLoading(TallyXMLGenerator.class, "");
     freemarkerConfiguration.setObjectWrapper(new DefaultObjectWrapper());
   }
   return freemarkerConfiguration;
 }
コード例 #9
0
 private Configuration getFreeMarkerConfig() {
   if (mFreemarkerConfig == null) {
     mFreemarkerConfig = new Configuration();
     mFreemarkerConfig.setClassForTemplateLoading(getClass(), "");
     mFreemarkerConfig.setObjectWrapper(new DefaultObjectWrapper());
   }
   return mFreemarkerConfig;
 }
コード例 #10
0
 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;
 }
コード例 #11
0
  public void test() throws IOException, TemplateException {
    Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(this.getClass(), "/");
    Template template = configuration.getTemplate("orkut_community_content.ftl");

    com.google.api.services.orkut.model.Community orkutCommunity =
        new com.google.api.services.orkut.model.Community();
    orkutCommunity.setName("Vaalikal");
    orkutCommunity.setDescription("Vaalikal");
    orkutCommunity.setCreationDate(new DateTime(System.currentTimeMillis()));
    orkutCommunity.setId(123456);
    orkutCommunity.setMemberCount(6);
    orkutCommunity.setPhotoUrl("ABC");

    Community community = new Community(orkutCommunity);
    OrkutAuthorResource p1 = new OrkutAuthorResource();
    p1.setDisplayName("Thomas Mathew");
    p1.setImage(new OrkutAuthorResource.Image());
    Member m1 = new Member(p1);
    p1.setDisplayName("Kiran Kumar");
    Member m2 = new Member(p1);
    p1.setDisplayName("Aswani");
    Member m3 = new Member(p1);
    community.members = Arrays.asList(m1, m2, m3);

    CommunityTopic communityTopic = new CommunityTopic();
    communityTopic.setAuthor(p1);
    communityTopic.setTitle("Testing");
    communityTopic.setNumberOfReplies(2);
    Topic topic = new Topic(communityTopic);

    CommunityMessage c1 = new CommunityMessage();
    c1.setAuthor(p1);
    c1.setBody("Hello Test");
    c1.setAddedDate(new DateTime(System.currentTimeMillis()));
    TopicMessage t1 = new TopicMessage(c1);
    CommunityMessage c2 = new CommunityMessage();
    c2.setAuthor(p1);
    c2.setBody("Looks Good");
    c2.setAddedDate(new DateTime(System.currentTimeMillis()));
    TopicMessage t2 = new TopicMessage(c2);

    topic.messageList.add(t1);
    topic.messageList.add(t2);
    community.topicList.add(topic);

    System.out.println(System.getProperty("java.io.tmpdir"));
    Writer out =
        new OutputStreamWriter(
            new FileOutputStream(
                new File(System.getProperty("java.io.tmpdir"), community.name + ".html")));
    BeansWrapper beansWrapper = new BeansWrapper();
    beansWrapper.setExposeFields(true);
    template.process(community, out, beansWrapper);
    out.flush();
  }
コード例 #12
0
ファイル: ExceptionDecorator.java プロジェクト: LyneLiu/cat
 @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);
   }
 }
コード例 #13
0
 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());
 }
コード例 #14
0
  @PostConstruct
  private void postConstruct() throws IOException {
    cfg = new Configuration();
    cfg.setTemplateUpdateDelay(500);
    cfg.setClassForTemplateLoading(this.getClass(), "/");

    runDirectory = context.getRunDirectory();
    File archiveReportDirectory = new File(runDirectory, "applications");
    File archiveDirectory = new File(archiveReportDirectory, "application");
    FileUtils.forceMkdir(archiveDirectory);
    reportReference = new File(archiveDirectory, "classloader-notfound.html");
  }
コード例 #15
0
ファイル: TemplateParser.java プロジェクト: gengchong/WFBD
  @SuppressWarnings("unchecked")
  public static String parseTemplate(
      Map paramMap,
      String templateName,
      String templateDirectory,
      boolean isDirectory,
      String encoding)
      throws IOException, TemplateException {
    if (configuration == null) {
      configuration = new Configuration();
    }
    if (StringUtils.isNotBlank(encoding)) {
      configuration.setEncoding(Locale.getDefault(), encoding);
    } else {
      configuration.setEncoding(Locale.getDefault(), DEFAULT_ENCODING);
    }
    ByteArrayOutputStream bos = null;
    OutputStreamWriter out = null;
    try {
      if (isDirectory) {
        configuration.setDirectoryForTemplateLoading(new File(templateDirectory));
      } else {
        configuration.setClassForTemplateLoading(TemplateParser.class, templateDirectory);
      }
      bos = new ByteArrayOutputStream();
      out = new OutputStreamWriter(bos);
      configuration.getTemplate(templateName).process(paramMap, out);
      return bos.toString();
    } catch (IOException e) {
      throw e;
    } catch (TemplateException e) {
      throw e;
    } finally {
      try {
        out.close();
      } catch (IOException e) {

      } finally {
        out = null;
      }

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

      } finally {
        bos = null;
      }
    }
  }
コード例 #16
0
  @Test
  public void testTemplate() throws Exception {
    Configuration cfg = new Configuration();
    cfg.setObjectWrapper(new FeatureWrapper());
    cfg.setClassForTemplateLoading(FeatureTemplate.class, "");

    Template template = cfg.getTemplate("description.ftl");
    assertNotNull(template);

    // create some data
    GeometryFactory gf = new GeometryFactory();
    SimpleFeatureType featureType =
        DataUtilities.createType("testType", "string:String,int:Integer,double:Double,geom:Point");

    SimpleFeature f =
        SimpleFeatureBuilder.build(
            featureType,
            new Object[] {
              "three", new Integer(3), new Double(3.3), gf.createPoint(new Coordinate(3, 3))
            },
            "fid.3");

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    template.process(f, new OutputStreamWriter(output));
    // template.process(f, new OutputStreamWriter(System.out));

    // This generates the following:

    // <h4>testType</h4>

    // <ul class="textattributes">
    // <li><strong><span class="atr-name">string</span>:</strong> <span
    // class="atr-value">three</span></li>
    // <li><strong><span class="atr-name">int</span>:</strong> <span
    // class="atr-value">3</span></li>
    // <li><strong><span class="atr-name">double</span>:</strong> <span
    // class="atr-value">3.3</span></li>
    //
    // </ul>

    // TODO docbuilder cannot parse this? May expect encapsulation, which table did provide

    // DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    // Document document = docBuilder.parse(new ByteArrayInputStream(output.toByteArray()));

    // assertNotNull(document);

    // assertEquals("table", document.getDocumentElement().getNodeName());
  }
コード例 #17
0
 public static void main(String[] args) {
   // TODO Auto-generated method stub
   Configuration configuration = new Configuration();
   configuration.setClassForTemplateLoading(HelloWorldFreeMarkerStyle.class, "/");
   try {
     Template helloTemplate = configuration.getTemplate("hello.ftl");
     StringWriter stringWriter = new StringWriter();
     Map<String, Object> helloMap = new HashMap<String, Object>();
     helloMap.put("name", "FreeMarker");
     helloTemplate.process(helloMap, stringWriter);
     System.out.println(stringWriter);
   } catch (Exception e) {
     System.err.println("Exception");
     e.printStackTrace();
   }
 }
コード例 #18
0
  public void genServerConfFile() throws IOException, TemplateException {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
    cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
    cfg.setClassForTemplateLoading(this.getClass(), "/");
    Template template = cfg.getTemplate("template/galera_server.ftl");

    // Build the data-model
    Map<String, Object> data = new HashMap<>();
    data.put("ownHostInfo", hostInfo);
    data.put("otherHostInfos", otherHostInfo);
    // Console output
    String path = getClass().getClassLoader().getResource("").getFile();
    FileWriter out = new FileWriter(path + "/template/server.cnf." + hostInfo.getHostName());
    template.process(data, out);
    out.flush();
    out.close();
  }
コード例 #19
0
ファイル: GenerateJavaFile.java プロジェクト: yufeidu/SHES
 /**
  * 生成文件
  *
  * @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();
   }
 }
コード例 #20
0
  public static void main(String[] args) {
    Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(HelloWorldSparkFreemarkerStyle.class, "/");

    try {
      Template helloTemplate = configuration.getTemplate("hello.ftl");
      StringWriter writer = new StringWriter();
      Map<String, Object> helloMap = new HashMap<String, Object>();
      helloMap.put("name", "freemarker");

      helloTemplate.process(helloMap, writer);
      // System.out.println(writer);
      spark.Spark.get("/hello", (req, res) -> writer);

    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
コード例 #21
0
 @Override
 protected Configuration createConfiguration(Object data, Class clazz) {
   Configuration cfg = super.createConfiguration(data, clazz);
   cfg.setClassForTemplateLoading(getClass(), "templates");
   cfg.setObjectWrapper(
       new ObjectToMapWrapper<WFSInfo>(WFSInfo.class) {
         @Override
         protected void wrapInternal(Map properties, SimpleHash model, WFSInfo wfsInfo) {
           WorkspaceInfo workspaceInfo = wfsInfo.getWorkspace();
           properties.put(
               "workspaceName",
               workspaceInfo != null ? workspaceInfo.getName() : "NO_WORKSPACE");
           properties.put("enabled", wfsInfo.isEnabled() ? "true" : "false");
           properties.put("name", wfsInfo.getName());
           properties.put("title", wfsInfo.getTitle());
           properties.put("maintainer", wfsInfo.getMaintainer());
           properties.put("abstract", wfsInfo.getAbstract());
           properties.put("accessConstraints", wfsInfo.getAccessConstraints());
           properties.put("fees", wfsInfo.getFees());
           properties.put("versions", wfsInfo.getVersions());
           properties.put("keywords", wfsInfo.getKeywords());
           properties.put("metadataLink", wfsInfo.getMetadataLink());
           properties.put("citeCompliant", wfsInfo.isCiteCompliant() ? "true" : "false");
           properties.put("onlineResource", wfsInfo.getOnlineResource());
           properties.put("schemaBaseURL", wfsInfo.getSchemaBaseURL());
           properties.put("verbose", wfsInfo.isVerbose() ? "true" : "false");
           properties.put("maxFeatures", String.valueOf(wfsInfo.getMaxFeatures()));
           properties.put("isFeatureBounding", wfsInfo.isFeatureBounding() ? "true" : "false");
           properties.put(
               "hitsIgnoreMaxFeatures", wfsInfo.isHitsIgnoreMaxFeatures() ? "true" : "false");
           properties.put(
               "maxNumberOfFeaturesForPreview", wfsInfo.getMaxNumberOfFeaturesForPreview());
           properties.put("serviceLevel", wfsInfo.getServiceLevel());
           properties.put(
               "isCanonicalSchemaLocation",
               wfsInfo.isCanonicalSchemaLocation() ? "true" : "false");
           properties.put(
               "encodeFeatureMember", wfsInfo.isEncodeFeatureMember() ? "true" : "false");
         }
       });
   return cfg;
 }
コード例 #22
0
  public static void main(String[] args) {
    Configuration configuration = new Configuration();

    configuration.setClassForTemplateLoading(HelloWorldFreemarkerStyle.class, "/");

    try {
      Template helloTemplate = configuration.getTemplate("hello.ftl");
      StringWriter writer = new StringWriter();
      Map<String, Object> helloMap = new HashMap<>();
      helloMap.put("name", "Freemarker");

      helloTemplate.process(helloMap, writer);

      System.out.println(writer);

    } catch (Exception e) {
      e.printStackTrace(); // To change body of catch statement use File | Settings | File
      // Templates.
    }
  }
コード例 #23
0
  private String generateMessage(String trigger, Map executionData, Map config) {
    Configuration freeMarkerCfg = new Configuration();
    String templateName;

    if (messageTemplateLocation != null && messageTemplateLocation.length() > 0) {
      File messageTemplateFile = new File(messageTemplateLocation);
      try {
        freeMarkerCfg.setDirectoryForTemplateLoading(messageTemplateFile.getParentFile());
      } catch (IOException ioEx) {
        throw new HipChatNotificationPluginException(
            "Error setting FreeMarker template loading directory: [" + ioEx.getMessage() + "].",
            ioEx);
      }
      templateName = messageTemplateFile.getName();
    } else {
      freeMarkerCfg.setClassForTemplateLoading(HipChatNotificationPlugin.class, "/templates");
      templateName = HIPCHAT_MESSAGE_DEFAULT_TEMPLATE;
    }

    Map<String, Object> model = new HashMap<String, Object>();
    model.put("trigger", trigger);
    model.put("execution", executionData);
    model.put("config", config);

    StringWriter sw = new StringWriter();
    try {
      Template template = freeMarkerCfg.getTemplate(templateName);
      template.process(model, sw);

    } catch (IOException ioEx) {
      throw new HipChatNotificationPluginException(
          "Error loading HipChat notification message template: [" + ioEx.getMessage() + "].",
          ioEx);
    } catch (TemplateException templateEx) {
      throw new HipChatNotificationPluginException(
          "Error merging HipChat notification message template: [" + templateEx.getMessage() + "].",
          templateEx);
    }

    return sw.toString();
  }
コード例 #24
0
  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);
    }
  }
コード例 #25
0
ファイル: FreeMarkerPaser.java プロジェクト: jianganglu/NC
  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;
  }
コード例 #26
0
  public static void main(String[] args) {

    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(HelloWorldMongodbSparkFreemarkerStyle.class, "/");

    MongoClient client = new MongoClient();

    MongoDatabase db = client.getDatabase("course");

    final MongoCollection<Document> coll = db.getCollection("hello");

    coll.drop();

    coll.insertOne(new Document("name", "Mongodb"));

    Spark.get(
        new Route("/") {

          @Override
          public Object handle(Request arg0, Response arg1) {
            StringWriter writer = new StringWriter();
            try {
              Template helloTemplate = configuration.getTemplate("hello.ftl");

              Document document = coll.find().first();

              helloTemplate.process(document, writer);

              // System.out.println(writer);

            } catch (Exception e) {
              halt(500);
              e.printStackTrace();
            }
            return writer;
          }
        });
  }
コード例 #27
0
  /**
   * Create an eclipse launch configuration file for the specified test
   *
   * @param test the GWTTestCase
   * @param testSrc the source directory where the test lives
   * @throws MojoExecutionException some error occured
   */
  private void createLaunchConfigurationForGwtTestCase(File testSrc, String test)
      throws MojoExecutionException {
    File testFile = new File(testSrc, test);

    String fqcn = test.replace(File.separatorChar, '.').substring(0, test.lastIndexOf('.'));
    File launchFile = new File(getProject().getBasedir(), fqcn + ".launch");
    if (launchFile.exists() && launchFile.lastModified() > testFile.lastModified()) {
      return;
    }

    Configuration cfg = new Configuration();
    cfg.setClassForTemplateLoading(EclipseTestMojo.class, "");

    Map<String, Object> context = new HashMap<String, Object>();
    List<String> sources = new LinkedList<String>();
    sources.addAll(executedProject.getTestCompileSourceRoots());
    sources.addAll(executedProject.getCompileSourceRoots());
    context.put("sources", sources);
    context.put("test", fqcn);
    int basedir = getProject().getBasedir().getAbsolutePath().length();
    context.put("out", testOutputDirectory.getAbsolutePath().substring(basedir + 1));
    context.put("extraJvmArgs", getExtraJvmArgs());
    context.put("project", eclipseUtil.getProjectName(getProject()));

    try {
      //            context.put( "gwtDevJarPath", getGwtDevJar().getAbsolutePath() );
      Writer configWriter = WriterFactory.newXmlWriter(launchFile);
      Template template = cfg.getTemplate("test-launch.fm", "UTF-8");
      template.process(context, configWriter);
      configWriter.flush();
      configWriter.close();
      getLog().info("Write launch configuration for GWT test : " + launchFile.getAbsolutePath());
    } catch (IOException ioe) {
      throw new MojoExecutionException("Unable to write launch configuration", ioe);
    } catch (TemplateException te) {
      throw new MojoExecutionException("Unable to merge freemarker template", te);
    }
  }
コード例 #28
0
  public static void main(String[] args) {

    final Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
    configuration.setClassForTemplateLoading(HelloWorldFreemarkerStyle.class, "/");

    get(
        "/",
        (request, response) -> {
          StringWriter writer = new StringWriter();
          try {
            Template helloTemplate = configuration.getTemplate("hello.ftl");

            Map<String, Object> helloMap = new HashMap<>();
            helloMap.put("name", "Freemarker");

            helloTemplate.process(helloMap, writer);
          } catch (Exception e) {
            halt(500);
            e.printStackTrace();
          }
          return writer;
        });
  }
コード例 #29
0
ファイル: SendMail.java プロジェクト: pttien/tieuluan1310
  public static void sendMail(String mail, MailContent mailContent) throws Exception {

    Properties props = new Properties();
    //		try {
    //			props.load(new FileInputStream(new File("settings.properties")));
    //		} catch (FileNotFoundException e1) {
    //			e1.printStackTrace();
    //		} catch (IOException e1) {
    //			e1.printStackTrace();
    //		}

    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session =
        Session.getDefaultInstance(
            props,
            new Authenticator() {

              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("*****@*****.**", "mycity@123");
              }
            });

    try {
      String a = mail;
      String b = mailContent.getTopp();
      String c = mailContent.getBody1();
      String d = mailContent.getBody2();
      Message message = new MimeMessage(session);
      //			MimeUtility.encodeText(subject, "utf-8", "B")
      message.setFrom(new InternetAddress("*****@*****.**"));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mail));
      message.setSubject(MimeUtility.encodeText(mailContent.getSubJect(), "utf-8", "B"));

      BodyPart body = new MimeBodyPart();
      // freemarker stuff.
      Configuration cfg = new Configuration();
      FileTemplateLoader ftl1 =
          new FileTemplateLoader(
              new File(ServletActionContext.getServletContext().getRealPath("/")));
      cfg.setClassForTemplateLoading(cfg.getClass(), "/");
      cfg.setTemplateLoader(ftl1);
      Template template = null;
      template =
          cfg.getTemplate("resources/mycity_cms/templates/mail/html-mail-template.html", "UTF-8");

      Map<String, String> rootMap = new HashMap<String, String>();
      rootMap.put("to", mailContent.getTopp());
      rootMap.put("body1", mailContent.getBody1());
      rootMap.put("body2", mailContent.getBody2());
      Writer out = new StringWriter();
      template.process(rootMap, out);
      // freemarker stuff ends.

      /* you can add html tags in your text to decorate it. */
      //			body.setContent(out.toString(),	"text/html");
      body.setContent(out.toString(), "text/html; charset=UTF-8");

      Multipart multipart = new MimeMultipart();
      multipart.addBodyPart(body);
      // cfg
      //			body = new MimeBodyPart();
      //
      //			String filename = "hello.txt";
      //			DataSource source = new FileDataSource(filename);
      //			body.setDataHandler(new DataHandler(source));
      //			body.setFileName(filename);
      //			multipart.addBodyPart(body);
      //
      message.setContent(multipart, "text/html; charset=UTF-8;");
      //
      Transport.send(message);

    } catch (MessagingException e) {
      LogUtility.logError(e, e.getMessage());
    }

    System.out.println("Done....");
  }
コード例 #30
0
  @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");
    }
  }