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

nz.net.osnz.common.extjs.ExtTemplateService Maven / Gradle / Ivy

The newest version!
package nz.net.osnz.common.extjs;

import nz.net.osnz.common.jackson.JacksonHelperApi;
import org.codehaus.groovy.runtime.IOGroovyMethods;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import javax.servlet.ServletContext;
import java.io.IOException;
import java.util.*;

/**
 * @author Kefeng Deng
 */
@Component("extTemplateService")
public class ExtTemplateService {

    private static final Logger log = LoggerFactory.getLogger(ExtTemplateService.class);

    private static final String EXT_RESOURCES_PATH = "/ext/";

    private static final String EXT_VIEW_EXTENSION = ".html";

    private static final String DIRECTORY_PATH = "/";

    private Map templates;

    @Inject
    private JacksonHelperApi jacksonHelperApi;

    @Inject
    private ServletContext context;

    @Value("${scanner.devmode}")
    private boolean inDevMode = false;

    protected void collectResources(Set paths, List collected) {
        for (String path : paths) {
            if (path.endsWith(EXT_VIEW_EXTENSION)) {
                collected.add(path);
            } else if (path.endsWith(DIRECTORY_PATH)) {
                collectResources(context.getResourcePaths(path), collected);
            }
        }
    }

    protected List collectResources() {

        List collected = new ArrayList();

        collectResources(context.getResourcePaths(EXT_RESOURCES_PATH), collected);

        return collected;
    }

    protected Map collectAngularTemplates(List resources) {

        Map templateMapping = new HashMap();

        for ( String url : resources ) {
            String mapping = url.substring(url.indexOf(EXT_RESOURCES_PATH) + "/ext".length());
            try {
                templateMapping.put(mapping, IOGroovyMethods.getText(context.getResourceAsStream(url)));
            } catch ( IOException ioe ) {
                log.error("Cannot read " + url);
            }

            log.debug( String.format("ext-template: %s\n%s ", url, templateMapping.get(url)) );
        }

        templates = templateMapping;

        return templateMapping;
    }

    public Map getExtTemplates() {
        if (inDevMode || templates == null) {
            return collectAngularTemplates(collectResources());
        } else {
            return templates;
        }
    }

    public String getExtTemplatesAsJson() {
        return jacksonHelperApi.jsonSerialize(getExtTemplates());
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy