pl.chilldev.web.spring.context.SpringBeansJspPageMetaModelResolver.java Source code

Java tutorial

Introduction

Here is the source code for pl.chilldev.web.spring.context.SpringBeansJspPageMetaModelResolver.java

Source

/**
 * This file is part of the ChillDev-Web.
 *
 * @license http://mit-license.org/ The MIT license
 * @copyright 2014  by Rafa Wrzeszcz - Wrzasq.pl.
 */

package pl.chilldev.web.spring.context;

import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.PageContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.BeansException;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import pl.chilldev.web.core.page.PageMetaModel;

import pl.chilldev.web.tags.context.PageMetaModelContextException;
import pl.chilldev.web.tags.context.PageMetaModelResolver;

/**
 * Resolves page meta model from Spring DIC.
 *
 * @version 0.0.3
 * @since 0.0.1
 */
public class SpringBeansJspPageMetaModelResolver implements PageMetaModelResolver {
    /**
     * Logger.
     */
    protected Logger logger = LoggerFactory.getLogger(SpringBeansJspPageMetaModelResolver.class);

    /**
     * {@inheritDoc}
     * @since 0.0.1
     */
    @Override
    public PageMetaModel getPageMetaModel(JspContext context) throws PageMetaModelContextException {
        WebApplicationContext applicationContext;

        // try to get web context
        if (context instanceof PageContext) {
            applicationContext = WebApplicationContextUtils
                    .getWebApplicationContext(((PageContext) context).getServletContext());
        } else {
            this.logger.error("Could not acquire appplication context.");
            throw new PageMetaModelContextException(
                    "SpringBeansJspPageMetaModelResolver requires JSP to be run with PageContenxt implmentation.");
        }

        try {
            this.logger.debug("Taking PageMetaModel from Spring context.");
            return applicationContext.getBean(PageMetaModel.class);
        } catch (BeansException error) {
            this.logger.error("Error while fethcing page model from Spring context.", error);
            throw new PageMetaModelContextException("Error fetching page meta model from Spring context.", error);
        }
    }
}