Java Code Examples for freemarker.template.TemplateException

The following are top voted examples for showing how to use freemarker.template.TemplateException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: tdl-auth   File: LinkGeneratorLambdaTest.java   Source Code and License 8 votes vote down vote up
@Test
public void handleRequestShouldThrowException() throws TemplateException, KeyOperationException, IOException {
    expectedException.expect(RuntimeException.class);
    expectedException.expectMessage("Email");
    LinkGeneratorLambdaHandler handler = mock(LinkGeneratorLambdaHandler.class);
    doCallRealMethod().when(handler).handleRequest(any(), any());
    Exception ex = new TemplateException("Message", null);
    doThrow(ex).when(handler).getUploadPageUrlFromRequest(any(), any());
    
    Context context = mock(Context.class);
    LambdaLogger logger = mock(LambdaLogger.class);
    doNothing().when(logger).log(anyString());
    doReturn(logger).when(context).getLogger();
    
    handler.handleRequest(mock(LinkGeneratorRequest.class), context);
}
 
Example 2
Project: synthea_java   File: CCDAExporter.java   Source Code and License 6 votes vote down vote up
private static Configuration templateConfiguration() {
  Configuration configuration = new Configuration(Configuration.VERSION_2_3_26);
  configuration.setDefaultEncoding("UTF-8");
  configuration.setLogTemplateExceptions(false);
  try {
    configuration.setSetting("object_wrapper",
        "DefaultObjectWrapper(2.3.26, forceLegacyNonListCollections=false, "
            + "iterableSupport=true, exposeFields=true)");
  } catch (TemplateException e) {
    e.printStackTrace();
  }
  configuration.setAPIBuiltinEnabled(true);
  configuration.setClassLoaderForTemplateLoading(ClassLoader.getSystemClassLoader(),
      "templates/ccda");
  return configuration;
}
 
Example 3
Project: Android_Code_Arbiter   File: FreemarkerUsage.java   Source Code and License 6 votes vote down vote up
public void allSignatures(String inputFile) throws IOException, TemplateException {
    Configuration cfg = new Configuration();
    Template template = cfg.getTemplate(inputFile);
    Map<String, Object> data = new HashMap<String, Object>();

    template.process(data, new OutputStreamWriter(System.out)); //TP
    template.process(data, new OutputStreamWriter(System.out), null); //TP
    template.process(data, new OutputStreamWriter(System.out), null, null); //TP
}
 
Example 4
Project: support-rulesengine   File: RuleCreator.java   Source Code and License 6 votes vote down vote up
public String createDroolRule(Rule rule) throws TemplateException, IOException {
  try {
    Template temp = cfg.getTemplate(templateName);
    Writer out = new StringWriter();
    temp.process(createMap(rule), out);
    return out.toString();
  } catch (IOException iE) {
    logger.error("Problem getting rule template file." + iE.getMessage());
    throw iE;
  } catch (TemplateException tE) {
    logger.error("Problem writing Drool rule." + tE.getMessage());
    throw tE;
  } catch (Exception e) {
    logger.error("Problem creating rule: " + e.getMessage());
    throw e;
  }
}
 
Example 5
Project: magic-beanstalk   File: FileGeneratorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void generateUserDockerrunFileTest() throws IOException, TemplateException {
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("awsEBDockerrunVersion", "2");
    parameters.put("hostPort", "80");
    parameters.put("configFile", "config.yml");
    parameters.put("containerPort", "80");
    parameters.put("memory", "2");
    parameters.put("awsEBDockerrunVersion", "6144");
    FileGenerator.generateUserDockerrunFile(
            "src/test/resources/DockerrunTemplate.ftlh",
            "src/test/resources/testUserDockerrunFile.aws.json",
            parameters
    );

    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> generatedTestData = mapper.readValue(new File("src/test/resources/testUserDockerrunFile.aws.json"), Map.class);
    Map<String, Object> expectedTestData = mapper.readValue(new File("src/test/resources/expectedDockerrunFile.aws.json"), Map.class);

    for (String k : generatedTestData.keySet()) {
        Assert.assertTrue(generatedTestData.get(k).equals(expectedTestData.get(k)));
    }

    File generatedTestFile = new File("src/test/resources/testUserDockerrunFile.aws.json");
    generatedTestFile.delete();
}
 
Example 6
Project: magic-beanstalk   File: FileGeneratorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void generateDefaultDockerrunFileTest() throws IOException, TemplateException {
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("awsEBDockerrunVersion", "2");
    parameters.put("hostPort", "80");
    parameters.put("configFile", "config.yml");
    parameters.put("containerPort", "80");
    parameters.put("memory", "2");
    parameters.put("awsEBDockerrunVersion", "6144");
    FileGenerator.generateDefaultDockerrunFile(
            "src/test/resources/defaultGeneratedDockerrun.aws.json",
            parameters
    );

    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> generatedTestData = mapper.readValue(new File("src/test/resources/defaultGeneratedDockerrun.aws.json"), Map.class);
    Map<String, Object> expectedTestData = mapper.readValue(new File("src/test/resources/expectedDockerrunFile.aws.json"), Map.class);

    for (String k : generatedTestData.keySet()) {
        Assert.assertTrue(generatedTestData.get(k).equals(expectedTestData.get(k)));
    }

    File generatedTestFile = new File("src/test/resources/defaultGeneratedDockerrun.aws.json");
    generatedTestFile.delete();
}
 
Example 7
Project: tdl-auth   File: LinkGeneratorLambdaHandler.java   Source Code and License 6 votes vote down vote up
LinkGeneratorLambdaHandler(String region, String jwtEncryptKeyArn, String pageStorageBucket, String authVerifyEndpointURL,
                           AWSCredentialsProvider awsCredential, String introPageTemplateName) throws IOException, TemplateException {
    AWSKMS kmsClient = AWSKMSClientBuilder.standard()
            .withCredentials(awsCredential)
            .withRegion(region)
            .build();
    AmazonS3 s3client = AmazonS3ClientBuilder
            .standard()
            .withCredentials(awsCredential)
            .withRegion(region)
            .build();
    kmsEncrypt = new KMSEncrypt(kmsClient, jwtEncryptKeyArn);
    this.pageStorageBucket = pageStorageBucket;
    this.authVerifyEndpointURL = authVerifyEndpointURL;
    this.pageUploader = new PageUploader(s3client, pageStorageBucket);


    this.introPageTemplate = new IntroPageTemplate(introPageTemplateName);
}
 
Example 8
Project: nixmash-blog   File: FmServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public String displayTestTemplate(User user) {

    String applicationPropertyUrl = environment.getProperty("spring.application.url");
    String siteName = mailUI.getMessage("mail.site.name");
    String greeting = "YOUSA!";

    Map<String, Object> model = new Hashtable<>();
    model.put("siteName", siteName);
    model.put("greeting", greeting);
    model.put("user", user);
    model.put("applicationPropertyUrl", applicationPropertyUrl);

    String result = null;

    try {
        Template template = fm.getTemplate("tests/test.ftl");
        result = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
    } catch (IOException | TemplateException e) {
        logger.error("Problem merging test template : " + e.getMessage());
    }
    return result;
}
 
Example 9
Project: nixmash-blog   File: FmServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public String createRssPostContent(Post post) {
    String html = null;

    Map<String, Object> model = new Hashtable<>();

    model.put("post", post);
    model.put("baseurl", applicationSettings.getBaseUrl());

    try {
        Template template = fm.getTemplate("posts/rss_post.ftl");
        html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
    } catch (IOException | TemplateException e) {
        logger.error("Problem merging post template : " + e.getMessage());
    }
    return html;
}
 
Example 10
Project: nixmash-blog   File: FmServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public String createPostHtml(Post post, String templateName) {
    String html = null;
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM dd, yyyy");
    String postCreated = post.getPostDate().format(formatter);

    Map<String, Object> model = new Hashtable<>();

    model.put("post", post);
    model.put("postCreated", postCreated);
    model.put("shareSiteName",
            StringUtils.deleteWhitespace(applicationSettings.getSiteName()));
    model.put("shareUrl",
            String.format("%s/post/%s", applicationSettings.getBaseUrl(), post.getPostName()));

    String displayType = templateName == null ? post.getDisplayType().name().toLowerCase() : templateName;
    String ftl = String.format("posts/%s.ftl", displayType);

    try {
        Template template = fm.getTemplate(ftl);
        html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
    } catch (IOException | TemplateException e) {
        logger.error("Problem merging post template : " + e.getMessage());
    }
    return html;
}
 
Example 11
Project: nixmash-blog   File: FmServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public String createPostAtoZs() {
    String html = null;

    String backToTop = mailUI.getMessage("posts.az.page.backtotop");
    String azFileName = environment.getProperty("posts.az.file.name");
    String azFilePath = applicationSettings.getPostAtoZFilePath();

    Map<String, Object> model = new Hashtable<>();
    model.put("alphaLinks", postService.getAlphaLInks());
    model.put("alphaPosts", postService.getAlphaPosts());
    model.put("backToTop", backToTop);

    try {
        Template template = fm.getTemplate("posts/az.ftl");
        html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
        InputStream in = IOUtils.toInputStream(html, "UTF-8");
        FileUtils.copyInputStreamToFile(in, new File(azFilePath + azFileName));
    } catch (IOException | TemplateException e) {
        logger.error("Problem creating A-to-Z template or HTML file: " + e.getMessage());
    }
    return html;
}
 
Example 12
Project: dingtalk-incoming-webhoot-plugin   File: DingtalkNotificationPlugin.java   Source Code and License 6 votes vote down vote up
private String generateMessage(String trigger, Map executionData, Map config) {

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

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

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

        return sw.toString();
    }
 
Example 13
Project: Equella   File: ListRendererDirective.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings({"nls"})
@Override
protected void writeMiddle(SectionWriter writer) throws IOException
{
	List<Option<?>> options = listState.getOptions();
	for( Option<?> option : options )
	{
		writer.writeTag("li");
		writer.writeTag("input", "type", "hidden", "name", listState.getName(), "value", option.getValue());
		loopVars[0] = new BeanModel(option, wrapper);
		try
		{
			body.render(writer);
		}
		catch( TemplateException e )
		{
			SectionUtils.throwRuntime(e);
		}
		writer.endTag("li");
	}
}
 
Example 14
Project: Equella   File: BooleanListDirective.java   Source Code and License 6 votes vote down vote up
@Override
protected void writeMiddle(SectionWriter writer) throws IOException
{
	List<ListOption<Object>> optionList = renderer.renderOptionList(writer);
	for( ListOption<Object> listOption : optionList )
	{
		Option<Object> option = listOption.getOption();
		HtmlBooleanState state = listOption.getBooleanState();
		state.setLabel(new TextLabel(option.getName(), true));
		loopVars[0] = new BeanModel(option, wrapper);
		loopVars[1] = new BeanModel(state, wrapper);
		try
		{
			body.render(writer);
		}
		catch( TemplateException e )
		{
			throw Throwables.propagate(e);
		}
	}
}
 
Example 15
Project: tdl-auth   File: IntroPageTemplate.java   Source Code and License 6 votes vote down vote up
public String generateContent(String mainChallengeTitle,
                              String sponsorName,
                              String codingSessionDurationLabel, String username,
                              String token,
                              String authVerifyEndpointUrl,
                              Date expirationDate,
                              String journeyId)
        throws IOException, TemplateException {
    StringWriter stringWriter = new StringWriter();
    Map<String, String> contentParams = new HashMap<>();
    contentParams.put("MAIN_CHALLENGE_TITLE", mainChallengeTitle);
    contentParams.put("SPONSOR", sponsorName);
    contentParams.put("EXPIRATION_DATE", dateFormatter.format(expirationDate));
    contentParams.put("CODING_SESSION_DURATION", codingSessionDurationLabel);
    contentParams.put("API_VERIFY_ENDPOINT", authVerifyEndpointUrl);
    contentParams.put("USERNAME", username);
    contentParams.put("TOKEN", token);
    contentParams.put("JOURNEY_ID", journeyId);
    template.process(contentParams, stringWriter);
    return stringWriter.toString();
}
 
Example 16
Project: cluecumber-report-plugin   File: StartPageRenderer.java   Source Code and License 6 votes vote down vote up
public String getRenderedContent(
        final StartPageCollection startPageCollection, final Template template)
        throws CluecumberPluginException {

    ReportDetails reportDetails = new ReportDetails();
    addChartJsonToReportDetails(startPageCollection, reportDetails);
    addCurrentDateToReportDetails(reportDetails);
    addCustomParametersToReportDetails(startPageCollection);
    startPageCollection.setReportDetails(reportDetails);

    Writer stringWriter = new StringWriter();
    try {
        template.process(startPageCollection, stringWriter);
    } catch (TemplateException | IOException e) {
        throw new CluecumberPluginException(e.getMessage());
    }
    return stringWriter.toString();
}
 
Example 17
Project: tdl-auth   File: Mailer.java   Source Code and License 6 votes vote down vote up
public void send() throws IOException, TemplateException {
    client = createClient();
    Destination destination = new Destination().withToAddresses(new String[]{email});
    Content subject = new Content().withData(SUBJECT);
    String bodyContent = createBody();
    Content textContent = new Content().withData(bodyContent);
    Body body = new Body().withText(textContent);
    Message message = new Message()
            .withSubject(subject)
            .withBody(body);
    SendEmailRequest request = new SendEmailRequest()
            .withSource(getSender())
            .withDestination(destination)
            .withMessage(message);

    client.sendEmail(request);
}
 
Example 18
Project: incubator-freemarker-online-tester   File: ExceptionUtils.java   Source Code and License 6 votes vote down vote up
/**
 * The error message (and sometimes also the class), and then the same with the cause exception, and so on. Doesn't
 * contain the stack trace or other location information.
 */
public static String getMessageWithCauses(final Throwable exc) {
    StringBuilder sb = new StringBuilder();
    
    Throwable curExc = exc;
    while (curExc != null) {
        if (curExc != exc) {
            sb.append("\n\nCaused by:\n");
        }
        String msg = curExc.getMessage();
        if (msg == null || !(curExc instanceof TemplateException || curExc instanceof ParseException)) {
            sb.append(curExc.getClass().getName()).append(": ");
        }
        sb.append(msg);
        curExc = curExc.getCause();
    }
    return sb.toString();
}
 
Example 19
Project: incubator-freemarker-online-tester   File: FreeMarkerServiceTest.java   Source Code and License 6 votes vote down vote up
@Override
public synchronized void execute(Environment env, @SuppressWarnings("rawtypes") Map params,
        TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
    entered++;
    notifyAll();
    final long startTime = System.currentTimeMillis();
    while (!released) {
        // To avoid blocking the CI server forever is something goes wrong:
        if (System.currentTimeMillis() - startTime > BLOCKING_TEST_TIMEOUT) {
            LOG.error("JUnit test timed out");
        }
        try {
            wait(1000);
        } catch (InterruptedException e) {
            LOG.error("JUnit test was interrupted");
        }
    }
    LOG.debug("Blocker released");
}
 
Example 20
Project: EM   File: BndPlugin.java   Source Code and License 5 votes vote down vote up
public void addToBuild(MavenProject project) throws MavenExecutionException {

		String includePackages = project.getProperties().getProperty(PROP_MODULE_INCLUDE_PACKAGES, "");
		String importPackages = project.getProperties().getProperty(PROP_MODULE_IMPORT_PACKAGES, "");
		String ignorePackages = project.getProperties().getProperty(PROP_MODULE_IGNORE_PACKAGES, "");
		
		StringBuilder importStatement = new StringBuilder();
		if (!ignorePackages.isEmpty()) {
			Arrays.stream(ignorePackages.split(",")).forEach(p -> importStatement.append("!").append(p).append(","));
		}
		if (!importPackages.isEmpty()) {
			importStatement.append(importPackages).append(",");
		}
		importStatement.append("*");
		
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("includePackages", includePackages);
		model.put("importStatement", importStatement);
		
		String bndContent = null;
		try {
			bndContent = templates.process("META-INF/templates/bnd.fmt", model);
		} catch (IOException | TemplateException e) {
			throw new MavenExecutionException("Failed to process template file!", e);
		}
				
		StringBuilder configuration = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") //
				.append("<configuration><bnd><![CDATA[ \n") //
				.append(bndContent)
				.append("]]></bnd></configuration>"); //

		logger.debug("Generated bnd-maven-plugin confgiguration: \n {}", configuration);
		
		project.getBuild().getPlugins().add(0, preparePlugin(configuration.toString()));

		configureJarPlugin(project);
		
		logger.info("Added `bnd-maven-plugin` to generate metadata");

	}
 
