All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.minijax.mustache.MinijaxMustacheWriter Maven / Gradle / Ivy

There is a newer version: 0.5.10
Show newest version
package org.minijax.mustache;

import static javax.ws.rs.core.MediaType.*;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;

import org.minijax.view.View;

import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;

@Singleton
@Produces(TEXT_HTML)
public class MinijaxMustacheWriter implements MessageBodyWriter {

    @Inject
    private MustacheFactory mf;

    @Override
    public boolean isWriteable(final Class type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
        return type != null && View.class.isAssignableFrom(type);
    }

    @Override
    public void writeTo(
            final View page,
            final Class type,
            final Type genericType,
            final Annotation[] annotations,
            final MediaType mediaType,
            final MultivaluedMap httpHeaders,
            final OutputStream entityStream)
                    throws IOException {

        final Mustache mustache = mf.compile("templates/" + page.getTemplateName() + ".mustache");

        try (final OutputStreamWriter writer = new OutputStreamWriter(entityStream)) {
            mustache.execute(writer, page.getModel()).flush();
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy