Helper method to create a string template source for a given formatter and content.

@param formatter the formatter
@param contentSupplier the content supplier

@return the string template provider
437338
public static Function<String, String> createStringTemplateSource(
        I_CmsFormatterBean formatter,
        Supplier<CmsXmlContent> contentSupplier) {

        return key -> {
            String result = null;
            if (formatter != null) {
                result = formatter.getAttributes().get(key);
            }
            if (result == null) {
                CmsXmlContent content = contentSupplier.get();
                if (content != null) {
                    result = content.getHandler().getParameter(key);
                }
            }
            return result;
        };
    }
1246642
public static DoubleIteratorEx of(final Supplier<? extends DoubleIterator> iteratorSupplier) {
        N.checkArgNotNull(iteratorSupplier, "iteratorSupplier");

        return new DoubleIteratorEx() {
            private DoubleIterator iter = null;
            private DoubleIteratorEx iterEx = null;
            private boolean isInitialized = false;

            @Override
            public boolean hasNext() {
                if (isInitialized == false) {
                    init();
                }

                return iter.hasNext();
            }

            @Override
            public double nextDouble() {
                if (isInitialized == false) {
                    init();
                }

                return iter.nextDouble();
            }

            @Override
            public void skip(long n) {
                N.checkArgNotNegative(n, "n");

                if (isInitialized == false) {
                    init();
                }

                if (iterEx != null) {
                    iterEx.skip(n);
                } else {
                    super.skip(n);
                }
            }

            @Override
            public long count() {
                if (isInitialized == false) {
                    init();
                }

                if (iterEx != null) {
                    return iterEx.count();
                } else {
                    return super.count();
                }
            }

            @Override
            public void close() {
                if (isInitialized == false) {
                    init();
                }

                if (iterEx != null) {
                    iterEx.close();
                }
            }

            private void init() {
                if (isInitialized == false) {
                    isInitialized = true;
                    iter = iteratorSupplier.get();
                    iterEx = iter instanceof DoubleIteratorEx ? (DoubleIteratorEx) iter : null;
                }
            }
        };
    }
828244
public static StringTemplate stringTemplate(Template template, List<?> args) {
        return new StringTemplate(template, ImmutableList.copyOf(args));
    }
40129
@Pure
	protected String formatResource(XtextResource resource) {
		assert resource != null;
		try {
			final ITextRegionAccess regionAccess = this.regionAccessBuilder.get().forNodeModel(resource).create();
			final FormatterRequest formatterRequest = new FormatterRequest();
			formatterRequest.setAllowIdentityEdits(false);
			formatterRequest.setTextRegionAccess(regionAccess);
			final IPreferenceValues preferenceValues = FormatterFacade.this.configurationProvider
					.getPreferenceValues(resource);
			formatterRequest.setPreferences(TypedPreferenceValues.castOrWrap(preferenceValues));
			final List<ITextReplacement> replacements = this.formatter.format(formatterRequest);
			return regionAccess.getRewriter().renderToString(replacements);
		} catch (Exception exception) {
			throw Exceptions.sneakyThrow(exception);
		}
	}
1123975
protected CmsXmlContentProperty createTemplateContextsPropertyDefinition(
        I_CmsTemplateContextProvider contextProvider,
        Locale locale) {

        if (contextProvider == null) {
            return null;
        }
        List<String> contextOptions = new ArrayList<String>();
        for (CmsTemplateContext context : contextProvider.getAllContexts().values()) {
            contextOptions.add(context.getKey() + ":" + context.getLocalizedName(locale));
        }
        String widgetConfig = CmsStringUtil.listAsString(contextOptions, "|");

        String niceName = Messages.get().getBundle(locale).key(Messages.GUI_SETTING_TEMPLATE_CONTEXTS_NAME_0);
        String description = Messages.get().getBundle(locale).key(Messages.GUI_SETTING_TEMPLATE_CONTEXTS_DESCRIPTION_0);
        CmsXmlContentProperty propDef = new CmsXmlContentProperty(
            CmsTemplateContextInfo.SETTING,
            "string",
            "multicheck",
            widgetConfig,
            null,
            null,
            "",
            niceName,
            description,
            "",
            "false");
        return propDef;
    }
