htmltemplatedisplay.java

来自「JAVA开源LDAP浏览器jxplorer的源码!」· Java 代码 · 共 1,490 行 · 第 1/5 页

JAVA
1,490
字号
                recreateEditor(current, htmlText);
            }
        }
        else
        {
            recreateEditor(current, htmlText);
        }
        editor.validate();

        // TODO: figure out a way of being able to reuse the viewport without getting exceptions.
        // In Java 1.5 exceptions are thrown more than not when reusing the viewport.
        // Now we will recreated it each time :-S
        try
        {
            viewport.setView(editor);
        }
        catch (ArrayIndexOutOfBoundsException e) // XXX sun stuff sometimes throws an exception, claiming the viewport has no existing child??
        {
            viewport = new JViewport();
            viewport.setView(editor);
            scrollDisplay.setViewport(viewport);
        }
    }

    /**
     * The Swing editor is a fragile beast, and must be frequently executed because deep inside it is as
     * buggy a piece of crap as Sun ever wrote.
     * @param current
     * @param htmlText
     */
    private void recreateEditor(Dimension current, String htmlText)
    {
        editor = getNewEditor();
        if (current == null) // this occasionally happens.  *shrug*
        {
            //System.out.println("CURRENT IS NULL???");
            current = new Dimension (400,400);
        }
        editor.setSize(current);
        editor.setText(htmlText);
    }


    /**
     *	As advised in the doco, it is apparently better to re-create an
     *  editor pane every time, rather than reuse the old one.  Phenomenal.
     *
     *  Sept '04 - this method causes a memory leak, so calling repeatedly
     * is not advised.  The doco actually advises recreating the document
     * object, however for our purposes we can probably accept the performance
     * hit of tearing down the old document and rebuilding it.  Seems to fix
     * the memory leak anyway :-).
     */

    protected JEditorPane getNewEditor()
    {
        // this fixes the memory leak, but removes the point of the method -
        // better not to call it at all.
        //if (editor != null) { return editor; }

        //System.out.println("Getting new editor");

        JEditorPane newEditor = new JEditorPane();

        newEditor.setEditorKitForContentType("text/html", htmlEditorKit);
        newEditor.addHyperlinkListener(hyperlinkListener);
        newEditor.setEditable(false);
        newEditor.setMinimumSize(new Dimension(400, 400));
        newEditor.setContentType("text/html");

        return newEditor;

    }

    /**
     * <p>This code is run by both constructors.  It sets up the GUI and the template lists, and other
     * housekeeping tasks.</p>
     * @param owner
     * @param props
     * @param resourceLoader
     */
    private void commonConstructorCode(Component owner, Properties props, CBResourceLoader resourceLoader)
    {
        initMyProperties(props);

        this.resourceLoader = resourceLoader;

        setupTemplateLists();

/*
        baseURL = JXplorer.getFileURL(myProperties.getProperty("dir.templates"));
        try
        {
            base = new URL(baseURL);
        }
        catch (MalformedURLException e)
        {
            log.warning(" unable to parse file url: " + baseURL + "\n ( error was: " + e + " )");
        }

        localURL = myProperties.getProperty("dir.local"); 							//TE: gets the path of the users local dir.
*/
        initGUI(owner);

        setStartPage();



    }

    /**
     * <p>This searches the template directories at start up, and builds up a list
     * of available templates, keyed by lowercase object class.</p>
     */
    private void setupTemplateLists()
    {
        try
        {
            // unpack any plugin templates (sets 'pluginTemplateDirectory')
            initZipTemplates();

            // Find the root of the /template directory tree
            baseTemplateDir = getBaseTemplateDirectory();
            String baseTemplate = baseTemplateDir.getCanonicalPath();

            // get the list of default html templates that can be used for all object classes
            String[] defaultTemplates = CBUtility.readFilteredDirectory(baseTemplate, new String[]{"html", "htm"});

            addToGlobalTemplateList(defaultTemplates, DEFAULT);

            // do the same for the plugin templates (if any)
            if (pluginTemplateDirectory != null)
            {

                defaultTemplates = CBUtility.readFilteredDirectory(pluginTemplateDirectory.getCanonicalPath(), new String[]{"html", "htm"});
                addToGlobalTemplateList(defaultTemplates, "");
            }

            if (defaultTemplates == null || defaultTemplates.length == 0)
                log.warning("Warning - can't find any default html templates in " + baseTemplate);

            // get the list of object class directories (e.g. /person, /organizationalUnit etc.)
            String[] objectClassFolders = getAllTemplateSubDirectories(baseTemplateDir);
            addIndividualObjectClassTemplates(objectClassFolders, baseTemplate);

            // do the same for the plugin templates (if any)
            if (pluginTemplateDirectory != null)
            {
                objectClassFolders = getAllTemplateSubDirectories(pluginTemplateDirectory);
                addIndividualObjectClassTemplates(objectClassFolders, pluginTemplateDirectory.toString());
            }

            //printTemplates();
        }
        catch (FileNotFoundException e)
        {
            log.warning("Error initialising HTML Template: " + e.toString());
        }
        catch (IOException e2)
        {
            log.warning("Error initialising HTML Template file paths: " + e2.toString());
        }
    }
