Package com.github.mustachejava

Examples of com.github.mustachejava.Mustache


     * @param resourceUri    Template Id
     * @return Template
     */
    private Mustache createMustache(Reader resourceReader, String resourceUri) throws IOException {
        try {
            Mustache newMustache;
            if (startDelimiter != null && endDelimiter != null && mustacheFactory instanceof DefaultMustacheFactory) {
                DefaultMustacheFactory defaultMustacheFactory = (DefaultMustacheFactory) mustacheFactory;
                newMustache = defaultMustacheFactory.compile(resourceReader, resourceUri, startDelimiter, endDelimiter);
            } else {
                newMustache = mustacheFactory.compile(resourceReader, resourceUri);
View Full Code Here


  void copy(String resourceName, InputSupplier<InputStream> inputs, File file) throws IOException {
    InputSupplier<InputStreamReader> readers;
    readers = CharStreams.newReaderSupplier(inputs, Charsets.UTF_8);
    InputStreamReader reader = readers.getInput();

    Mustache mustache = set.compileMustache(reader, resourceName);
    BufferedWriter writer = Files.newWriter(file, Charsets.UTF_8);
    Object context = set.getContext();

    mustache.execute(writer, context).flush();
  }
View Full Code Here

  void copy(String resourceName, InputSupplier<InputStream> inputs, File file) throws IOException {
    InputSupplier<InputStreamReader> readers;
    readers = CharStreams.newReaderSupplier(inputs, Charsets.UTF_8);
    InputStreamReader reader = readers.getInput();

    Mustache mustache = set.compileMustache(reader, resourceName);
    BufferedWriter writer = Files.newWriter(file, Charsets.UTF_8);
    Object context = set.getContext();

    mustache.execute(writer, context).flush();
  }
View Full Code Here

        } catch (IOException e) {
          throw new MustacheException();
        }
      }
    };
    Mustache mustache = mb.compile(template + ".txt");

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    XPathFactory xpf = XPathFactory.newInstance();
    final DocumentBuilder db = dbf.newDocumentBuilder();
    final XPathExpression replyX = xpf.newXPath().compile("//a");
    final Properties cache = new Properties();
    File cacheFile = new File("cache");
    if (cacheFile.exists()) {
      cache.load(new FileInputStream(cacheFile));
    }

    Set<String> ungenerated = new HashSet<String>(
            Arrays.asList(
                    "MULTI", "EXEC", "DISCARD", // Transactions
                    "PSUBSCRIBE", "SUBSCRIBE", "UNSUBSCRIBE", "PUNSUBSCRIBE", // subscriptions
                    "AUTH" // authentication
            )
    );
    final Set<String> genericReply = new HashSet<String>(Arrays.asList(
            "SORT", // Can return an integer reply
            "ZRANK", "ZREVRANK", // Two different return values
            "SRANDMEMBER", // Can return a bulk or multibulk reply depending on count
            "BRPOPLPUSH" // If the timeout occurs it returns a Nil multi-bulk reply instead of a bulk reply
    ));
    final Set<String> multiples = new HashSet<String>(Arrays.asList(
            "ZADD"
    ));
    JsonFactory jf = new MappingJsonFactory();
    JsonParser jsonParser = jf.createJsonParser(new URL("https://raw.github.com/antirez/redis-doc/master/commands.json"));
    final JsonNode commandNodes = jsonParser.readValueAsTree();
    Iterator<String> fieldNames = commandNodes.getFieldNames();
    ImmutableListMultimap<String,String> group = Multimaps.index(fieldNames,
            new Function<String, String>() {
              @Override
              public String apply(String s) {
                return commandNodes.get(s).get("group").asText();
              }
            });
    List<Object> commands = new ArrayList<Object>();
    for (Map.Entry<String, String> entry : group.entries()) {
      String key = entry.getKey();
      final String groupName = key.substring(0, 1).toUpperCase() + key.substring(1);
      final String command = entry.getValue();
      if (ungenerated.contains(command)) continue;
      final boolean splitCommand = command.contains(" ");
      final String safeCommand = command.replace(" ", "_");
      String cacheReply = cache.getProperty(command.toLowerCase());
      if (cacheReply == null) {
        final Document detail = db.parse("http://query.yahooapis.com/v1/public/yql/javarants/redisreply?url=" + URLEncoder.encode("http://redis.io/commands/" + safeCommand.toLowerCase(), "utf-8"));
        cacheReply = replyX.evaluate(detail).replaceAll("[- ]", "").replaceAll("reply", "Reply").replaceAll("bulk", "Bulk").replaceAll("Statuscode", "Status");
        cache.setProperty(safeCommand.toLowerCase(), cacheReply);
        cache.store(new FileWriter(cacheFile), "# Updated " + new Date());
      }
      final String finalReply = cacheReply;
      final JsonNode commandNode = commandNodes.get(command);
      commands.add(new Object() {
        String group = groupName;
        boolean split_command = splitCommand;
        String name = safeCommand;
        String name1 = splitCommand ? name.substring(0, name.indexOf("_")) : name;
        String name2 = splitCommand ? name.substring(name.indexOf("_") + 1) : "";
        String comment = commandNode.get("summary").getTextValue();
        boolean generic = finalReply.equals("") || genericReply.contains(name);
        String reply = generic ? "Reply" : finalReply;
        String version = commandNode.get("since").getTextValue();
        boolean hasOptional = false;
        boolean hasMultiple = false;
        List<String> skipped = new ArrayList<String>();
        boolean varargs() {
          return (hasMultiple || hasOptional);
        }

        boolean usearray = false;
        List<Object> arguments = new ArrayList<Object>();

        int base_length() {
          return arguments.size() - (hasMultiple ? 1 : 0);
        }

        {
          JsonNode argumentArray = commandNode.get("arguments");
          if (argumentArray != null) {
            if (argumentArray.size() > 3) {
              usearray = true;
            }
            boolean first = true;
            int argNum = 0;
            if (multiples.contains(name)) {
              arguments.add(new Object() {
                boolean first = true;
                boolean multiple = true;
                String typename = "Object";
                String name = "args";
              });
            } else {
              for (final JsonNode argumentNode : argumentArray) {
                JsonNode nameNodes = argumentNode.get("name");
                final String argName;
                if (nameNodes.isArray()) {
                  boolean f = true;
                  StringBuilder sb = new StringBuilder();
                  for (JsonNode nameNode : nameNodes) {
                    if (!f) {
                      sb.append("_or_");
                    }
                    f = false;
                    String textValue = nameNode.getTextValue();
                    sb.append(textValue);
                  }
                  argName = sb.toString();
                } else {
                  argName = nameNodes.getTextValue();
                }
                final boolean finalFirst = first;
                final int finalArgNum = argNum;
                final boolean isMultiple = argumentNode.get("multiple") != null || argumentNode.get("command") != null;
                final boolean isOptional = argumentNode.get("optional") != null;
                if (isOptional) hasOptional = true;
                if (isMultiple) hasMultiple = true;
                final int finalArgNum1 = argNum;
                arguments.add(new Object() {
                  int arg_num = finalArgNum1;
                  boolean first = finalFirst;
                  boolean multiple = isMultiple;
                  String typename = "Object";
                  String name() {
                    String name = (argName + finalArgNum).replaceAll("[- :]", "_");
                    for (String s : skipped) {
                      name = s + "_" + name;
                    }
                    return name;
                  }
                  Boolean optional = isOptional;
                  boolean skip() {
                    boolean skip = hasMultiple && isOptional && !isMultiple;
                    if (skip) {
                      skipped.add(argName);
                    }
                    return skip;
                  }
                });
                if (isMultiple) {
                  usearray = true;
                }
                first = false;
                argNum++;
                if (isMultiple) break;
              }
            }
          }
        }

        String methodname = safeCommand.toLowerCase();
        String quote = keywords.contains(methodname) ? "`" : "";
      });
    }

    Map<String, Object> ctx = new HashMap<String, Object>();
    ctx.put("commands", commands);
    File base = new File(dest, pkg.replace(".", "/"));
    base.mkdirs();
    mustache.execute(new FileWriter(new File(base, className + "." + language)), ctx).close();
  }
