freemarker.template.TemplateException Java Examples

The following examples show how to use freemarker.template.TemplateException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DocFragmentService.java    From estatio with Apache License 2.0 6 votes vote down vote up
/**
 * Overload of {@link #render(Object, String)}, but allowing the atPath to be specified explicitly rather than inferred from the supplied domain object.
 *
 * @param domainObject provides the state for the interpolation into the fragment's {@link DocFragment#getTemplateText() template text}
 * @param name corresponds to the {@link DocFragment#getName() name} of the {@link DocFragment} to use to render.
 * @param atPath corrsponds to the {@link ApplicationTenancyService#atPathFor(Object) atPath} of the {@link DocFragment} to use to render
 *
 * @throws IOException
 * @throws TemplateException
 * @throws RenderException - if could not locate any {@link DocFragment}.
 */
@Programmatic
public String render(
            final Object domainObject,
            final String name,
            final String atPath)
        throws IOException, TemplateException, RenderException {
    final String objectType = objectTypeFor(domainObject);

    final DocFragment fragment = repo.findByObjectTypeAndNameAndApplicableToAtPath(objectType, name, atPath);

    if (fragment != null)
        return fragment.render(domainObject);
    else
        throw new RenderException(
                "No fragment found for objectType: %s, name: %s, atPath: %s",
                objectType, name, atPath);
}
 
Example #2
Source File: UnitJobPage.java    From freeacs with MIT License 6 votes vote down vote up
private void getFailedUnitJobs(Job job, Output res, DataSource mainDataSource)
    throws SQLException, IOException, TemplateException {
  res.setTemplatePath("unit-job/failed");
  Map<String, Object> rootMap = new HashMap<>();
  UnitJobs unitJobs = new UnitJobs(mainDataSource);
  List<UnitJob> unitJobsList = unitJobs.readAllProcessed(job);
  //		List<UnitJob> list = new ArrayList<UnitJob>();
  //		if (limit != null) {
  //			for (int i = 0; i < limit && i <= unitJobsList.size() - 1; i++) {
  //				list.add(unitJobsList.get(i));
  //			}
  //			unitJobsList = list;
  //		}
  SessionCache.getSessionData(sessionId).setFailedUnitJobsList(null);
  if (!unitJobsList.isEmpty()) {
    rootMap.put("unitJobs", unitJobsList);
    SessionCache.getSessionData(sessionId).setFailedUnitJobsList(unitJobsList);
  }
  rootMap.put("job", job);
  rootMap.put("async", inputData.getAsync().getString());
  //		rootMap.put("limit", limit);
  res.getTemplateMap().putAll(rootMap);
}
 
Example #3
Source File: DatabaseGenerator.java    From j-road with Apache License 2.0 6 votes vote down vote up
public static void generate(DatabaseClasses classes, String outputdir) throws IOException, TemplateException {
  Configuration cfg = new Configuration();
  cfg.setClassForTemplateLoading(TypeGen.class, "/");
  cfg.setObjectWrapper(new DefaultObjectWrapper());

  Template interfaceTemp = cfg.getTemplate(DATABASE_TEMPLATE_FILE);
  Template implTemp = cfg.getTemplate(DATABASE_IMPL_TEMPLATE_FILE);

  for (DatabaseClass databaseClass : classes.getClasses().values()) {
    Map<String, DatabaseClass> root = new HashMap<String, DatabaseClass>();
    root.put("databaseClass", databaseClass);

    Writer out = FileUtil.createAndGetOutputStream(databaseClass.getQualifiedInterfaceName(), outputdir);
    interfaceTemp.process(root, out);
    out.flush();

    out = FileUtil.createAndGetOutputStream(databaseClass.getQualifiedImplementationName(), outputdir);
    implTemp.process(root, out);
    out.flush();
  }
}
 