/*
    private void printTemplates()
    {
            System.out.println("***PRINTING TEMPLATES VARIABLE***");
            Enumeration bloop = templates.keys();
            while (bloop.hasMoreElements())
            {
                String key = (String)bloop.nextElement();
                System.out.println("hashtable: " + key);
                File[] files = (File[]) templates.get(key);
                if (files == null)
                    System.out.println("  NULL !");
                else
                    for (int i=0; i<files.length; i++)
                        System.out.println("  -> " + files[i].toString());
            }
    }
*/
    private void addIndividualObjectClassTemplates(String[] objectClassFolders, String baseTemplate)
    {
        // search the discovered object class directories, adding their html templates to the global hash.
        for (int i = 0; i < objectClassFolders.length; i++)
        {
            String folderName = baseTemplate + File.separator + objectClassFolders[i];
            String objectClass = objectClassFolders[i];
            String[] ocTemplates = CBUtility.readFilteredDirectory(folderName, new String[]{"html", "htm"});
            addToGlobalTemplateList(ocTemplates, objectClass);
        }
    }

    /**
     * <p>Adds a directory of html files (with paths relative to baseTemplateDir) to the global hash, keyed by lower case object class.</p>
     * @param fileNames the individual file names
     * @param folderName the name of the folder, in mixed case, which is also the object class to key by.
     */
    private void addToGlobalTemplateList(String[] fileNames, String folderName)
    {
        if (fileNames == null)  // there may not be any templates at all...
            return;

        String objectClass = folderName.toLowerCase();

        File[] fileList = new File[fileNames.length];
        for (int i = 0; i < fileNames.length; i++)
        {
            if (DEFAULT.equals(folderName))
                fileList[i] = new File(fileNames[i]);
            else
                fileList[i] = new File(folderName, fileNames[i]);
        }

        // add the array of files to the hashtable, keyed by lowercase object class.
        templates.put(objectClass, fileList);
    }

    /**
     * <p>CONSTRUCTOR METHOD: returns all sub directories under the template directory</p>
     * <p>These correspond to the various object classes.</p>
     * @param baseTemplateDir
     * @return
     */
    private String[] getAllTemplateSubDirectories(File baseTemplateDir)
    {
        String[] childDirectories = baseTemplateDir.list(new FilenameFilter()
        {
            public boolean accept(File dir, String name)
            {
                File candidate = new File(dir, name);
                return candidate.isDirectory();
            }
        });

        return childDirectories;
    }

    /**
     * <p>CONSTRUCTOR METHOD: This finds the root of the /templates directory tree, where the
     * html file templates are stored.  (It is also where any templates
     * in .zip resource files are kept.)</p>
     * @return the file location of /templates (usually [jxplorer home]/templates )
     * @throws FileNotFoundException
     */
    private File getBaseTemplateDirectory()
            throws FileNotFoundException
    {
        File baseTemplateDir = new File(myProperties.getProperty("dir.templates"));
        if (!baseTemplateDir.exists())
        {
            log.warning("can't find html template directory " + baseTemplateDir + " - trying to find /templates directory");
            baseTemplateDir = new File(JXplorer.localDir + "templates" + File.separator);
            if (!baseTemplateDir.exists())
            {
                throw new FileNotFoundException("ERROR - Cannot find backup /template directory in " + baseTemplateDir);
            }
        }
        return baseTemplateDir;
    }

    /**
     *	<p>Gets any resourses from a zip/jar file depending on the object class of the entry.
     *	For example, if the oc is person, this checks the zip/jar file for resources in
     *	templates/oc/.  It then extracts these files and puts them in a temporary dir of the
     *	same path within the plugins dir.  For example, jxplorer/plugins/templates/oc/Main.html .
     *
     * <p>This is Trudi code, that has been kidnapped by Chris and mungified...
     * It now unpacks permanently, and only does the writing if needed (checks the
     * date stamps).</p>
     */
    private void initZipTemplates()
    {
        String[] zipTemplates = null;		//TE: stores the names of any resourses found in the zip/jar file.

        File pluginDirectory = new File(JXplorer.getProperty("dir.plugins"));
        if (!pluginDirectory.exists())
            pluginDirectory.mkdirs();

        //zipTemplates = resourceLoader.getPrefixedResources("templates/"+className+"/");//+File.separator);// doesn't wk w file.sep??????

        // read all plugin files with the prefix 'templates/'

        zipTemplates = resourceLoader.getPrefixedResources("templates/");

        if (zipTemplates.length == 0)
            return; // nothing to do!

        pluginTemplateDirectory = new File(pluginDirectory, "templates/");

        // unpack them to the plugins directory.

        int prefixSize = "templates/".length();

        for (int i = 0; i < zipTemplates.length; i++)
        {
            // get the template name as a string and as a (potential) file.
            String templateName = zipTemplates[i];

⌨️ 快捷键说明

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