Example 21
Project: EM   File: BndExportPlugin.java   Source Code and License 5 votes vote down vote up
private void generateBndrun(MavenProject project, String distro, File bndFile) throws MavenExecutionException {

		Set<String> requirements = new HashSet<>();
		requirements.add("osgi.identity;filter:='(osgi.identity=" + project.getArtifactId() + ")'");

		String contracts = project.getProperties().getProperty(PROP_CONTRACTS);
		if (contracts != null && !contracts.trim().isEmpty()) {
			String[] contractsArray = contracts.split("[\\s]*,[\\s]*");
			for (String contract : contractsArray) {
				requirements.add("em.contract;filter:='(em.contract=" + contract + ")';effective:=assemble");
			}
		}

		Set<String> runProperties = new HashSet<>();
		
		String runPropertiesText = project.getProperties().getProperty(PROP_EXECUTABLE_RUN_PROPERTIES);
		if (runPropertiesText != null && !runPropertiesText.trim().isEmpty()) {
			String[] propertiesArray = runPropertiesText.split("[\\s]*\\n[\\s]*");
			runProperties.addAll(Arrays.asList(propertiesArray));
		}
		
		
		Map<String, Object> model = new HashMap<>();
		model.put("requirements", requirements);
		model.put("runProperties", runProperties);
		model.put("distro", distro);

		String bndrunContent = null;
		try {
			bndrunContent = templates.process("META-INF/templates/bndrun.fmt", model);
		} catch (IOException | TemplateException e) {
			throw new MavenExecutionException("Failed to process template file!", e);
		}

		if (logger.isDebugEnabled())
			logger.debug("Generated bndrun file: \n{}", bndrunContent);

		writeBndrun(bndFile, bndrunContent);

	}
 
Example 22
Project: incubator-netbeans   File: RsrcLoader.java   Source Code and License 5 votes vote down vote up
public void handleTemplateException(TemplateException ex, Environment env, Writer w) throws TemplateException {
    try {
        w.append(ex.getLocalizedMessage());
        LOG.log(Level.INFO, "Failure processing " + fo, ex);
        LOG.log(Level.INFO, "Bindings:"); // NOI18N
        for (Map.Entry<String, Object> entry : engineScope.entrySet()) {
            LOG.log(Level.INFO, "  key: " + entry.getKey() + " value: " + entry.getValue()); // NOI18N
        }
    } catch (IOException e) {
        Exceptions.printStackTrace(e);
    }
}
 
Example 23
Project: incubator-netbeans   File: ProcessorTest.java   Source Code and License 5 votes vote down vote up
@Override
public void handleTemplateException(TemplateException te, Environment e, Writer writer) throws TemplateException {
    if (exceptions == null) {
        exceptions = new ArrayList<TemplateException>();
    }
    exceptions.add(te);
    try {
        writer.append(te.getLocalizedMessage());
    } catch (IOException ioex) {
        Exceptions.printStackTrace(ioex);
    }
}
 
Example 24
Project: tdl-auth   File: IntroPageTemplateUploaderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void createClient() throws IOException, TemplateException {
    AmazonS3ClientBuilder
            .standard()
            .build();
    Object client = AmazonS3ClientBuilder
            .standard()
            .build();
    assertThat(client, instanceOf(AmazonS3.class));
}
 
Example 25
Project: magic-beanstalk   File: FileGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * Generate a dockerrun.aws.json file with a custom user template
 * @param dockerrunFilePath the location of the dockerrun template
 * @param dockerrunOutputDestination the output directory
 * @param parameters a map to hydrate the template with
 * @throws IOException if failed to load the template file
 * @throws TemplateException if template generation fails
 */
public static void generateUserDockerrunFile(
    String dockerrunFilePath,
    String dockerrunOutputDestination,
    Map<String, Object> parameters
) throws IOException, TemplateException {
  File templateFile = new File(dockerrunFilePath);
  Configuration cfg = initializeTemplateConfiguration();
  cfg.setDirectoryForTemplateLoading(templateFile.getParentFile());
  generateFileFromTemplate(cfg, templateFile.getName(), dockerrunOutputDestination, parameters);

}
 
Example 26
Project: magic-beanstalk   File: FileGenerator.java   Source Code and License 5 votes vote down vote up
/**
 *Generate a dockerrun.aws.json file with the default template
 * @param outputFilePath the output directory
 * @param parameters a map to hydrate the default template with
 * @throws IOException if failed to load the template file
 * @throws TemplateException if template generation fails
 */
public static void generateDefaultDockerrunFile(
    String outputFilePath,
    Map<String, Object> parameters
) throws IOException, TemplateException {
  Configuration cfg = initializeTemplateConfiguration();
  cfg.setClassForTemplateLoading(FileGenerator.class, "/");
  final String defaultDockerrunTemplateFile = "DockerrunTemplate.ftlh";
  generateFileFromTemplate(cfg, defaultDockerrunTemplateFile, outputFilePath, parameters);
}
 