Example #4
Source File: CmsFriendlinkCtgListDirective.java    From Lottery with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void execute(Environment env, Map params, TemplateModel[] loopVars,
		TemplateDirectiveBody body) throws TemplateException, IOException {
	Integer siteId = getSiteId(params);
	if (siteId == null) {
		siteId = FrontUtils.getSite(env).getId();
	}
	List<CmsFriendlinkCtg> list = cmsFriendlinkCtgMng.getList(siteId);

	Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(
			params);
	paramWrap.put(OUT_LIST, DEFAULT_WRAPPER.wrap(list));
	Map<String, TemplateModel> origMap = DirectiveUtils
			.addParamsToVariable(env, paramWrap);
	body.render(env.getOut());
	DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);
}
 
Example #5
Source File: ControllerTask.java    From generator with Apache License 2.0 6 votes vote down vote up
@Override
public void run() throws IOException, TemplateException {
    // 生成Controller填充数据
    Map<String, String> controllerData = new HashMap<>();
    controllerData.put("BasePackageName", ConfigUtil.getConfiguration().getPackageName());
    controllerData.put("ControllerPackageName", ConfigUtil.getConfiguration().getPath().getController());
    if (StringUtil.isBlank(ConfigUtil.getConfiguration().getPath().getInterf())) {
        controllerData.put("ServicePackageName", ConfigUtil.getConfiguration().getPath().getService());
    } else {
        controllerData.put("ServicePackageName", ConfigUtil.getConfiguration().getPath().getInterf());
    }
    controllerData.put("EntityPackageName", ConfigUtil.getConfiguration().getPath().getEntity());
    controllerData.put("Author", ConfigUtil.getConfiguration().getAuthor());
    controllerData.put("Date", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
    controllerData.put("ClassName", className);
    controllerData.put("EntityName", StringUtil.firstToLowerCase(className));
    String filePath = FileUtil.getSourcePath() + StringUtil.package2Path(ConfigUtil.getConfiguration().getPackageName()) + StringUtil.package2Path(ConfigUtil.getConfiguration().getPath().getController());
    String fileName = className + "Controller.java";
    // 生成Controller文件
    FileUtil.generateToJava(FreemarketConfigUtil.TYPE_CONTROLLER, controllerData, filePath, fileName);
}
 
Example #6
Source File: Templates.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
public static void createFileContent(
    String outputFileLocation, String templateName, Map<String, String> dataMap)
    throws CoreException {
  Preconditions.checkNotNull(outputFileLocation, "output file is null");
  Preconditions.checkNotNull(templateName, "template name is null");
  Preconditions.checkNotNull(dataMap, "data map is null");

  if (configuration == null) {
    configuration = createConfiguration();
  }
  Path outputFile = Paths.get(outputFileLocation);
  try (Writer writer =
      new OutputStreamWriter(Files.newOutputStream(outputFile), StandardCharsets.UTF_8)) {
    Template template = configuration.getTemplate(templateName);
    template.process(dataMap, writer);
  } catch (IOException | TemplateException ex) {
    throw new CoreException(StatusUtil.error(Templates.class, ex.getMessage()));
  }
}
 
Example #7
Source File: ReportWebPlugin.java    From allure2 with Apache License 2.0 6 votes vote down vote up
protected void writeIndexHtml(final Configuration configuration,
                              final Path outputDirectory) throws IOException {
    final FreemarkerContext context = configuration.requireContext(FreemarkerContext.class);
    final Path indexHtml = outputDirectory.resolve("index.html");
    final List<PluginConfiguration> pluginConfigurations = configuration.getPlugins().stream()
            .map(Plugin::getConfig)
            .collect(Collectors.toList());

    try (BufferedWriter writer = Files.newBufferedWriter(indexHtml)) {
        final Template template = context.getValue().getTemplate("index.html.ftl");
        final Map<String, Object> dataModel = new HashMap<>();
        dataModel.put(Constants.PLUGINS_DIR, pluginConfigurations);
        template.process(dataModel, writer);
    } catch (TemplateException e) {
        LOGGER.error("Could't write index file", e);
    }
}
 
Example #8
Source File: ScriptUtils.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
/** @return script variables */
public static Set<String> getScriptVariables(Script script) {
  // based on https://stackoverflow.com/a/48024379
  Set<String> scriptExpressions = new LinkedHashSet<>();
  Configuration configuration = new Configuration(VERSION);
  configuration.setTemplateExceptionHandler(
      (te, env, out) -> {
        if (te instanceof InvalidReferenceException) {
          scriptExpressions.add(te.getBlamedExpressionString());
          return;
        }
        throw te;
      });

  try {
    Template template = new Template(null, new StringReader(script.getContent()), configuration);
    template.process(emptyMap(), new StringWriter());
  } catch (TemplateException | IOException e) {
    throw new GenerateScriptException(
        "Error processing parameters for script [" + script.getName() + "]. " + e.getMessage());
  }
  return scriptExpressions;
}
 
Example #9
Source File: GenerateDocsTask.java    From synopsys-detect with Apache License 2.0 6 votes vote down vote up
@TaskAction
public void generateDocs() throws IOException, TemplateException, IntegrationException {
    final Project project = getProject();
    final File file = new File("synopsys-detect-" + project.getVersion() + "-help.json");
    final Reader reader = new FileReader(file);
    final HelpJsonData helpJson = new Gson().fromJson(reader, HelpJsonData.class);

    final File outputDir = project.file("docs/generated");
    final File troubleshootingDir = new File(outputDir, "advanced/troubleshooting");

    FileUtils.deleteDirectory(outputDir);
    troubleshootingDir.mkdirs();

    final TemplateProvider templateProvider = new TemplateProvider(project.file("docs/templates"), project.getVersion().toString());

    createFromFreemarker(templateProvider, troubleshootingDir, "exit-codes", new ExitCodePage(helpJson.getExitCodes()));

    handleDetectors(templateProvider, outputDir, helpJson);
    handleProperties(templateProvider, outputDir, helpJson);
    handleContent(outputDir, templateProvider);
}
 
Example #10
Source File: TemplateFactoryTest.java    From Mario with Apache License 2.0 6 votes vote down vote up
@Test
public void testTemplateFactoryForService() throws IOException,
		TemplateException {
	TemplateFactory factory = TemplateFactory.getInstance();
	String path = "templates/Service.java.ftl";

	SqlTable table = new SqlTable(schema, tablename);
	Map<String, Object> data = new HashMap<String, Object>();
	data.put("sqlTable", table);
	Properties properties = ApplicationProperties.getProperties();
	data.put("prop", properties);

	String content = factory.process(path, data, "UTF-8");
	assertTrue(StringUtils.isNotBlank(content));

}
 
Example #11
Source File: DbTableProcess.java    From jeewx with Apache License 2.0 5 votes vote down vote up
public static void createOrDropTable(CgFormHeadEntity table, Session session) throws IOException, TemplateException, HibernateException, SQLException, DBException  {
	Template t;
	t = getConfig("/org/jeecgframework/web/cgform/engine/hibernate").getTemplate("tableTemplate.ftl");
	Writer out = new StringWriter();
	//模板对于数字超过1000,会自动格式为1,,000(禁止转换)
	t.setNumberFormat("0.#####################");
	t.process(getRootMap(table,DbTableUtil.getDataType(session)), out);
	String xml = out.toString();
	logger.info(xml);
	createTable(xml, table, session);
}
 
Example #12
Source File: MessagesDirective.java    From hermes with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
	if (!params.containsKey(PARAM_NAME_KEY)) {
		throw new TemplateModelException("key is necessary!");
	}
	env.getOut().write(App.message(params.get(PARAM_NAME_KEY).toString()));
}
 
