ru.histone.spring.mvc.HistoneWebAppResourceLoader.java Source code

Java tutorial

Introduction

Here is the source code for ru.histone.spring.mvc.HistoneWebAppResourceLoader.java

Source

/**
 *    Copyright 2012 MegaFon
 *
 *    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 ru.histone.spring.mvc;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.WebApplicationContext;
import ru.histone.evaluator.nodes.Node;
import ru.histone.resourceloaders.ContentType;
import ru.histone.resourceloaders.DefaultResourceLoader;
import ru.histone.resourceloaders.Resource;
import ru.histone.resourceloaders.ResourceLoadException;
import ru.histone.resourceloaders.StreamResource;

import javax.servlet.ServletContext;
import java.io.InputStream;
import java.net.URI;

public class HistoneWebAppResourceLoader extends DefaultResourceLoader implements ApplicationContextAware {
    private ServletContext servletContext;

    @Deprecated
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    @Override
    public String resolveFullPath(String location, String baseLocation) throws ResourceLoadException {
        return super.resolveFullPath(location, baseLocation); //To change body of overridden methods use File | Settings | File Templates.
    }

    @Override
    public Resource load(String location, String baseLocation, Node... args) throws ResourceLoadException {
        URI fullLocation = makeFullLocation(location, baseLocation);

        Resource resource = null;

        if (fullLocation.getScheme().equals("webapp")) {
            resource = loadWebAppResource(fullLocation.getPath());
        } else {
            resource = super.load(location, baseLocation, args);
        }

        return resource;
    }

    private Resource loadWebAppResource(String location) {
        InputStream stream = servletContext.getResourceAsStream(location);
        return new StreamResource(stream, location, ContentType.TEXT);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.servletContext = ((WebApplicationContext) applicationContext).getServletContext();
    }
}