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

fr.wseduc.webutils.http.Renders Maven / Gradle / Ivy

/*
 * Copyright © WebServices pour l'Éducation, 2014
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package fr.wseduc.webutils.http;

import java.io.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import org.vertx.java.core.AsyncResult;
import org.vertx.java.core.Handler;
import org.vertx.java.core.Vertx;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;
import org.vertx.java.core.logging.impl.LoggerFactory;
import org.vertx.java.platform.Container;

import fr.wseduc.webutils.I18n;
import fr.wseduc.webutils.Server;

public class Renders {

	protected static final Logger log = LoggerFactory.getLogger(Renders.class);
	protected String pathPrefix;
	protected Container container;
	private final I18n i18n;
	protected Vertx vertx;
	private static final ConcurrentMap templates = new ConcurrentHashMap<>();

	public Renders(Vertx vertx, Container container) {
		this.container = container;
		if (container != null) {
			this.pathPrefix = Server.getPathPrefix(container.config());
		}
		this.i18n = I18n.getInstance();
		this.vertx = vertx;
	}

	protected void setLambdaTemplateRequest(final HttpServerRequest request,
			Map ctx) {
		ctx.put("i18n", new Mustache.Lambda() {

			@Override
			public void execute(Template.Fragment frag, Writer out) throws IOException {
				String key = frag.execute();
				String text = i18n.translate(key, getHost(request), I18n.acceptLanguage(request));
				out.write(text);
			}
		});

		ctx.put("static", new Mustache.Lambda() {

			@Override
			public void execute(Template.Fragment frag, Writer out) throws IOException {
				String path = frag.execute();
				out.write(staticResource(request, container.config().getBoolean("ssl", false),
						null, pathPrefix + "/public", path));
			}
		});

		ctx.put("infra", new Mustache.Lambda() {

			@Override
			public void execute(Template.Fragment frag, Writer out) throws IOException {
				String path = frag.execute();
				out.write(staticResource(request, container.config().getBoolean("ssl", false),
						"8001", "/infra/public", path));
			}
		});

		ctx.put("formatBirthDate", new Mustache.Lambda() {
			@Override
			public void execute(Template.Fragment frag, Writer out) throws IOException {
				String date = frag.execute();
				if(date != null && date.trim().length() > 0){
					String[] splitted = date.split("-");
					if(splitted.length == 3){
						out.write(splitted[2] + "/" + splitted[1] + "/" + splitted[0]);
						return;
					}
				}
				out.write(date);
			}
		});
	}

	private String staticResource(HttpServerRequest request,
			boolean https, String infraPort, String publicDir, String path) {
		String host = Renders.getHost(request);
		String protocol = https ? "https://" : "http://";
		if (infraPort != null && request.headers().get("X-Forwarded-For") == null) {
			host = host.split(":")[0] + ":" + infraPort;
		}
		return protocol
				+ host
				+ ((publicDir != null && publicDir.startsWith("/")) ? publicDir : "/" + publicDir)
				+ "/" + path;
	}

	public void renderView(HttpServerRequest request) {
		renderView(request, new JsonObject());
	}

	/*
	 * Render a Mustache template : see http://mustache.github.com/mustache.5.html
	 * TODO : modularize
	 * TODO : isolate scope management
	 */
	public void renderView(HttpServerRequest request, JsonObject params) {
		renderView(request, params, null, null, 200);
	}

	public void renderView(HttpServerRequest request, JsonObject params, String resourceName, Reader r) {
		renderView(request, params, resourceName, r, 200);
	}

	public void renderView(final HttpServerRequest request, JsonObject params,
			String resourceName, Reader r, final int status) {
		processTemplate(request, params, resourceName, r, new Handler() {
			@Override
			public void handle(Writer writer) {
				if (writer != null) {
				request.response().putHeader("content-type", "text/html; charset=utf-8");
				request.response().setStatusCode(status);
				request.response().end(writer.toString());
				} else {
					renderError(request);
				}
			}
		});
	}

	public void processTemplate(HttpServerRequest request, String template, JsonObject params,
			final Handler handler) {
		processTemplate(request, params, template, null, new Handler() {
			@Override
			public void handle(Writer w) {
				if (w != null) {
					handler.handle(w.toString());
				} else {
					handler.handle(null);
				}
			}
		});
	}

	public void processTemplate(final HttpServerRequest request,
			JsonObject p, String resourceName, Reader r, final Handler handler) {
		final JsonObject params = (p == null) ? new JsonObject() : p;
		getTemplate(request, resourceName, r, new Handler