@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); }
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; }
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; } }
@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(); }
@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(); }
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); }
@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; }
@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; }
@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; }
@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; }
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(); }
@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"); } }
@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); } } }
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(); }
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(); }
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); }
/** * 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(); }
@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"); }
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"); }
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); }
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); } }
@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); } }
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 }
@Test public void createClient() throws IOException, TemplateException { AmazonS3ClientBuilder .standard() .build(); Object client = AmazonS3ClientBuilder .standard() .build(); assertThat(client, instanceOf(AmazonS3.class)); }
/** * 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); }
/** *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); }
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); }
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(); }
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); } }
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); } }
@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"); }
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); } }
/** * 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); } }
@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()); }
@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)); }
@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; }