001/*
002 * Stallion Core: A Modern Web Framework
003 *
004 * Copyright (C) 2015 - 2016 Stallion Software LLC.
005 *
006 * This program is free software: you can redistribute it and/or modify it under the terms of the
007 * GNU General Public License as published by the Free Software Foundation, either version 2 of
008 * the License, or (at your option) any later version. This program is distributed in the hope that
009 * it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
010 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
011 * License for more details. You should have received a copy of the GNU General Public License
012 * along with this program.  If not, see <http://www.gnu.org/licenses/gpl-2.0.html>.
013 *
014 *
015 *
016 */
017
018package io.stallion.dataAccess;
019
020import io.stallion.restfulEndpoints.SlugRegistry;
021import io.stallion.services.Log;
022import io.stallion.templating.TemplateRenderer;
023
024import java.util.Map;
025
026import static io.stallion.utils.Literals.*;
027import static io.stallion.Context.*;
028
029
030public class DisplayableModelController<T extends Displayable> extends StandardModelController<T> {
031    private String defaultTemplate = "";
032
033    @Override
034    protected void preInitialize(DataAccessRegistration registration) {
035        setDefaultTemplate(registration.getTemplatePath());
036    }
037
038    public String getDefaultTemplate() {
039        return defaultTemplate;
040    }
041    public DisplayableModelController<T> setDefaultTemplate(String template) {
042        this.defaultTemplate = template;
043        return this;
044    }
045
046    public String getTemplate(T model) {
047        if (!empty(model.getTemplate())) {
048            return model.getTemplate();
049        }
050        return getDefaultTemplate();
051    }
052
053    public String render(T item, Map<String, Object> context) {
054        String template = or(getTemplate(item), settings().getPageTemplate());
055        return TemplateRenderer.instance().renderTemplate(template, context);
056    }
057
058    @Override
059    public void onPostLoadItem(T obj) {
060        StandardDisplayableModel item = (StandardDisplayableModel)obj;
061
062        Log.fine("Add to slug registry slug={0} id={1} bucket=bucket:{2}", item.getSlug(), item.getId(), getBucket());
063        SlugRegistry.instance().addDisplayable(item);
064        if (!empty(item.getOldUrls())) {
065            for (String url: item.getOldUrls()) {
066                SlugRegistry.instance().registerRedirect(url, item.getSlug());
067            }
068        }
069    }
070
071
072
073}