Example #13
Source File: NotHasPermissionDirective.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void execute(boolean hasPermission, Environment env, TemplateDirectiveBody body)
    throws TemplateException, IOException {
  if (!hasPermission) {
    body.render(env.getOut());
  }
}
 
Example #14
Source File: HeatTemplateBuilderTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws IOException, TemplateException {
    initMocks(this);
    FreeMarkerConfigurationFactoryBean factoryBean = new FreeMarkerConfigurationFactoryBean();
    factoryBean.setPreferFileSystemAccess(false);
    factoryBean.setTemplateLoaderPath("classpath:/");
    factoryBean.afterPropertiesSet();
    Configuration configuration = factoryBean.getObject();
    ReflectionTestUtils.setField(heatTemplateBuilder, "freemarkerConfiguration", configuration);
    ReflectionTestUtils.setField(heatTemplateBuilder, "openStackHeatTemplatePath", templatePath);

    stackName = "testStack";
    groups = new ArrayList<>(1);
    String name = "master";
    List<Volume> volumes = Arrays.asList(new Volume("/hadoop/fs1", "HDD", 1), new Volume("/hadoop/fs2", "HDD", 1));
    InstanceTemplate instanceTemplate = new InstanceTemplate("m1.medium", name, 0L, volumes, InstanceStatus.CREATE_REQUESTED,
            new HashMap<>(), 0L, "cb-centos66-amb200-2015-05-25");
    InstanceAuthentication instanceAuthentication = new InstanceAuthentication("sshkey", "", "cloudbreak");
    CloudInstance instance = new CloudInstance("SOME_ID", instanceTemplate, instanceAuthentication);
    List<SecurityRule> rules = singletonList(new SecurityRule("0.0.0.0/0",
            new PortDefinition[]{new PortDefinition("22", "22"), new PortDefinition("443", "443")}, "tcp"));
    Security security = new Security(rules, emptyList());
    groups.add(new Group(name, InstanceGroupType.CORE, singletonList(instance), security, null,
            instanceAuthentication, instanceAuthentication.getLoginUserName(), instanceAuthentication.getPublicKey(), 50, Optional.empty()));
    Map<InstanceGroupType, String> userData = ImmutableMap.of(
            InstanceGroupType.CORE, "CORE",
            InstanceGroupType.GATEWAY, "GATEWAY"
    );
    image = new Image("cb-centos66-amb200-2015-05-25", userData, "redhat6", "redhat6", "url", "default", null, new HashMap<>());
}
 
Example #15
Source File: RenderComponentDirective.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException {
    TemplateModel componentParentParam = (TemplateModel) params.get(COMPONENT_PARENT_PARAM_NAME);
    TemplateModel componentParam = (TemplateModel) params.get(COMPONENT_PARAM_NAME);
    TemplateModel componentPathParam = (TemplateModel) params.get(COMPONENT_PATH_PARAM_NAME);
    TemplateModel additionalModelParam = (TemplateModel) params.get(ADDITIONAL_MODEL_PARAM_NAME);
    Map<String, Object> additionalModel = null;
    SiteItem component;

    if (componentParam == null && componentPathParam == null) {
        throw new TemplateException("No '" + COMPONENT_PARAM_NAME + "' or '" + COMPONENT_PATH_PARAM_NAME +
                                    "' param specified", env);
    } else if (componentParam != null) {
        component = getComponentFromNode(componentParentParam, componentParam, env);
    } else {
        component = getComponentFromPath(componentPathParam, env);
    }

    if (additionalModelParam != null) {
        additionalModel = unwrap(ADDITIONAL_MODEL_PARAM_NAME, additionalModelParam, Map.class, env);
    }

    Map<String, Object> templateModel = executeScripts(component, additionalModel, env);
    SimpleHash model = getFullModel(component, templateModel, additionalModel);
    Template template = getTemplate(component, env);
    Writer output = env.getOut();

    processComponentTemplate(template, model, output, env);
}
 
Example #16
Source File: RenderComponentDirective.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
protected void executeScript(Script script, Map<String, Object> scriptVariables, Environment env)
    throws TemplateException {
    if (logger.isDebugEnabled()) {
        logger.debug("Executing component script at " + script.getUrl());
    }

    try {
        script.execute(scriptVariables);
    } catch (Exception e) {
        throw new TemplateException("Error executing component script at " + script.getUrl(), e, env);
    }
}
 
