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

com.harium.web.Web Maven / Gradle / Ivy

There is a newer version: 1.0.2
Show newest version
package com.harium.web;

import com.harium.web.model.WebModule;
import spark.Filter;
import spark.Request;
import spark.Response;
import spark.Spark;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Web {

    private static String host = "";
    public static final String PARAM_PATH = "path";

    static List webModules = new ArrayList<>();
    static List> registers = new ArrayList<>();

    public static void register(Class controller) {
        registers.add(controller);
    }

    public static void init() {
        Web.acceptEndSlash();
        for (Class controller : registers) {
            try {
                Constructor constructor = controller.getConstructor();
                WebModule webModule = (WebModule) constructor.newInstance();
                webModule.init();
                webModules.add(webModule);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        registers.clear();
    }

    /**
     * Method to treat paths with end slash
     */
    public static void acceptEndSlash() {
        Spark.before(new Filter() {
            @Override
            public void handle(Request request, Response response) throws Exception {
                String path = request.pathInfo();
                if (!"/".equals(path) && path.endsWith("/")) {
                    response.redirect(path.substring(0, path.length() - 1));
                }
            }
        });
    }

    public static Map buildModel(Request request) {
        Map model = new HashMap<>();
        model.put(PARAM_PATH, host);

        for (WebModule controller : webModules) {
            controller.buildModel(request, model);
        }

        return model;
    }

    public static void host(String host) {
        Web.host = host;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy