com.balero.controllers.PageController.java Source code

Java tutorial

Introduction

Here is the source code for com.balero.controllers.PageController.java

Source

/**
 * <pre>
 * Balero CMS Enterprise Edition is free and open source software under MIT License.
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013-2014 <Balero CMS All Rights Reserved>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * <a href="http://www.balerocms.com">BaleroCMS.com</a>
 * </pre>
 *
 * @author      Anibal Gomez
 * @version     1.0
 * @since       1.0
 */

package com.balero.controllers;

import com.balero.models.Footer;
import com.balero.models.StaticPages;
import com.balero.utils.FileManager;
import com.balero.utils.UsersAuth;
import com.balero.utils.ListFilesUtil;
import com.balero.utils.UAgentInfo;
import com.github.slugify.InitSlugifyTag;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

@Controller
public class PageController {

    @Autowired
    private com.balero.models.StaticPagesDAO StaticPagesDAO;

    @Autowired
    private com.balero.models.FooterDAO FooterDAO;

    @Autowired
    private com.balero.models.UsersDAO UsersDAO;

    @Autowired
    private com.balero.models.SettingsDAO SettingsDAO;

    private static final Logger logger = Logger.getLogger(PageController.class);

    @RequestMapping(value = "/page/{pageslug}", method = RequestMethod.GET)
    public String showPage(@PathVariable String pageslug,
            @CookieValue(value = "baleroAdmin", defaultValue = "init") String baleroAdmin, Model model,
            HttpServletRequest request, Locale locale) {

        String background = "eternity.png";
        model.addAttribute("background", background);

        // Credentials
        UsersAuth auth = new UsersAuth();
        auth.setCredentials(baleroAdmin, UsersDAO);
        if (auth.auth(baleroAdmin, auth.getLocalUsername(), auth.getLocalPassword())) {
            // Admin Elements
            model.addAttribute("auth", true);
        } else {
            model.addAttribute("auth", false);
        }

        ListFilesUtil listFilesUtil = new ListFilesUtil();
        String files = listFilesUtil.listFiles();

        // Footer content
        List<Footer> footer = FooterDAO.findAll();

        // Pages
        List<StaticPages> page = StaticPagesDAO.findPageBySlug(pageslug);
        List<StaticPages> pages = StaticPagesDAO.findAll(locale);

        // Vars
        String pathCover = "../webapps/media/default.jpg";
        File defaultCover = new File(pathCover);

        if (defaultCover.exists()) {
            model.addAttribute("defaultCover", "media/default.jpg");
        } else {
            model.addAttribute("defaultCover", "resources/images/eternity.png");
        }

        // Mobile
        model.addAttribute("mobile", false);
        String useragent = request.getHeader("user-agent");
        String accept = "Accept: */*";
        UAgentInfo agent = new UAgentInfo(useragent, accept);
        if (agent.detectMobileQuick() == true) {
            model.addAttribute("mobile", true);
        }

        // media files w.*
        FileManager w = new FileManager();
        String custom = w.read("../webapps/media/custom.css");
        model.addAttribute("custom", custom);

        model.addAttribute("pageslug", pageslug);

        model.addAttribute("username", auth.getLocalUsername());
        model.addAttribute("hierarchy", auth.getHierarchy());
        model.addAttribute("pagename", StaticPagesDAO.pageName(pageslug));
        model.addAttribute("settingsId", SettingsDAO.settingsId());
        model.addAttribute("sitename", SettingsDAO.siteName());
        model.addAttribute("slogan", SettingsDAO.siteSlogan());
        model.addAttribute("url", SettingsDAO.siteURL());
        model.addAttribute("navbar", SettingsDAO.siteNavBar());
        model.addAttribute("files", files);
        model.addAttribute("page", page);
        model.addAttribute("pages", pages);
        model.addAttribute("footer", footer);

        return "page";

    }

    @RequestMapping(value = "/page/edit/{id}", method = RequestMethod.POST)
    public String editPage(@PathVariable int id, @RequestParam String pagename, @RequestParam String pageslug,
            @RequestParam String pagebody, @RequestParam String pagelocale,
            @CookieValue(value = "baleroAdmin") String baleroAdmin, RedirectAttributes redirectAttributes,
            Locale locale, HttpServletRequest request) {

        // Security
        UsersAuth security = new UsersAuth();
        security.setCredentials(baleroAdmin, UsersDAO);
        if (security.auth(baleroAdmin, security.getLocalUsername(), security.getLocalPassword()) == false)
            return "hacking";

        if (pagename.isEmpty()) {
            pagename = "(No Title)";
        }

        // Slugify
        String newSlug = InitSlugifyTag.getSlugify().slugify(pageslug);

        ResourceBundle messages = ResourceBundle.getBundle("messages", locale);

        String view = null;
        try {
            if (pageslug.isEmpty()) {
                throw new Exception("Slug is empty!");
            }
            StaticPagesDAO.updatePage(id, pagename, pagebody, newSlug, pagelocale);
            view = "redirect:/page/" + newSlug;
        } catch (Exception e) {
            logger.debug(e.getMessage());
            redirectAttributes.addFlashAttribute("message", messages.getString("label.page.slugerror"));
            String referer = request.getHeader("Referer");
            view = "redirect:" + referer;
        }

        return view;

    }

    /**
     * Page delete controller
     *
     * @param id Page ID
     * @param baleroAdmin Magic cookie
     * @return Home view
     */
    @RequestMapping(value = "/page/delete", method = RequestMethod.GET)
    public String deletePage(@RequestParam String id, @CookieValue(value = "baleroAdmin") String baleroAdmin,
            HttpServletRequest request) {

        /**
         * Security
         */
        UsersAuth security = new UsersAuth();
        security.setCredentials(baleroAdmin, UsersDAO);
        if (security.auth(baleroAdmin, security.getLocalUsername(), security.getLocalPassword()) == false)
            return "hacking";

        int intId = Integer.parseInt(id);
        StaticPagesDAO.deletePage(intId);

        String referer = request.getHeader("Referer");
        return "redirect:" + referer;

    }

    /**
     * New page controller
     *
     * @param name Page name
     * @param model Framework model
     * @param redirectAttributes Message center
     * @param locale Framework locale
     * @param baleroAdmin Magic cookie
     * @return Home controller
     */
    @RequestMapping(value = "/page/new", method = RequestMethod.POST)
    public String newPage(@RequestParam("name") String name, Model model, RedirectAttributes redirectAttributes,
            Locale locale, @CookieValue(value = "baleroAdmin") String baleroAdmin, HttpServletRequest request) {

        /**
         * Security
         */
        UsersAuth security = new UsersAuth();
        security.setCredentials(baleroAdmin, UsersDAO);
        if (security.auth(baleroAdmin, security.getLocalUsername(), security.getLocalPassword()) == false)
            return "hacking";

        if (name.equals("")) {
            name = "(No Title)";
        }

        String html;

        html = "<p>\n"
                + "Lorem ipsum es el texto que se usa habitualmente en diseo grfico en demostraciones de tipografas o de borradores de diseo para probar el diseo visual antes de insertar el texto final.\n"
                + "\n"
                + "Aunque no posee actualmente fuentes para justificar sus hiptesis, el profesor de filologa clsica Richard McClintock asegura que su uso se remonta a los impresores de comienzos del siglo XVI.1 Su uso en algunos editores de texto muy conocidos en la actualidad ha dado al texto lorem ipsum nueva popularidad.\n"
                + "\n"
                + "El texto en s no tiene sentido, aunque no es completamente aleatorio, sino que deriva de un texto de Cicern en lengua latina, a cuyas palabras se les han eliminado slabas o letras.\n"
                + "</p>";

        logger.debug("UTF-8->name: " + name);

        /**
         * Referer:
         * lingobit.com/solutions/java/java_localization.html
         */
        ResourceBundle messages = ResourceBundle.getBundle("messages", locale);

        String slug = InitSlugifyTag.getSlugify().slugify(name);
        try {
            StaticPagesDAO.addPage(name, html, slug, locale);
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("message", messages.getString("label.page.slugerror"));
        }

        String referer = request.getHeader("Referer");
        return "redirect:" + referer;

    }

}