Example #17
Source File: AnalysisSaikuService.java    From collect-earth with MIT License 5 votes vote down vote up
private void setMdxSaikuSchema(final File mdxFileTemplate, final File mdxFile)
		throws IOException, TemplateException {
	Map<String, String> saikuData = new HashMap<>();
	String saikuSchemaName = getSchemaName();
	if (saikuSchemaName == null) {
		saikuSchemaName = ""; //$NON-NLS-1$
	}
	saikuData.put("saikuDbSchema", saikuSchemaName); //$NON-NLS-1$
	FreemarkerTemplateUtils.applyTemplate(mdxFileTemplate, mdxFile, saikuData);
}
 
Example #18
Source File: RenderWrappedTextDirective.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env, @SuppressWarnings("rawtypes") Map args, TemplateModel[] loopVars, TemplateDirectiveBody body)
        throws TemplateException, IOException {
    Map<String, Object> ctx = UtilGenerics.checkMap(FreeMarkerWorker.getWrappedObject("context", env), String.class, Object.class);
    String wrappedFTL = FreeMarkerWorker.getArg(UtilGenerics.checkMap(args, String.class, Object.class), "wrappedFTL", ctx);
    if (UtilValidate.isNotEmpty(wrappedFTL)) {
        env.getOut().write(wrappedFTL);
    } else {
        if (Debug.verboseOn()) {
            Debug.logVerbose("wrappedFTL was empty. skipping write.", module);
        }
    }
}
 
Example #19
Source File: FreemarkerTemplatingService.java    From blackduck-alert with Apache License 2.0 5 votes vote down vote up
public String resolveTemplate(FreemarkerDataModel dataModel, Template template) throws IntegrationException {
    try {
        StringWriter stringWriter = new StringWriter();
        template.process(dataModel, stringWriter);
        return stringWriter.toString();
    } catch (IOException | TemplateException e) {
        throw new IntegrationException(e.getMessage(), e);
    }
}
 
Example #20
Source File: CrafterTemplateExceptionHandler.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void handleTemplateException(TemplateException te, Environment env, Writer out) throws TemplateException {
    if (displayTemplateExceptionsInView) {
        String error = ERROR_FORMAT.replace("{errorId}", createErrorId());
        error = error.replace("{error}", getExceptionStackTrace(te));

        try {
            out.write(error);
        } catch (IOException e) {
            throw new TemplateException("Failed to print error. Cause: " + e, env);
        }
    }
}
 
Example #21
Source File: RoleTag.java    From SpringBoot-Base-System with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void render(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateDirectiveBody body) throws IOException, TemplateException {
    boolean show = showTagBody(getName(params));
    if (show) {
        renderBody(env, body);
    }
}
 
Example #22
Source File: DownloadEmailUtils.java    From occurrence with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
protected String buildBody(Download download, String bodyTemplate) throws IOException, TemplateException {
  // Prepare the E-Mail body text
  StringWriter contentBuffer = new StringWriter();
  Template template = freemarker.getTemplate(bodyTemplate);
  template.process(new EmailModel(download, portalUrl, getHumanQuery(download)), contentBuffer);
  return contentBuffer.toString();
}
 