1186856
@Override
	public Template getTemplate(String resource) {
		if(ObjectUtil.equal(ResourceMode.STRING, this.resourceMode)) {
			return EnjoyTemplate.wrap(this.engine.getTemplateByString(resource));
		}
		return EnjoyTemplate.wrap(this.engine.getTemplate(resource));
	}
593088
public String generateJava2ContentParser(TypeName paramTypeName) {
		if (!managedParams.containsKey(paramTypeName)) {
			managedParams.put(paramTypeName, "" + (managedParams.size() + 1));
		}

		return PARAM_PARSER_PREFIX + managedParams.get(paramTypeName);
	}
1248285
public static StringTemplate stringTemplate(String template, List<?> args) {
        return stringTemplate(createTemplate(template), args);
    }
278067
public static void initServletContext( ServletContext servletContext, TemplatedURLFormatter formatter )
    {
        assert servletContext != null : "The ServletContext cannot be null.";

        if ( servletContext == null )
        {
            throw new IllegalArgumentException( "The ServletContext cannot be null." );
        }

        servletContext.setAttribute( TEMPLATED_URL_FORMATTER_ATTR, formatter );
    }
802947
private String generateContent(String templateFile) {
		try {
			GStringTemplateEngine gStringEngine = new GStringTemplateEngine();
			URL url = loadTemplate(templateFolder + "/" + templateFile);
			if (url == null) {
				logWarn("NO TEMPLATE FOUND FOR " + templateFile);
			} else {
				logDebug("Loaded template: " + url.getPath());
			}
			if (url == null) return null;
			
			Template template = gStringEngine.createTemplate(url);
			return template.make(modelMap).toString();
		} catch (Exception e) {
			ps.println("### ERROR: Failed generate templatefile: " + templateFile);
			e.printStackTrace(ps);
			return null;
		}
	}
986061
static String format(String template, Object... args) {
        template = String.valueOf(template); // null -> "null"

        if (N.isNullOrEmpty(args)) {
            return template;
        }

        // start substituting the arguments into the '%s' placeholders
        final StringBuilder sb = Objectory.createStringBuilder(template.length() + 16 * args.length);
        int templateStart = 0;
        int i = 0;

        String placeholder = "{}";
        int placeholderStart = template.indexOf(placeholder);

        if (placeholderStart < 0) {
            placeholder = "%s";
            placeholderStart = template.indexOf(placeholder);
        }

        while (placeholderStart >= 0 && i < args.length) {
            sb.append(template, templateStart, placeholderStart);
            sb.append(N.toString(args[i++]));
            templateStart = placeholderStart + 2;
            placeholderStart = template.indexOf(placeholder, templateStart);
        }

        sb.append(template, templateStart, template.length());

        // if we run out of placeholders, append the extra args in square braces
        if (i < args.length) {
            sb.append(" [");
            sb.append(N.toString(args[i++]));
            while (i < args.length) {
                sb.append(", ");
                sb.append(N.toString(args[i++]));
            }
            sb.append(']');
        }

        final String result = sb.toString();

        Objectory.recycle(sb);

        return result;
    }
938496
private String getContentByContainer(
        CmsContainerElementBean element,
        CmsContainer container,
        CmsFormatterConfiguration configs) {

        String content = null;

        I_CmsFormatterBean formatter = getFormatterForContainer(
            m_cms,
            element,
            container,
            m_adeConfig,
            CmsADESessionCache.getCache(m_req, m_cms));
        if (formatter != null) {
            element = element.clone(); // clone element because presets for different containers may be different
            element.initSettings(m_cms, formatter, m_locale, m_req, container.getSettingPresets());
            try {
                content = getElementContent(element, m_cms.readResource(formatter.getJspStructureId()), container);
                //                }
            } catch (Exception e) {
                LOG.error(e.getLocalizedMessage(), e);
            }
            if (content != null) {
                content = removeScriptTags(content);
            }
        }
        return content;
    }
