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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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;
}