jetspeedtemplatelocatorservice.java

来自「jetspeed源代码」· Java 代码 · 共 902 行 · 第 1/2 页

JAVA
902
字号
     *          or null if not found.
     */
    public String locateParameterTemplate(RunData data, String template)
    {
        List templatePaths = localizeTemplateName(data);
        Iterator i = templatePaths.iterator();

        while (i.hasNext())
        {
            String path = (String) i.next();
            String located = locateTemplate(data, DIR_PARAMETERS, path, template);

            if (null != located)
            {
                return DIR_PARAMETERS + located;
            }
        }

        return null;
    }

    /**
     * General template location algorithm. Starts with the most specific resource,
     * including mediatype + nls specification, and fallsback to least specific.
     *
     * @param data The rundata for the request.
     * @param resourceType The path specific to the resource type sought (eg /screens).
     * @param path The fullest path to the template based on simple NLS/mediatype directory.
     * @param template The name of the template.
     *
     * @return the exact path to the template, or null if not found.
     */
    private String locateTemplate(RunData data, String resourceType, String path, String template)
    {
        String located = null;

        // Iterate through each of the template roots
        for (int i = 0; i < templateRoots.length; i++)
        {
            located = locateTemplate(data, resourceType, path, template, templateRoots[i]);
            if (located != null)
            {
                break;
            }
        }

        return located;
    }

    /**
     * General template location algorithm. Starts with the most specific resource,
     * including mediatype + nls specification, and fallsback to least specific.
     *
     * @param data The rundata for the request.
     * @param resourceType The path specific to the resource type sought (eg /screens).
     * @param path The fullest path to the template based on simple NLS/mediatype directory.
     * @param template The name of the template.
     * @param templateRoot The template root to be searched.
     *
     * @return the exact path to the template, or null if not found.
     */
    private String locateTemplate(
        RunData data,
        String resourceType,
        String path,
        String template,
        String templateRoot)
    {
        String finalPath;

        // make sure resourceType doesn't end with "/" but starts with "/"
        if (resourceType.endsWith(PATH_SEPARATOR))
        {
            resourceType = resourceType.substring(0, resourceType.length() - 1);
        }
        if (!resourceType.startsWith(PATH_SEPARATOR))
        {
            resourceType = PATH_SEPARATOR + resourceType;
        }
        // make sure path doesn't end with "/" but starts with "/"
        if (path.endsWith(PATH_SEPARATOR))
        {
            path = path.substring(0, path.length() - 1);
        }
        if (!path.startsWith(PATH_SEPARATOR))
        {
            path = PATH_SEPARATOR + path;
        }
        // make sure template starts with "/"
        if (!template.startsWith(PATH_SEPARATOR))
        {
            template = PATH_SEPARATOR + template;
        }

        StringBuffer fullPath = new StringBuffer(templateRoot);

        if (!templateRoot.endsWith(PATH_SEPARATOR))
        {
            fullPath.append(PATH_SEPARATOR);
        }

        fullPath.append(getTemplateExtension(template));
        fullPath.append(resourceType);

        String basePath = fullPath.toString();
        String realPath = null;
        String workingPath = null;

        do
        {
            workingPath = path + template;
            realPath = TurbineServlet.getRealPath(basePath + workingPath);

            // the current template exists in cache, return the corresponding path
            if (templateExists(realPath, true))
            {
                if (logger.isDebugEnabled())
                {
                    logger.debug(
                        "TemplateLocator: template exists in cache: "
                            + realPath
                            + " returning "
                            + workingPath);
                }

                return workingPath;
            }
            else if (this.hotDeploy == true)
            {
                // Try to locate it directly on file system, perhaps it was recently added
                if (templateExists(realPath, false))
                {
                    if (logger.isDebugEnabled())
                    {
                        logger.debug(
                            "TemplateLocator: template exists on the file system: "
                                + realPath
                                + " returning "
                                + workingPath);
                    }

                    // add it to the map
                    //templateMap.put(workingPath, null);
                    templateMap.put(realPath, null);

                    return workingPath;
                }
            }
            // else strip path of one of its components and loop
            int pt = path.lastIndexOf(PATH_SEPARATOR);
            if (pt > -1)
            {
                path = path.substring(0, pt);
            }
            else
            {
                path = null;
            }
        }
        while (path != null);

        return null;
    }

    /**
     * Helper function for template locator to find a localized (NLS) resource.
     * Considers both language and country resources as well as all the possible
     * media-types for the request
     *
     * @param data The rundata for the request.
     *
     * @return The possible paths to a localized template ordered by
     * descending preference
     */
    private List localizeTemplateName(RunData data)
    {
        return localizeTemplateName(data, null);
    }

    /**
     * Helper function for template locator to find a localized (NLS) resource.
     * Considers both language and country resources as well as all the possible
     * media-types for the request
     *
     * @param data The rundata for the request.
     * @param locale The locale for the request.
     *
     * @return The possible paths to a localized template ordered by
     * descending preference
     */
    private List localizeTemplateName(RunData data, Locale inLocale)
    {
        List templates = new ArrayList();
        Locale tmplocale = null;

        if (inLocale != null)
        {
            tmplocale = inLocale;
        }
        else
        {
            CustomLocalizationService locService = (CustomLocalizationService) ServiceUtil.getServiceByName(
                LocalizationService.SERVICE_NAME);
            tmplocale = locService.getLocale(data);
        }

        // Get the locale store it in the user object
        if (tmplocale == null)
        {
            tmplocale =
                new Locale(
                    TurbineResources.getString("locale.default.language", "en"),
                    TurbineResources.getString("locale.default.country", "US"));
        }

        data.getUser().setTemp("locale", tmplocale);

        StringBuffer templatePath = new StringBuffer();

        // retrieve all the possible media types
        String type = data.getParameters().getString(Profiler.PARAM_MEDIA_TYPE, null);
        List types = new ArrayList();
        CapabilityMap cm = ((JetspeedRunData) data).getCapability();

        // Grab the Locale from the temporary storage in the User object
        Locale locale = (Locale) data.getUser().getTemp("locale");
        String language = locale.getLanguage();
        String country = locale.getCountry();

        if (null != type)
        {
            types.add(type);
        }
        else
        {
            Iterator i = cm.listMediaTypes();
            while (i.hasNext())
            {
                types.add(i.next());
            }
        }

        Iterator typeIterator = types.iterator();

        while (typeIterator.hasNext())
        {
            type = (String) typeIterator.next();

            if ((type != null) && (type.length() > 0))
            {
                templatePath.append(PATH_SEPARATOR).append(type);
            }

            if ((language != null) && (language.length() > 0))
            {
                templatePath.append(PATH_SEPARATOR).append(language);
            }

            if ((country != null) && (country.length() > 0))
            {
                templatePath.append(PATH_SEPARATOR).append(country);
            }

            templates.add(templatePath.toString());
            templatePath.setLength(0);
        }

        return templates;
    }

    /**
     * Returns the extension for the specified template
     *
     * @param template the template name to scan for an extension
     * @return the template extension if it exists or the default
     * template extension
     */
    private String getTemplateExtension(String template)
    {
        String ext = TurbineTemplate.getDefaultExtension();

        int idx = template.lastIndexOf(".");

        if (idx > 0)
        {
            ext = template.substring(idx + 1);
        }

        return ext;
    }

    /**
     * Checks for the existence of a template resource given a key.
     * The key are absolute paths to the templates, and are cached
     * in a template cache for performance.
     *
     * @param key The absolute path to the template resource.
     *
     * @return True when the template is found, otherwise false.
     */
    public boolean templateExists(String templateKey, boolean useNameCache)
    {
        if (null == templateKey)
        {
            return false;
        }

        if (useNameCache == true)
        {
            return templateMap.containsKey(templateKey);
        }

        return (new File(templateKey).exists());
    }

    /**
     * Loads the configuration parameters for this service from the
     * JetspeedResources.properties file.
     *
     * @exception throws a <code>InitializationException</code> if the service
     * fails to initialize
     */
    private void initConfiguration() throws InitializationException
    {

        templateRoots =
            JetspeedResources.getStringArray(
                TurbineServices.SERVICE_PREFIX
                    + TemplateLocatorService.SERVICE_NAME
                    + CONFIG_TEMPLATE_ROOT);

        if ((templateRoots == null) || (templateRoots.length == 0))
        {
            throw new InitializationException(MSG_MISSING_PARAMETER + CONFIG_TEMPLATE_ROOT);
        }

        templateMap = new HashMap();

        for (int i = 0; i < templateRoots.length; i++)
        {
            String templateRoot = templateRoots[i];

            if (!templateRoot.endsWith(PATH_SEPARATOR))
            {
                templateRoot = templateRoot + PATH_SEPARATOR;
            }

            if (logger.isDebugEnabled())
            {
                logger.debug("TemplateLocator: Adding templateRoot:" + templateRoot);
            }

            // traverse starting from the root template directory and add resources
            String templateRootPath = TurbineServlet.getRealPath(templateRoot);
            if (null != templateRootPath)
            {
                loadNameCache(templateRootPath, "");
            }
        }

        
        velocityService =
            (VelocityService) TurbineServices.getInstance().getService(
                VelocityService.SERVICE_NAME);

        jspService = (JspService) TurbineServices.getInstance().getService(JspService.SERVICE_NAME);

        useGlobalPortletSearch = JetspeedResources.getBoolean(
                TurbineServices.SERVICE_PREFIX
                    + TemplateLocatorService.SERVICE_NAME
                    + CONFIG_PORTLET_GLOBAL_SEARCH, false);

        hotDeploy = JetspeedResources.getBoolean(
                TurbineServices.SERVICE_PREFIX
                    + TemplateLocatorService.SERVICE_NAME
                    + CONFIG_HOT_DEPLOY, true);

    }

    /**
     * Loads the template name cache map to accelerate template searches.
     *
     * @param path The template
     * @param name just the name of the resource
     */
    private void loadNameCache(String path, String name)
    {
        File file = new File(path);
        if (file.isFile())
        {
            // add it to the map
            templateMap.put(path, null);
        }
        else
        {
            if (file.isDirectory())
            {
                if (!path.endsWith(File.separator))
                {
                    path += File.separator;
                }

                String list[] = file.list();

                // Process all files recursivly
                for (int ix = 0; list != null && ix < list.length; ix++)
                {
                    loadNameCache(path + list[ix], list[ix]);
                }
            }
        }
    }

    /**
     * Correctly locate the default layout based on the 
     * default.layout.template property of the appropriate
     * template service.
     * @author <a href="mailto:sweaver@rippe.com">Scott Weaver</a>
     */
    private String getTemplateLayout(String extension)
    {
        String dftLayout = "/default." + extension;

        Configuration velocityCfg = null;
        Configuration jspCfg = null;
        if (velocityService != null)
        {
            velocityCfg = velocityService.getConfiguration();
        }

        if (jspService != null)
        {
            jspCfg = jspService.getConfiguration();
        }

        if (velocityCfg != null
            && velocityCfg.getString(TEMPLATE_EXTENSION).indexOf(extension) > -1)
        {
            return velocityCfg.getString(DEFAULT_LAYOUT, dftLayout);
        }
        else if (jspCfg != null && jspCfg.getString(TEMPLATE_EXTENSION).indexOf(extension) > -1)
        {
            return jspCfg.getString(DEFAULT_LAYOUT, dftLayout);
        }
        else
        {
            return dftLayout;
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?