⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 i18nfactoryset.java

📁 structs源码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
     * @return the key or <code>null</code> if not found.
     */
    protected Object getDefinitionsFactoryKey(
        String name,
        ServletRequest request,
        ServletContext servletContext) {

        Locale locale = null;
        try {
            HttpSession session = ((HttpServletRequest) request).getSession(false);
            if (session != null) {
                locale = (Locale) session.getAttribute(ComponentConstants.LOCALE_KEY);
            }

        } catch (ClassCastException ex) {
            log.error("I18nFactorySet.getDefinitionsFactoryKey");
            ex.printStackTrace();
        }

        return locale;
    }

    /**
     * Create a factory for specified key.
    * If creation failes, return default factory and log an error message.
    * @param key The key.
    * @param request Servlet request.
    * @param servletContext Servlet context.
    * @return Definition factory for specified key.
    * @throws DefinitionsFactoryException If an error occur while creating factory.
     */
    protected DefinitionsFactory createFactory(
        Object key,
        ServletRequest request,
        ServletContext servletContext)
        throws DefinitionsFactoryException {

        if (key == null) {
            return getDefaultFactory();
        }

        // Build possible postfixes
        List possiblePostfixes = calculateSuffixes((Locale) key);

        // Search last postix corresponding to a config file to load.
        // First check if something is loaded for this postfix.
        // If not, try to load its config.
        XmlDefinitionsSet lastXmlFile = null;
        DefinitionsFactory factory = null;
        String curPostfix = null;
        int i = 0;

        for (i = possiblePostfixes.size() - 1; i >= 0; i--) {
            curPostfix = (String) possiblePostfixes.get(i);

            // Already loaded ?
            factory = (DefinitionsFactory) loaded.get(curPostfix);
            if (factory != null) { // yes, stop search
                return factory;
            }

            // Try to load it. If success, stop search
            lastXmlFile = parseXmlFiles(servletContext, curPostfix, null);
            if (lastXmlFile != null) {
                break;
            }
        }

        // Have we found a description file ?
        // If no, return default one
        if (lastXmlFile == null) {
            return getDefaultFactory();
        }

        // We found something. Need to load base and intermediate files
        String lastPostfix = curPostfix;
        XmlDefinitionsSet rootXmlConfig = parseXmlFiles(servletContext, "", null);
        for (int j = 0; j < i; j++) {
            curPostfix = (String) possiblePostfixes.get(j);
            parseXmlFiles(servletContext, curPostfix, rootXmlConfig);
        }

        rootXmlConfig.extend(lastXmlFile);
        rootXmlConfig.resolveInheritances();

        factory = new DefinitionsFactory(rootXmlConfig);
        loaded.put(lastPostfix, factory);

        if (log.isDebugEnabled()) {
            log.debug("factory loaded : " + factory);
        }

        // return last available found !
        return factory;
    }

    /**
     * Calculate the suffixes based on the locale.
     * @param locale the locale
     */
    private List calculateSuffixes(Locale locale) {

        List suffixes = new ArrayList(3);
        String language = locale.getLanguage();
        String country  = locale.getCountry();
        String variant  = locale.getVariant();

        StringBuffer suffix = new StringBuffer();
        suffix.append('_');
        suffix.append(language);
        if (language.length() > 0) {
            suffixes.add(suffix.toString());
        }

        suffix.append('_');
        suffix.append(country);
        if (country.length() > 0) {
            suffixes.add(suffix.toString());
        }

        suffix.append('_');
        suffix.append(variant);
        if (variant.length() > 0) {
            suffixes.add(suffix.toString());
        }

        return suffixes;

    }

    /**
     * Parse files associated to postix if they exist.
     * For each name in filenames, append postfix before file extension,
     * then try to load the corresponding file.
     * If file doesn't exist, try next one. Each file description is added to
     * the XmlDefinitionsSet description.
     * The XmlDefinitionsSet description is created only if there is a definition file.
     * Inheritance is not resolved in the returned XmlDefinitionsSet.
     * If no description file can be opened and no definiion set is provided, return <code>null</code>.
     * @param postfix Postfix to add to each description file.
     * @param xmlDefinitions Definitions set to which definitions will be added. If <code>null</code>, a definitions
     * set is created on request.
     * @return XmlDefinitionsSet The definitions set created or passed as parameter.
     * @throws DefinitionsFactoryException On errors parsing file.
     */
    protected XmlDefinitionsSet parseXmlFiles(
        ServletContext servletContext,
        String postfix,
        XmlDefinitionsSet xmlDefinitions)
        throws DefinitionsFactoryException {

        if (postfix != null && postfix.length() == 0) {
            postfix = null;
        }

        // Iterate throw each file name in list
        Iterator i = filenames.iterator();
        while (i.hasNext()) {
            String filename = concatPostfix((String) i.next(), postfix);
            xmlDefinitions = parseXmlFile(servletContext, filename, xmlDefinitions);
        }

        return xmlDefinitions;
    }

    /**
     * Parse specified xml file and add definition to specified definitions set.
     * This method is used to load several description files in one instances list.
     * If filename exists and definition set is <code>null</code>, create a new set. Otherwise, return
     * passed definition set (can be <code>null</code>).
     * @param servletContext Current servlet context. Used to open file.
     * @param filename Name of file to parse.
     * @param xmlDefinitions Definitions set to which definitions will be added. If null, a definitions
     * set is created on request.
     * @return XmlDefinitionsSet The definitions set created or passed as parameter.
     * @throws DefinitionsFactoryException On errors parsing file.
     */
    protected XmlDefinitionsSet parseXmlFile(
        ServletContext servletContext,
        String filename,
        XmlDefinitionsSet xmlDefinitions)
        throws DefinitionsFactoryException {

        try {
            InputStream input = servletContext.getResourceAsStream(filename);
            // Try to load using real path.
            // This allow to load config file under websphere 3.5.x
            // Patch proposed Houston, Stephen (LIT) on 5 Apr 2002
            if (null == input) {
                try {
                    input =
                        new java.io.FileInputStream(
                            servletContext.getRealPath(filename));
                } catch (Exception e) {
                }
            }

            // If the config isn't in the servlet context, try the class loader
            // which allows the config files to be stored in a jar
            if (input == null) {
                input = getClass().getResourceAsStream(filename);
            }

            // If still nothing found, this mean no config file is associated
            if (input == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Can't open file '" + filename + "'");
                }
                return xmlDefinitions;
            }

            // Check if parser already exist.
            // Doesn't seem to work yet.
            //if( xmlParser == null )
            if (true) {
                xmlParser = new XmlParser();
                xmlParser.setValidating(isValidatingParser);
            }

            // Check if definition set already exist.
            if (xmlDefinitions == null) {
                xmlDefinitions = new XmlDefinitionsSet();
            }

            xmlParser.parse(input, xmlDefinitions);

        } catch (SAXException ex) {
            if (log.isDebugEnabled()) {
                log.debug("Error while parsing file '" + filename + "'.");
                ex.printStackTrace();
            }
            throw new DefinitionsFactoryException(
                "Error while parsing file '" + filename + "'. " + ex.getMessage(),
                ex);

        } catch (IOException ex) {
            throw new DefinitionsFactoryException(
                "IO Error while parsing file '" + filename + "'. " + ex.getMessage(),
                ex);
        }

        return xmlDefinitions;
    }

    /**
     * Concat postfix to the name. Take care of existing filename extension.
     * Transform the given name "name.ext" to have "name" + "postfix" + "ext".
     * If there is no ext, return "name" + "postfix".
     * @param name Filename.
     * @param postfix Postfix to add.
     * @return Concatenated filename.
     */
    private String concatPostfix(String name, String postfix) {
        if (postfix == null) {
            return name;
        }

        // Search file name extension.
        // take care of Unix files starting with .
        int dotIndex = name.lastIndexOf(".");
        int lastNameStart = name.lastIndexOf(java.io.File.pathSeparator);
        if (dotIndex < 1 || dotIndex < lastNameStart) {
            return name + postfix;
        }

        String ext = name.substring(dotIndex);
        name = name.substring(0, dotIndex);
        return name + postfix + ext;
    }

    /**
     * Return String representation.
     * @return String representation.
     */
    public String toString() {
        StringBuffer buff = new StringBuffer("I18nFactorySet : \n");
        buff.append("--- default factory ---\n");
        buff.append(defaultFactory.toString());
        buff.append("\n--- other factories ---\n");
        Iterator i = factories.values().iterator();
        while (i.hasNext()) {
            buff.append(i.next().toString()).append("---------- \n");
        }
        return buff.toString();
    }

}

⌨️ 快捷键说明

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