Example #23
Source File: FreeMarkerService.java    From freemarker-online-tester with Apache License 2.0 5 votes vote down vote up
private FreeMarkerService(Builder bulder) {
     maxOutputLength = bulder.getMaxOutputLength();
     maxThreads = bulder.getMaxThreads();
     maxQueueLength = bulder.getMaxQueueLength();
     maxTemplateExecutionTime = bulder.getMaxTemplateExecutionTime();

     int actualMaxQueueLength = maxQueueLength != null
             ? maxQueueLength
             : Math.max(
                     MIN_DEFAULT_MAX_QUEUE_LENGTH,
                     (int) (MAX_DEFAULT_MAX_QUEUE_LENGTH_MILLISECONDS / maxTemplateExecutionTime));
     ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
             maxThreads, maxThreads,
             THREAD_KEEP_ALIVE_TIME, TimeUnit.MILLISECONDS,
             new BlockingArrayQueue<Runnable>(actualMaxQueueLength));
     threadPoolExecutor.allowCoreThreadTimeOut(true);
     templateExecutor = threadPoolExecutor;

     // Avoid ERROR log for using the actual current version. This application is special in that regard.
     Version latestVersion = new Version(Configuration.getVersion().toString());

     freeMarkerConfig = new Configuration(latestVersion);
     freeMarkerConfig.setNewBuiltinClassResolver(TemplateClassResolver.ALLOWS_NOTHING_RESOLVER);
     freeMarkerConfig.setObjectWrapper(new SimpleObjectWrapperWithXmlSupport(latestVersion));
     freeMarkerConfig.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
     freeMarkerConfig.setLogTemplateExceptions(false);
     freeMarkerConfig.setAttemptExceptionReporter(new AttemptExceptionReporter() {
@Override
public void report(TemplateException te, Environment env) {
	// Suppress it
}
     });
     freeMarkerConfig.setLocale(AllowedSettingValues.DEFAULT_LOCALE);
     freeMarkerConfig.setTimeZone(AllowedSettingValues.DEFAULT_TIME_ZONE);
     freeMarkerConfig.setOutputFormat(AllowedSettingValues.DEFAULT_OUTPUT_FORMAT);
     freeMarkerConfig.setOutputEncoding("UTF-8");
 }
 
Example #24
Source File: AzureCredentialAppCreationCommandTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenerateWhenFreemarkerConfigGetTemplateThrowsMalformedTemplateNameExceptionThenCloudConnectorExceptionComesForAppCreationCommandTemplate()
        throws IOException, TemplateException {
    doThrow(new MalformedTemplateNameException(TEMPLATE_NAME, MALFORMED_TEMPLATE_NAMED_EXCEPTION_DESCRIPTION)).when(freemarkerConfiguration)
            .getTemplate(APP_CREATION_COMMAND_TEMPLATE_PATH, ENCODING);

    thrown.expect(CloudConnectorException.class);
    thrown.expectMessage(format(GENERATE_EXCEPTION_MESSAGE_FORMAT, APP_CREATION_COMMAND_TEMPLATE_PATH));

    underTest.generate(DEPLOYMENT_ADDRESS);

    verify(template, times(0)).process(any(), any(StringWriter.class));
    verify(freemarkerConfiguration, times(1)).getTemplate(anyString(), anyString());
    verify(freemarkerConfiguration, times(1)).getTemplate(APP_CREATION_COMMAND_TEMPLATE_PATH, ENCODING);
}
 
Example #25
Source File: AwsNetworkCfTemplateProviderTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testProvideWhenPrivateSubnetsAndInterfaceServicesAreDisabled() throws IOException, TemplateException {
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode expectedJson = objectMapper.readTree(new File("src/test/resources/json/aws-cf-network-privatesubnet-onlygatewayvpcendpoints.json"));

    when(freeMarkerTemplateUtils.processTemplateIntoString(any(), any())).thenCallRealMethod();
    NetworkCreationRequest networkCreationRequest = createNetworkRequest(true, false);
    List<SubnetRequest> subnetRequestList = createPrivateAndPublicSubnetRequestList();

    String actual = underTest.provide(networkCreationRequest, subnetRequestList);

    JsonNode json = objectMapper.readTree(actual);
    assertEquals(expectedJson, json);
    verify(freeMarkerTemplateUtils).processTemplateIntoString(any(Template.class), anyMap());
}
 