View Full Code Here

  }

  private String render(Class<?> templateClass, Context context) {
    try {

      Mustache mustache = mustaches.compile(templateClass);

      StringWriter writer = new StringWriter();
      Map<?, ?> scope = toMustacheScope(context);

      Writer execute = mustache.execute(writer, scope);
      execute.flush();

      return writer.toString();

    } catch (IOException e) {
View Full Code Here

    }

    @Override
    public void execute(final Reader input, final Writer output, final String name, final Object parameters) {
        try {
            final Mustache template = MUSTACHE.compile(input, name);
            template.execute(output, parameters);
        }
        catch (MustacheException e) {
            final Throwable cause = Throwables.getRootCause(e);
            Throwables.propagateIfInstanceOf(cause, MissingParameterException.class);
            throw e;
View Full Code Here

    protected void onExchange(Exchange exchange) throws Exception {
        String newResourceUri = exchange.getIn().getHeader(MUSTACHE_RESOURCE_URI, String.class);
        if (newResourceUri == null) {
            // Get Mustache
            String newTemplate = exchange.getIn().getHeader(MUSTACHE_TEMPLATE, String.class);
            Mustache newMustache;
            if (newTemplate == null) {
                newMustache = getOrCreateMustache();
            } else {
                newMustache = createMustache(new StringReader(newTemplate), "mustache:temp#" + newTemplate.hashCode());
                exchange.getIn().removeHeader(MUSTACHE_TEMPLATE);
            }

            // Execute Mustache
            Map<String, Object> variableMap = ExchangeHelper.createVariableMap(exchange);
            StringWriter writer = new StringWriter();
            newMustache.execute(writer, variableMap);
            writer.flush();

            // Fill out message
            Message out = exchange.getOut();
            out.setBody(writer.toString());
View Full Code Here

        try {
            ClassLoader apcl = getCamelContext().getApplicationContextClassLoader();
            if (apcl != null) {
                Thread.currentThread().setContextClassLoader(apcl);
            }
            Mustache newMustache;
            if (startDelimiter != null && endDelimiter != null && mustacheFactory instanceof DefaultMustacheFactory) {
                DefaultMustacheFactory defaultMustacheFactory = (DefaultMustacheFactory) mustacheFactory;
                newMustache = defaultMustacheFactory.compile(resourceReader, resourceUri, startDelimiter, endDelimiter);
            } else {
                newMustache = mustacheFactory.compile(resourceReader, resourceUri);
View Full Code Here

    }

    @Override
    public void render(View view, Locale locale, OutputStream output) throws IOException, WebApplicationException {
        try {
            final Mustache template = factories.get(view.getClass())
                                               .compile(view.getTemplateName());
            final Charset charset = view.getCharset().or(Charsets.UTF_8);
            try (OutputStreamWriter writer = new OutputStreamWriter(output, charset)) {
                template.execute(writer, view);
            }
        } catch (ExecutionException | UncheckedExecutionException | MustacheException ignored) {
            throw new FileNotFoundException("Template " + view.getTemplateName() + " not found.");
        }
    }
View Full Code Here

    try {
      InputStream stream = getClass().getResourceAsStream(templateName);
      if (stream == null) {
        throw new MustacheException("Template not found: " + templateName);
      }
      Mustache mustache = mf.compile(new InputStreamReader(stream), templateName);
      mustache.execute(response.getWriter(), parameters);

      response.setStatus(status);
      response.setContentType(contentType);
    } catch (MustacheException e) {
      LOG.error("Template exception.", e);
View Full Code Here

TOP

Related Classes of com.github.mustachejava.Mustache

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.