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

📄 localizedstringsgenerator.java

📁 This is a resource based on j2me embedded,if you dont understand,you can connection with me .
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* * * * Copyright  1990-2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER *  * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 only, as published by the Free Software Foundation. *  * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details (a copy is * included at /legal/license.txt). *  * You should have received a copy of the GNU General Public License * version 2 along with this work; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA *  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa * Clara, CA 95054 or visit www.sun.com if you need additional * information or have any questions. * *//** * Generates localized string data from source XML file. */package com.sun.midp.l10n.generator;import java.io.*;import java.util.*;import javax.xml.parsers.*;import javax.xml.transform.*;import javax.xml.transform.dom.*;import javax.xml.transform.stream.StreamResult;import javax.xml.transform.stream.StreamSource;import org.w3c.dom.*;import org.xml.sax.ErrorHandler;import org.xml.sax.SAXParseException;import org.xml.sax.SAXException;/** *  Driver class with main(). Parses command line arguments and invokes *  LocalizedStringsGeneratorImpl instance that does all the transformation work. */public class LocalizedStringsGenerator {    /** Transformer that does actual transformation */    private static LocalizedStringsGeneratorImpl transformer = null;    /** XML file name to apply transformation to */    public static String xmlFileName = "";    /** Output file name */    public static String outFileName = "";    /** Print debug output while running */    private static boolean debug = false;    /** Print usage info and exit */    private static boolean printHelp = false;    /**     * Main method     *     * @param args Command line arguments     */    public static void main(String[] args) {        try {            parseArgs(args);            if (printHelp) {                printHelp();                return;            }            transformer = new LocalizedStringsGeneratorImpl(debug);            transformer.transform(xmlFileName, outFileName);        } catch (SAXException e) {            // error was already reported            e.printStackTrace();            System.exit(1);        } catch (Exception e) {            e.printStackTrace();            System.exit(1);        }    }    /**     * Parse command line arguments, adding Transformation objects to     * <tt>transformations</tt> vector for each transformation specified.     *     * @param args command line arguments     */    private static void parseArgs(String[] args)    {        for (int i = 0; i < args.length; ++i) {            String arg = args[i];            if (debug) {                System.err.println("arg: " + arg);            }            if (arg.equals("-xml")) {                xmlFileName = args[++i];            } else if (arg.equals("-out")) {                outFileName = args[++i];            } else if (arg.equals("-debug")) {                debug = true;            } else {                printHelp = true;            }        }    }    /**     * Print usage information     */    private static void printHelp() {        /**         * Following options are recognized:         * -xml:        Source XML file.         * -out:        Output file. If empty, output will be to stdout.         * -help:       Print usage information         * -debug:      Be verbose: print some debug info while running.         */        System.err.println("Usage: java -jar <l10n_generator_jar_file>"            + "-xml <localXMLFile> "            + "-out <localOutputFile> "            + "[-debug] "            + "[-help]");    }}/** * Perform the transformation */class LocalizedStringsGeneratorImpl {    /** Factory constructing Transformer objects */    private TransformerFactory transformerFactory =        TransformerFactory.newInstance();    /** Be verbose: print some debug info while running */    private boolean debug = false;    /**     * Constructor     *     * @param dbg print some debug output while running     */    public LocalizedStringsGeneratorImpl(boolean dbg)    {        debug = dbg;    }    /**     * Converts errors.     */    class GeneratorErrorHandler        implements ErrorHandler {        /**         * Handles errors.         * @param e the parsing exception         */        public void error(SAXParseException e)            throws SAXParseException {            reportError(e);            // rethrow exception to stop processing on first error            throw e;        }        /**         * Handles fatal errors.         * @param e the parsing exception         */        public void fatalError(SAXParseException e) {            reportError(e);        }        /**         * Handles warnings.         * @param e the parsing exception         */        public void warning(SAXParseException e) {            reportError(e);        }        /**         * Outputs diagnostic messages.         * @param e the parsing exception         */        private void reportError(SAXParseException e) {            String msg = e.getMessage();            String location = e.getSystemId();            int line = e.getLineNumber();            System.err.print("Error: URI=" + location);            System.err.println(" Line=" + line + ": " + msg);        }    }    /**     * Do the actual transformation     *     * @param tr transformation to perform     */    public void transform(String xmlFileName, String outFileName)        throws Exception {        if (debug) {            System.err.println("xml file: " + xmlFileName);            System.err.println("out file: " + outFileName);        }        // load XML file as DOM tree        DocumentBuilderFactory domFactory =            DocumentBuilderFactory.newInstance();        DocumentBuilder domBuilder = domFactory.newDocumentBuilder();        domBuilder.setErrorHandler(new GeneratorErrorHandler());        Document doc = domBuilder.parse(new File(xmlFileName));        // make source from it        DOMSource source = new DOMSource(doc);        generateLocalizedStrings(doc, outFileName);    }    /**     * Creates a directory structure.     *     * @param fullFileName Full path to the file to be created. If directory     * in which file is to be created doesn't exists, it will be created     * @exception IOException is thrown if directory couldn't be created     */    private void makeDirectoryTree(String fullFileName) throws IOException {        if (debug == true) {            System.out.println("mkdir: " + fullFileName);        }        int index = fullFileName.lastIndexOf(File.separatorChar);        if (index == -1) {            // To be compatible with MKS-hosted build on win32, which            // does not translate / to \.            index = fullFileName.lastIndexOf('/');        }        File outputDirectory = new File(fullFileName.substring(0, index));        if (!(outputDirectory).exists()) {            if (!(outputDirectory).mkdirs()) {                throw new IOException("failed to create output directory");            }        }    }    /**     * Generates localized strings.     * @param doc the current  working file     * @param outDir the target output directory     */    private void generateLocalizedStrings(Document doc, String outDir)         throws Exception    {        processLocalizedStrings(doc.getDocumentElement(), null);        for (Enumeration e = locales.keys(); e.hasMoreElements();) {            String key = (String)e.nextElement();            LocalizedStringSet locale = (LocalizedStringSet)locales.get(key);            String filename = outDir + File.separatorChar + locale.className;            makeDirectoryTree(filename);            // Write LocalizedStrings<locale>.c file            CSourceWriter cwriter = new CSourceWriter();            cwriter.writeCSource(locale, filename + ".c", locale.className);            // Write LocalizedStrings<locale>.java file            FileOutputStream out = new FileOutputStream(filename + ".java");            PrintWriter writer = new PrintWriter(new OutputStreamWriter(out));            writer.println("// This file is auto-generated. Don't edit!");            writer.println("package com.sun.midp.l10n;");            writer.println("abstract class " + locale.className + " {");            writer.println("    native static String getContent(int index);");            writer.println("}");            writer.close();        }    }    /**     * Walk the XML tree to discover all <localized_string> elements,     * collect them and write the data tables specific for each     * locale to a pair of Java and C source files.     * @param n the current node to be processed     * @param className the name of the class to handle this node     */    private void processLocalizedStrings(Node n, String className)        throws Exception {        if (n.getNodeName().equals("localized_strings") &&            (n instanceof Element)) {            Element e = (Element)n;            String pkg = e.getAttribute("Package");            String name = e.getAttribute("Name");            className = name;        } else if (n.getNodeName().equals("localized_string") &&            (n instanceof Element) && className != null) {            Element e = (Element)n;            String value = e.getAttribute("Value");            // we use key value as index            int valueIndex = Integer.parseInt(e.getAttribute("KeyValue"));            addLocalizedString(className, valueIndex, value);        }        NodeList list = n.getChildNodes();        for (int i=0; i<list.getLength(); i++) {            processLocalizedStrings(list.item(i), className);        }    }    /** Supported locales table. */    Hashtable locales = new Hashtable();    /**     * Add one <localized_string> element to the LocalizedStringSet of     * the enclosing <localized_strings>.     * @param className the locales handler     * @param valueIndex key for this entry     * @param value data for this entry     */    private void addLocalizedString(String className,            int valueIndex, String value)        throws Exception    {        LocalizedStringSet locale = (LocalizedStringSet)locales.get(className);        if (locale == null) {            locale = new LocalizedStringSet(className);            locales.put(className, locale);        }        locale.put(valueIndex, value);    }}/** * Records all localized strings for the locale represented by * a given Java class. */class LocalizedStringSet {    /** This Java class represents a given locale. */    String className;    /** All localized strings for this locale */    Vector strings;    /**     * Default constructor.     * @param className class name of locale handler     */    LocalizedStringSet(String className) {        this.className = className;        strings = new Vector(512);    }    /**     * Stores the current entry.     * @param idx the key     * @param value the data     */    void put(int idx, String value) {        if (strings.size() < idx + 1) {            strings.setSize(idx + 1);        }        strings.set(idx, value);    }}/** * This class records related information about each localized string */class LocalizedString {    /**     * Constructor with initial data.     * @param i the key     * @param s the value     */    LocalizedString(int i, String s) {        this.index = i;        this.string = s;    }

⌨️ 快捷键说明

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