Example #26
Source File: MavenUtils.java    From camel-kafka-connector with Apache License 2.0 5 votes vote down vote up
public static Document createCrateXmlDocumentFromTemplate(Template template, Map<String, String> props) throws IOException, TemplateException, ParserConfigurationException, SAXException {
    StringWriter sw = new StringWriter();
    template.process(props, sw);

    String xml = sw.toString();
    ByteArrayInputStream bin = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));

    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    return builder.parse(bin);
}
 
Example #27
Source File: GenerateHQL.java    From occurrence with Apache License 2.0 5 votes vote down vote up
/**
 * Generates the Hive query file used for DwCA downloads.
 */
private static void generateQueryHQL(Configuration cfg, File outDir) throws IOException, TemplateException {
  try (FileWriter out = new FileWriter(new File(outDir, "execute-query.q"))) {
    Template template = cfg.getTemplate("download/execute-query.ftl");
    Map<String, Object> data = ImmutableMap.of(
      "verbatimFields", HIVE_QUERIES.selectVerbatimFields().values(),
      "interpretedFields", HIVE_QUERIES.selectInterpretedFields(false).values(),
      "initializedInterpretedFields", HIVE_QUERIES.selectInterpretedFields(true).values()
    );
    template.process(data, out);
  }
}
 
Example #28
Source File: AwsNetworkCfTemplateProviderTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testProvideWhenPublicSubnetsAndInterfaceServicesAreDisabled() throws IOException, TemplateException {
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode expectedJson = objectMapper.readTree(new File("src/test/resources/json/aws-cf-network-publicsubnet-onlygatewayvpcendpoints.json"));

    when(freeMarkerTemplateUtils.processTemplateIntoString(any(), any())).thenCallRealMethod();
    NetworkCreationRequest networkCreationRequest = createNetworkRequest(false, false);
    List<SubnetRequest> subnetRequestList = createPrivateAndPublicSubnetRequestList();

    String actual = underTest.provide(networkCreationRequest, subnetRequestList);

    JsonNode json = objectMapper.readTree(actual);
    assertEquals(expectedJson, json);
    verify(freeMarkerTemplateUtils).processTemplateIntoString(any(Template.class), anyMap());
}
 
Example #29
Source File: BootRestGenerator.java    From flyer-maker with MIT License 5 votes vote down vote up
@Override
public void makeCustom() throws IOException, TemplateException {
    GU.f(concat(basePackageDir, "App.java"), concat(Config.projectType, "App.java"));
    GU.f(concat(basePackageDir, "common", "WebMvcConfig.java"),
        concat(Config.projectType, "WebMvcConfig"));
    generatorResources();
    generatorTestResources();
}
 
Example #30
Source File: BaseProgen.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
public void project() throws IOException, TemplateException, DocumentException {
    Properties root = getRootProperties();
    GenProperties.projectName = System.getProperty("projectName");

    root.putAll(StringHelper.getDirValuesMap(root));

    Boolean hasClient = false;
    String  webType   = System.getProperty("webType");
    if (StringUtil.isNotBlank(webType) && !"-e".equals(webType)) {
        hasClient = true;
        root.put("webType", webType);
    } else {
        root.put("webType", "");
    }
    root.put("hasClient", hasClient);

    String projectTempPath   = FileHelpers.getCanonicalPath(GenProperties.dir_templates_root + "/java/project@/");
    String projectFolderName = processTempleteFiles(root, projectTempPath);

    String projectsPomXmlFilename = StringUtil.concatPath(GenProperties.getProjectsPath(), "pom.xml");
    //dom4j格式化输出把换行等全部去掉,因此这里采用text输出
    String pomXmlText = XmlUtil.appendToNode(projectsPomXmlFilename, "module", projectFolderName);
    if (StringUtil.isNotEmpty(pomXmlText)) {
        IOHelpers.saveFile(new File(projectsPomXmlFilename), pomXmlText, StringUtil.UTF_8);
        if (logger.isInfoEnabled()) {
            logger.info(new StringBuffer("修改pom成功:").append(projectsPomXmlFilename).toString());
        }
    }
    if (hasClient) {
        processClient(root, hasClient, webType, projectFolderName);
    }

}