Example 27
Project: magic-beanstalk   File: FileGenerator.java   Source Code and License 5 votes vote down vote up
private static void generateFileFromTemplate(Configuration cfg,
    String templateFile,
    String outputFilePath,
    Map<String, Object> parameters) throws IOException, TemplateException {
  Template temp = cfg.getTemplate(templateFile);
  File file = new File(outputFilePath);
  if (file.getParent() != null) {
    file.getParentFile().mkdirs();
  }
  FileWriter writer = new FileWriter(file);
  temp.process(parameters, writer);
}
 
Example 28
Project: alfresco-repository   File: FeedTaskProcessor.java   Source Code and License 5 votes vote down vote up
protected String processFreemarker(Map<String, Template> templateCache, String fmTemplate, Configuration cfg, Map<String, Object> model) throws IOException, TemplateException, Exception
{
    // Save on lots of modification date checking by caching templates locally
    Template myTemplate = templateCache.get(fmTemplate);
    if (myTemplate == null)
    {
        myTemplate = cfg.getTemplate(fmTemplate);
        templateCache.put(fmTemplate, myTemplate);
    }
    
    StringWriter textWriter = new StringWriter();
    myTemplate.process(model, textWriter);
    
    return textWriter.toString();
}
 
Example 29
Project: otus_java_2017_06   File: TemplateProcessor.java   Source Code and License 5 votes vote down vote up
String getPage(String filename, Map<String, Object> data) throws IOException {
    try (Writer stream = new StringWriter();) {
        Template template = configuration.getTemplate(filename);
        template.process(data, stream);
        return stream.toString();
    } catch (TemplateException e) {
        throw new IOException(e);
    }
}
 
Example 30
Project: otus_java_2017_06   File: TemplateProcessor.java   Source Code and License 5 votes vote down vote up
String getPage(String filename, Map<String, Object> data) throws IOException {
    try (Writer stream = new StringWriter();) {
        Template template = configuration.getTemplate(filename);
        template.process(data, stream);
        return stream.toString();
    } catch (TemplateException e) {
        throw new IOException(e);
    }
}
 
Example 31
Project: otus_java_2017_06   File: TemplateProcessor.java   Source Code and License 5 votes vote down vote up
String getPage(String filename, Map<String, Object> data) throws IOException {
    try (Writer stream = new StringWriter();) {
        Template template = configuration.getTemplate(filename);
        template.process(data, stream);
        return stream.toString();
    } catch (TemplateException e) {
        throw new IOException(e);
    }
}
 
Example 32
Project: otus_java_2017_06   File: TemplateProcessor.java   Source Code and License 5 votes vote down vote up
public String getPage(String filename, Map<String, Object> data) throws IOException {
    try (Writer stream = new StringWriter();) {
        Template template = configuration.getTemplate(HTML_DIR + File.separator + filename);
        template.process(data, stream);
        return stream.toString();
    } catch (TemplateException e) {
        throw new IOException(e);
    }
}
 
Example 33
Project: otus_java_2017_06   File: TemplateProcessor.java   Source Code and License 5 votes vote down vote up
String getPage(String filename, Map<String, Object> data) throws IOException {
    try (Writer stream = new StringWriter();) {
        Template template = configuration.getTemplate(filename);
        template.process(data, stream);
        return stream.toString();
    } catch (TemplateException e) {
        throw new IOException(e);
    }
}
 
Example 34
Project: otus_java_2017_06   File: TemplateProcessor.java   Source Code and License 5 votes vote down vote up
String getPage(String filename, Map<String, Object> data) throws IOException {
    try (Writer stream = new StringWriter();) {
        Template template = configuration.getTemplate(filename);
        template.process(data, stream);
        return stream.toString();
    } catch (TemplateException e) {
        throw new IOException(e);
    }
}
 
Example 35
Project: tdl-auth   File: LinkGeneratorLambdaHandler.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings({"unused", "WeakerAccess"})
public LinkGeneratorLambdaHandler() throws IOException, TemplateException {
    this(
            getEnv("AUTH_REGION"),
            getEnv("JWT_ENCRYPT_KEY_ARN"),
            getEnv("PAGE_STORAGE_BUCKET"),
            getEnv("AUTH_ENDPOINT_URL"),
            DefaultAWSCredentialsProviderChain.getInstance(),
            "intro.html.ftl");
}
 
Example 36
Project: otus_java_2017_06   File: TemplateProcessor.java   Source Code and License 5 votes vote down vote up
String getPage(String filename, Map<String, Object> data) throws IOException {
    try (Writer stream = new StringWriter();) {
        Template template = configuration.getTemplate(HTML_DIR + File.separator + filename);
        template.process(data, stream);
        return stream.toString();
    } catch (TemplateException e) {
        throw new IOException(e);
    }
}
 
Example 37
Project: NoMoreOversleeps   File: WebServlet.java   Source Code and License 5 votes vote down vote up
/**
 * Sends the main HTML page of the WebUI.
 * 
 * @param response
 * @throws TemplateNotFoundException
 * @throws MalformedTemplateNameException
 * @throws ParseException
 * @throws IOException
 * @throws ServletException
 */
private void sendMainPage(HttpServletResponse response) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, ServletException
{
	HashMap<String, Object> model = new HashMap<String, Object>();
	model.put("version", Main.VERSION);
	model.put("system", PlatformData.computerName);
	model.put("actionButtons", this.determineWebUIButtons());
	model.put("webcamKey", NMOConfiguration.INSTANCE.integrations.webUI.webcamSecurityKey);
	model.put("camTotal", WebcamCapture.webcams.length);
	model.put("message", NMOConfiguration.INSTANCE.integrations.webUI.message);
	model.put("username", NMOConfiguration.INSTANCE.integrations.webUI.username);
	String[] cc = new String[WebcamCapture.webcams.length];
	for (int i = 0; i < WebcamCapture.webcams.length; i++)
	{
		cc[i] = WebcamCapture.webcams[i].cc;
	}
	model.put("webcams", cc);
	for (Integration integration : Main.integrations)
	{
		model.put("integration_" + integration.id, integration.isEnabled());
	}
	try
	{
		WebTemplate.renderTemplate("nmo.ftl", response, model);
	}
	catch (TemplateException e)
	{
		throw new ServletException(e);
	}
}
 
Example 38
Project: tdl-auth   File: MailerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void send() throws IOException, TemplateException {
    Mailer mailer = mock(Mailer.class);
    mailer.setTemplateConfiguration(LinkGeneratorLambdaHandler.templateConfiguration);
    doReturn("Content").when(mailer).createBody();
    doCallRealMethod().when(mailer).send();

    AmazonSimpleEmailService client = mock(AmazonSimpleEmailService.class);
    doReturn(mock(SendEmailResult.class)).when(client).sendEmail(any());
    doReturn(client).when(mailer).createClient();

    mailer.send();
    verify(client, times(1)).sendEmail(any());
}
 
Example 39
Project: tdl-auth   File: MailerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void createClient() throws IOException, TemplateException {
    Mailer mailer = mock(Mailer.class);
    doCallRealMethod().when(mailer).createClient();
    Object client = mailer.createClient();
    assertThat(client, instanceOf(AmazonSimpleEmailService.class));
}
 
Example 40
Project: nixmash-blog   File: FmServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public String getNoResultsMessage(String search) {
    String result = null;
    Map<String, Object> model = new Hashtable<>();

    model.put("search", search);
    try {
        result =  FreeMarkerTemplateUtils.processTemplateIntoString(fm.getTemplate("posts/noresults.ftl"), model);
    } catch (IOException | TemplateException e) {
        logger.error("Problem merging Quick Search template : " + e.getMessage());
    }
    return result;
}
 
Example 41
Project: nixmash-blog   File: FmServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public String getNoLikesMessage() {
    String result = null;
    try {
        result =  FreeMarkerTemplateUtils.processTemplateIntoString(fm.getTemplate("posts/nolikes.ftl"), null);
    } catch (IOException | TemplateException e) {
        logger.error("Problem merging NoLikes template : " + e.getMessage());
    }
    return result;
}
 
Example 42
Project: nixmash-blog   File: FmServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public String getNoMoreLikeThisMessage() {
    String result = null;
    Map<String, Object> model = new Hashtable<>();

    try {
        result =  FreeMarkerTemplateUtils.processTemplateIntoString(fm.getTemplate("posts/nomlts.ftl"), model);
    } catch (IOException | TemplateException e) {
        logger.error("Problem merging No MoreLikeThis template : " + e.getMessage());
    }
    return result;
}
 
Example 43
Project: tdl-auth   File: LinkGeneratorLambdaHandler.java   Source Code and License 5 votes vote down vote up
String getUploadPageUrlFromRequest(LinkGeneratorRequest request, Context context) throws KeyOperationException, IOException, TemplateException {
    Predicate<LinkGeneratorRequest> mainChallengeTitle = req -> req.getMainChallengeTitle() != null;
    if (!mainChallengeTitle.test(request)) throw new IllegalArgumentException("Not a valid main challenge title");

    Predicate<LinkGeneratorRequest> sponsorName = req -> req.getSponsorName() != null;
    if (!sponsorName.test(request)) throw new IllegalArgumentException("Not a valid sponsor name");

    Predicate<LinkGeneratorRequest> validUsername = req -> req.getUsername() != null;
    if (!validUsername.test(request)) throw new IllegalArgumentException("Not a valid username");

    Predicate<LinkGeneratorRequest> positiveValidity = req -> req.getValidityDays() > 0;
    if (!positiveValidity.test(request)) throw new IllegalArgumentException("Incorrect validity");

    Predicate<LinkGeneratorRequest> nonNullChallenges = req -> req.getChallengeIds() != null && req.getChallengeIds().size() > 0;
    if (!nonNullChallenges.test(request)) throw new IllegalArgumentException("Challenge IDs null or empty");

    Predicate<LinkGeneratorRequest> codingDurationLabel = req -> req.getCodingDurationLabel() != null;
    if (!codingDurationLabel.test(request)) throw new IllegalArgumentException("Not a valid coding duration label");


    Date expirationDate = getExpirationDate(request.getValidityDays());
    String token = JWTTdlTokenUtils.generate(kmsEncrypt, request.getUsername(), request.getChallengeIds(), expirationDate);
    String journeyId = JourneyIdUtils.encode(request.getUsername(), request.getChallengeIds());
    context.getLogger().log("username: " + request.getUsername() + ", token: " + token + ", pageStorageBucket: " + pageStorageBucket + ", authVerifyEndpointURL: " + authVerifyEndpointURL);
    String pageContents = introPageTemplate.generateContent(
            request.getMainChallengeTitle(),
            request.getSponsorName(),
            request.getCodingDurationLabel(), request.getUsername(),
            token,
            authVerifyEndpointURL,
            expirationDate, journeyId
    );
    return pageUploader.uploadPage(pageContents);
}
 
Example 44
Project: nixmash-blog   File: FmServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public String getFileUploadingScript() {
    String result = null;
    try {
        result =  FreeMarkerTemplateUtils.processTemplateIntoString(fm.getTemplate("utils/fileuploading.ftl"), null);
    } catch (IOException | TemplateException e) {
        logger.error("Problem merging fileuploading template : " + e.getMessage());
    }
    return result;
}
 
Example 45
Project: nixmash-blog   File: FmServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public String getFileUploadedScript()  {
    String result = null;
    try {
        result =  FreeMarkerTemplateUtils.processTemplateIntoString(fm.getTemplate("utils/fileuploaded.ftl"), null);
    } catch (IOException | TemplateException e) {
        logger.error("Problem merging fileuploaded template : " + e.getMessage());
    }
    return result;
}
 
Example 46
Project: DMS   File: DmsTemplate.java   Source Code and License 5 votes vote down vote up
public String process() throws IOException, TemplateException {
    if (new File("WEB-INF/" + name).exists())
        try {
            Template template = getConfiguration().getTemplate(name);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
            template.process(input, writer);
            return out.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
    name = name.substring(0, name.lastIndexOf(".tls")) + ".html";
    return readFile("WEB-INF/" + name);
}
 
Example 47
Project: DMS   File: PostContextTemplate.java   Source Code and License 5 votes vote down vote up
public String processContent(int no, boolean isWriter, boolean isAdmin) throws IOException, TemplateException, SQLException {
    DmsTemplate template = new DmsTemplate(targetTemplate);
    for (String key : list.keySet()) {
        String[] columns = list.get(key);
        template.put(key, getString(no, columns));
    }
    template.put("isWriter", isWriter);
    template.put("isAdmin", isAdmin);
    return template.process();
}
 
Example 48
Project: DMS   File: LookupRecruitRouter.java   Source Code and License 5 votes vote down vote up
public void handle(RoutingContext context) {
    int code = 400;
    String content = null;
    if(AdminManager.isAdmin(context)){
        try {
            SafeResultSet rs = DataBase.getInstance().executeQuery("select student_data.number as 학번, student_data.name as 이름, recruit.language as 언어, recruit.project as 프로젝트, recruit.content as 다짐, recruit.area as 분야 from recruit LEFT JOIN student_data ON student_data.uid=recruit.uid");
            List<HashMap<String,Object>> list = rs.toHashMap();
            for(HashMap<String, Object> map : list){
                map.put("이름", AES256.decrypt((String)map.get("이름")));
                map.put("학번", AES256.decrypt((String)map.get("학번")));
            }
            List<String> columns = rs.getColumns();
            DmsTemplate template = new DmsTemplate("listpage");
            template.put("Title", "DMS 인턴 신청자");
            template.put("Heads", columns);
            template.put("Columns", columns);
            template.put("List", list);
            content = template.process();
            code = 200;
        } catch (SQLException | TemplateException | IOException e) {
            e.printStackTrace();
            code = 500;
        }
    }
    context.response().setStatusCode(code);
    if(content!=null)
        context.response().end(content);
    else context.response().end();
    context.response().close();
}
 
Example 49
Project: Equella   File: AjaxCaptureDirective.java   Source Code and License 5 votes vote down vote up
@Override
public void realRender(SectionWriter writer) throws IOException
{
	try
	{
		body.render(bodyOut);
	}
	catch( TemplateException e )
	{
		throw new SectionsRuntimeException(e);
	}
}
 
Example 50
Project: Equella   File: AbstractRenderDirective.java   Source Code and License 5 votes vote down vote up
@Override
public void realRender(SectionWriter writer) throws IOException
{
	try
	{

		body.render(writer);
	}
	catch( TemplateException e )
	{
		throw new SectionsRuntimeException(e);
	}
}
 
Example 51
Project: hippo   File: RestrictableDateFormatterDirective.java   Source Code and License 5 votes vote down vote up
private void assertRequiredParameterPresent(final Map parameters, final Environment environment)
    throws TemplateException {

    if (!parameters.containsKey(DATE_PARAM_NAME)) {
        throw new TemplateException(format("Required parameter ''{0}'' was not provided to template {1}.",
            DATE_PARAM_NAME, getClass().getName()), environment);
    }
}
 
Example 52
Project: Smart_City   File: ReportRoutes.java   Source Code and License 5 votes vote down vote up
protected void initReportRoute() throws IOException {
    get(new FreemarkerBasedRoute("/item/report", "report.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException {
            String itemId = request.queryParams("id");
            
            CityItem cityItem = CityItemDAO.getCityItem(itemId);
            
            SimpleHash data = new SimpleHash();
            data.put("id", itemId);
            data.put("type", cityItem.getTypeAsString());
            data.put("description", cityItem.getDescription());
            data.put("lat", cityItem.getLatitude());
            data.put("lng", cityItem.getLongitude());
            
            template.process(data, writer);
        }
    });
    
    post(new Route("/item/report") {
        @Override
        public Object handle(Request rqst, Response rspns) {
            Report.Builder b = new Report.Builder();
            b.cityItemId(rqst.queryParams("id"))
                    .comment(rqst.queryParams("comment"))
                    .priority(Integer.parseInt(rqst.queryParams("priority")))
                    .reportDate(new Date())
                    .resolved(false);
            
            ReportDAO.insertReport(b.build());
            
            JSONObject jsonResult = new JSONObject();
            jsonResult.put("success", true);
            return jsonResult.toString();
        }
    });
}
 
Example 53
Project: Smart_City   File: ReportRoutes.java   Source Code and License 5 votes vote down vote up
protected void initReportsRoute() throws IOException {
    get(new FreemarkerBasedRoute("reports", "reports.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException {
            Map<String, Object> input = new HashMap<>();
            
            List<ReportViewObject> reports = ReportDAO.findReportsForView();
            
            input.put("reports", reports);
            template.process(input, writer);
        }
    });
}
 