552599
function staticSiteGenerator(options) {

  var buffer = {},
      layoutCache = {},
      templateCache = {},
      markedRenderer = new marked.Renderer();

  options = merge.recursive({
    basePath: '/',
    data: {},
    defaultLayout: false,
    jade: jade,
    jadeOptions: {
      basedir: path.join(process.cwd(), 'src')
    },
    layoutPath: 'layouts',
    marked: marked,
    markedOptions: {
      renderer: markedRenderer
    },
    passThrough: true,
    prettyUrls: true,
    regexpHtml: /\.html$/i,
    regexpMarkdown: /\.(md|markdown)$/i,
    regexpTemplate: /\.jade$/i,
    renderCode: renderCode,
    renderTemplate: renderTemplate,
    renderMarkdown: renderMarkdown,
    slugify: true,
    slugOptions: {
      mode: 'rfc3986',
      remove: /^\./g
    }
  }, options || {});

  options.markedOptions.renderer.code = options.renderCode;
  options.marked.setOptions(options.markedOptions);
  options.jade.filters.markdown = options.renderMarkdown;

  return through.obj(transformChunk);

  /**
   * transforms a stream chunk
   * @param  {object}   chunk    chunk object
   * @param  {string}   encoding file encoding
   * @param  {Function} done     callback
   * @return {undefined}
   */
  function transformChunk(chunk, encoding, done) {
    if (chunk.isNull()) return done();
    if (chunk.isStream()) return this.emit('error', new PluginError(logFlag, 'Streaming not supported'));
    if (
      !(chunk.isMarkdown = options.regexpMarkdown.test(chunk.relative)) &&
      !(chunk.isTemplate = options.regexpTemplate.test(chunk.relative)) &&
      !(chunk.isHtml = options.regexpHtml.test(chunk.relative))
    ) {
      return options.passThrough ? done(null, chunk) : done();
    }
    transformChunkData(chunk);
    if (chunk.data.draft && process.env.NODE_ENV !== 'development') return done();
    if (buffer.hasOwnProperty(chunk.relative)) {
      logDuplicate(chunk);
      return done();
    }
    transformChunkContents.call(this, chunk);
    buffer[chunk.relative] = chunk;
    done(null, chunk);
  }

  /**
   * merge site data, options data, frontmatter data into chunk data
   * @param  {object} chunk stream chunk object
   * @return {object}       chunk with transformed data
   */
  function transformChunkData(chunk) {
    var matter = grayMatter(String(chunk.contents)),
        relPath = chunk.hasOwnProperty('data') && chunk.data.relativePath ?
          chunk.data.relativePath : getRelativePath(chunk.relative),
        absPath = path.normalize(path.join(options.basePath, relPath));
    chunk.data = merge.recursive({},
      options.data,
      {
        basePath: options.basePath,
        relativePath: relPath,
        path: absPath,
        urlPath: options.prettyUrls ? path.dirname(absPath) + '/' : absPath,
        srcBasePath: chunk.base,
        srcRelativePath: chunk.relative,
        srcPath: chunk.path,
        contents: '',
        draft: false,
        layout: options.defaultLayout
      },
      chunk.data || {},
      matter.data
    );
    chunk.contents = new Buffer(matter.content);
    chunk.path = path.join(chunk.base, relPath);
    return chunk;
  }

  /**
   * render chunk contents with markdown renderer, wrap layout, render template
   * @param  {object} chunk stream chunk object
   * @return {object}       chunk with transformed contents
   */
  function transformChunkContents(chunk) {
    var contents = String(chunk.contents);
    try {
      if (chunk.isMarkdown) {
        contents = options.renderMarkdown(contents);
      }
      if (chunk.isTemplate) {
        contents = options.renderTemplate(contents, chunk.data, chunk.data.srcPath);
      }
      chunk.contents = new Buffer(contents);
      if (chunk.data.layout) applyLayout(chunk);
    } catch (err) {
      this.emit('error', new PluginError(logFlag, err.stack || err));
    }
    return chunk;
  }

  /**
   * render a template string with optional data
   * @param  {string} contents template
   * @param  {object} data     optional template data
   * @param  {object} filename optional template path for importing/mergeing
   * @return {string}          rendered template
   */
  function renderTemplate(contents, data, filename) {
    if (!templateCache.hasOwnProperty(contents)) {
      var jadeOptions = merge.recursive({}, options.jadeOptions, {filename: filename});
      templateCache[contents] = options.jade.compile(contents, jadeOptions);
    }
    var locals = merge.recursive({}, data, {locals: locals});
    return templateCache[contents](data);
  }

  /**
   * render a markdown string to html
   * @param  {string} contents markdown
   * @return {string}          html
   */
  function renderMarkdown(contents) {
    return options.marked(contents).trim();
  }

  /**
   * render string of code to highlighted code html structure
   * @param {string}  code source code string
   * @param {string}  lang source code language string
   * @return {string}      html
   */
  function renderCode(code, lang) {
    lang = typeof lang === 'string' && highlightjs.getLanguage(lang) ? lang : false;
    code = lang ? highlightjs.highlight(lang, code).value : highlightjs.highlightAuto(code).value;
    return '<pre><code class="hljs' + (lang ? ' ' + lang : '') + '">' + code + '</code></pre>';
  }

  /**
   * set chunk contents as template data property and render it with a layout
   * @param  {object} chunk stream chunk object
   * @return {object}       chunk with applied layout
   */
  function applyLayout(chunk) {
    chunk.data.contents = String(chunk.contents);
    var layout = getLayout(chunk.data.layout),
        contents = options.renderTemplate(layout.contents, chunk.data, layout.path);
    chunk.contents = new Buffer(contents);
    return chunk;
  }

  /**
   * transform a src file path into an relative url path
   * @param  {string} filePath file path
   * @return {string}          url
   */
  function getRelativePath(filePath) {
    var urlPath = path.join(
      path.dirname(filePath),
      path.basename(filePath, path.extname(filePath))
    );
    if (options.slugify) {
      urlPath = urlPath.split('/').map(function(part) {
        return slug(part, options.slugOptions);
      }).join('/');
    }
    urlPath += !options.prettyUrls || (/(^|\/)index$/i).test(urlPath) ?
      '.html' : '/index.html';
    return urlPath;
  }

  /**
   * read a layout file from given path; store it in cache object for further
   * usage; return object with layout contents and absolute path
   * @param  {string}   layout path to layout
   * @return {object}          layout contents and path
   */
  function getLayout(layout) {
    if (!layoutCache.hasOwnProperty(layout)) {
      var layoutContents = false,
          layoutPath = path.join(
        path.isAbsolute(options.layoutPath) ?
          options.layoutPath : path.join(process.cwd(), options.layoutPath),
        layout
      );
      try {
        layoutContents = fs.readFileSync(layoutPath, 'utf8');
      } catch (err) {
        throw new PluginError(logFlag, 'Could not read layout: \'' + layoutPath + '\'\n');
      }
      layoutCache[layout] = {
        contents: layoutContents,
        path: layoutPath
      };
    }
    return layoutCache[layout];
  }

  /**
   * log possible output overwrite to console
   * @param  {object} chunk stream chunk object
   * @return {undefined}
   */
  function logDuplicate(chunk) {
    log(logFlag,
      chalk.black.bgYellow('WARNING') + ' skipping ' +
      chalk.magenta(chunk.data.srcRelativePath) +
      ' as it would output to same path as ' +
      chalk.magenta(buffer[chunk.relative].data.srcRelativePath)
    );
  }

}
520024
public PeriodFormatterBuilder append(PeriodFormatter formatter) {
        if (formatter == null) {
            throw new IllegalArgumentException("No formatter supplied");
        }
        clearPrefix();
        append0(formatter.getPrinter(), formatter.getParser());
        return this;
    }
913789
public static LongIterator of(final Supplier<? extends LongIterator> iteratorSupplier) {
        N.checkArgNotNull(iteratorSupplier, "iteratorSupplier");

        return new LongIterator() {
            private LongIterator iter = null;
            private boolean isInitialized = false;

            @Override
            public boolean hasNext() {
                if (isInitialized == false) {
                    init();
                }

                return iter.hasNext();
            }

            @Override
            public long nextLong() {
                if (isInitialized == false) {
                    init();
                }

                return iter.nextLong();
            }

            private void init() {
                if (isInitialized == false) {
                    isInitialized = true;
                    iter = iteratorSupplier.get();
                }
            }
        };
    }
211319
function addTemplate (poet, data) {
  if (!data.ext || !data.fn)
    throw new Error('Template must have both an extension and formatter function');

  [].concat(data.ext).map(function (ext) {
    poet.templates[ext] = data.fn;
  });

  return poet;
}
524099
public static Object formatL(final String template, final Object... args) {
    return new Object() {
      @Override
      public String toString() {
        return format(template, args);
      }
    };
  }