Example 54
Project: Smart_City   File: GenericRoutes.java   Source Code and License 5 votes vote down vote up
protected void initAboutRoute() throws IOException {
    get(new FreemarkerBasedRoute("/about", "about.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException {
            template.process(null, writer);
        }
    });
}
 
Example 55
Project: Smart_City   File: FreemarkerBasedRoute.java   Source Code and License 5 votes vote down vote up
@Override
public Object handle(Request request, Response response) {
    StringWriter writer = new StringWriter();

    try {
        doHandle(request, response, writer);
    } catch (IOException | TemplateException ex) {
        Logger.getLogger(FreemarkerBasedRoute.class.getName()).log(Level.SEVERE, null, ex);
        response.redirect("/internal_error");
    }
    
    return writer;
}
 
Example 56
Project: Smart_City   File: CityItemRoutes.java   Source Code and License 5 votes vote down vote up
protected void initIndexRoute() throws IOException {
    get(new FreemarkerBasedRoute("/", "index.ftl") {
        @Override
        public void doHandle(
                Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            SimpleHash data = new SimpleHash();
            data.put("Username", "dummy");

            template.process(data, writer);
        }
    });
}
 
Example 57
Project: tdl-auth   File: IntroPageTemplateTest.java   Source Code and License 5 votes vote down vote up
@Test
public void generate() throws IOException, TemplateException {
    String challengeTitle = "challengeTitle";
    String sponsorName = "sponsorName";
    String username = "myUsername";
    String codingSessionDurationLabel = "3hours";
    String token = "myToken";
    String journeyId = "myJourneyId";
    String url = "https://www.example.com/production/verify";
    IntroPageTemplate introPageTemplate = new IntroPageTemplate("test-intro.html.ftl");
    String content = introPageTemplate.generateContent(
            challengeTitle,
            sponsorName,
            codingSessionDurationLabel,
            username,
            token,
            url,
            new Date(),
            journeyId);
    assertThat(content, containsString(challengeTitle));
    assertThat(content, containsString(sponsorName));
    assertThat(content, containsString(username));
    assertThat(content, containsString(codingSessionDurationLabel));
    assertThat(content, containsString(token));
    assertThat(content, containsString(url));
    assertThat(content, containsString(journeyId));
}
 
Example 58
Project: belling-admin   File: FreeMarkerConfigExtend.java   Source Code and License 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws IOException, TemplateException {
	super.afterPropertiesSet();
	Configuration cfg = this.getConfiguration();
	cfg.setSharedVariable("shiro", new ShiroTags());// shiro标签
	cfg.setNumberFormat("#");// 防止页面输出数字,变成2,000
	// 可以添加很多自己的要传输到页面的[方法、对象、值]
}
 
Example 59
Project: unitimes   File: EventEmail.java   Source Code and License 5 votes vote down vote up
private String message() throws IOException, TemplateException {
	Configuration cfg = new Configuration(Configuration.VERSION_2_3_0);
	cfg.setClassForTemplateLoading(EventEmail.class, "");
	cfg.setLocale(Localization.getJavaLocale());
	cfg.setOutputEncoding("utf-8");
	Template template = cfg.getTemplate("confirmation.ftl");
	Map<String, Object> input = new HashMap<String, Object>();
	input.put("msg", MESSAGES);
	input.put("const", CONSTANTS);
	input.put("subject", subject());
	input.put("event", event());
	input.put("operation", request().getOperation() == null ? "NONE" : request().getOperation().name());
	if (response().hasCreatedMeetings())
		input.put("created", EventInterface.getMultiMeetings(response().getCreatedMeetings(), true, false));
	if (response().hasDeletedMeetings())
		input.put("deleted", EventInterface.getMultiMeetings(response().getDeletedMeetings(), true, false));
	if (response().hasCancelledMeetings())
		input.put("cancelled", EventInterface.getMultiMeetings(response().getCancelledMeetings(), true, false));
	if (response().hasUpdatedMeetings())
		input.put("updated", EventInterface.getMultiMeetings(response().getUpdatedMeetings(), true, false));
	if (request().hasMessage())
		input.put("message", request().getMessage());
	if (request().getEvent().getId() != null) {
		if (event().hasMeetings()) {
			input.put("meetings", EventInterface.getMultiMeetings(event().getMeetings(), true, false));
		} else
			input.put("meetings", new TreeSet<MultiMeetingInterface>());
	}
	input.put("version", MESSAGES.pageVersion(Constants.getVersion(), Constants.getReleaseDate()));
	input.put("ts", new Date());
	input.put("link", ApplicationProperty.UniTimeUrl.value());
	input.put("sessionId", iRequest.getSessionId());
	
	StringWriter s = new StringWriter();
	template.process(input, new PrintWriter(s));
	s.flush(); s.close();

	return s.toString();
}
 
Example 60
Project: tkcg   File: FreemarkerHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Process to file.
 *
 * @param model model
 * @param templateName templateName
 * @param targetFile targetFile
 * @param encoding encoding
 * @throws IOException io exception
 */
public void processToFile(Map model, String templateName, File targetFile, String encoding) throws IOException {
    Template template = configuration.getTemplate(templateName);
    Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), encoding));
    try {
        template.process(model, out);
    } catch (TemplateException e) {
        throw new GeneratorException("处理文件模板出错:" + e.getMessage());
    }
    out.close();
}