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

📄 htmlnormalizerfilter.java

📁 jxta官方例程
💻 JAVA
字号:
/*
*  Copyright (c) 2001 Sun Microsystems, Inc.  All rights
*  reserved.
*
*  Redistribution and use in source and binary forms, with or withouta
*  modification, are permitted provided that the following conditions
*  are met:
*
*  1. Redistributions of sourcec code must retain the above copyright
*  notice, this list of conditions and the following disclaimer.
*
*  2. Redistributions in binary form must reproduce the above copyright
*  notice, this list of conditions and the following discalimer in
*  the documentation and/or other materials provided with the
*  distribution.
*
*  3. The end-user documentation included with the redistribution,
*  if any, must include the following acknowledgment:
*  "This product includes software developed by the
*  Sun Microsystems, Inc. for Project JXTA."
*  Alternately, this acknowledgment may appear in the software itself,
*  if and wherever such third-party acknowledgments normally appear.
*
*  4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA"
*  must not be used to endorse or promote products derived from this
*  software without prior written permission. For written
*  permission, please contact Project JXTA at http://www.jxta.org.
*
*  5. Products derived from this software may not be called "JXTA",
*  nor may "JXTA" appear in their name, without prior written
*  permission of Sun.
*
*  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
*  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*  DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
*  ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
*  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
*  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
*  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
*  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*  SUCH DAMAGE.
*  ===================================================tre=================
*
*  This software consists of voluntary contributions made by many
*  individuals on behalf of Project JXTA.  For more
*  information on Project JXTA, please see
*  <http://www.jxta.org/>.
*
*
*  $Id: HTMLNormalizerFilter.java,v 1.2 2005/01/07 12:18:54 mcangus Exp $
*/
package net.jxta.myjxta.dialog.filter;

import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;

import net.jxta.myjxta.dialog.DialogMessage;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Normalizes HTML Text to be displayed in the Dialog panel.
 *
 * @author james todd [gonzo at jxta dot org]
 * @author mike mcangus [mcangus at jxta dot org]
 */
public class HTMLNormalizerFilter extends AbstractDialogFilter {
    
    private static final String IMPLIED_SUFFIX = "-implied";
    private static final String HTML_PREFIX = "<html";

    private static final Logger LOG = Logger.getLogger(HTMLNormalizerFilter.class);

    private static final String PREFIX = "<span class='preamble'>[";
    private static final String AT = "@";
    private static final String POSTFIX = "]</span>";
    private static final String SPACE = " "; //"&nbsp;";

    private static final String PREAMBLE_FORMAT = PREFIX + "<span class='peerName'>{0}</span>" + AT + "{1}" + POSTFIX + SPACE;
    private static final String TIMESTAMP_FORMAT = "hh:mm:ss";

    private MessageFormat preambleFormatter = new MessageFormat(PREAMBLE_FORMAT);
    private SimpleDateFormat dateFormatter = new SimpleDateFormat(TIMESTAMP_FORMAT);
    
    /**
     * Called if a new DialogMessage was received
     *
     * @param msg the newly received DialogMessage object
     * @return the newly modified DialogMessage object.
     */
    public DialogMessage filter(DialogMessage msg) {
        if (LOG.isEnabledFor(Level.DEBUG)) {
            LOG.debug("Begin filter(DialogMessage)");
            LOG.debug("msg      = " + msg.getOriginator() + ":" + msg.getMessage());
        }

        String text = null;
        String preamble = null;
        String htmlText = null;
        
        if (msg != null) {
            text = msg.getMessage() != null ?
                msg.getMessage().trim() : "";
            String orig = msg.getOriginator();
            Date timeStamp = msg.getTimeStamp();
            preamble = this.preambleFormatter.format(new Object[] {
                orig != null && orig.trim().length() > 0 ?
                    orig : DialogMessage.DEFAULT_ORIGINATOR,
                this.dateFormatter.format(timeStamp != null ? timeStamp : new Date())
            });
        }

        HTMLEditorKit htmlEditor = new HTMLEditorKit();
        HTMLDocument workingDoc = (HTMLDocument)htmlEditor.createDefaultDocument();
        Element bodyTag = null;
        Element pTag = null;

        if (text.toLowerCase().indexOf(HTML_PREFIX) > -1) {
            if (LOG.isEnabledFor(Level.DEBUG)) {
                LOG.debug("Processing text/html document");
            }
            
            // Put the HTML msg into the workingDoc, without the preamble.
            try {
                htmlEditor.read(new StringReader(text), workingDoc, 0);

                // Add the preamble to the message
                bodyTag = getFirstElement(workingDoc, HTML.Tag.BODY);
                pTag = getFirstElement(bodyTag, HTML.Tag.P);
                workingDoc.insertAfterStart(pTag, preamble);
            } catch (IOException ioe) {
                if (LOG.isEnabledFor(Level.ERROR)) {
                    LOG.error("Caught unexpected Exception", ioe);
                }
                
                return msg;
            } catch (BadLocationException ble) {
                if (LOG.isEnabledFor(Level.ERROR)) {    
                    LOG.error("Caught unexpected Exception", ble);
                }
                
                return msg;
            }
            
            htmlText = getText(workingDoc);

            if (LOG.isEnabledFor(Level.DEBUG) && preamble.length() > 0) {
                LOG.debug("message = " + htmlText);
            }
        } else if (text.length() > 0) {
            if (LOG.isEnabledFor(Level.DEBUG)) {    
                LOG.debug("Processing text/plain document");
            }
            
            bodyTag = getFirstElement(workingDoc, HTML.Tag.BODY);
            pTag = getFirstElement(bodyTag, HTML.Tag.P);
            
            try {
                if (LOG.isEnabledFor(Level.DEBUG)) {
                    LOG.debug("preamble:msg = " + preamble + ":" + text);
                }
                
                workingDoc.insertAfterStart(pTag, preamble + text);
            } catch (IOException ioe) {
                if (LOG.isEnabledFor(Level.ERROR)) {
                    LOG.error("Caught unexpected Exception", ioe);
                }
                
                return msg;
            } catch (BadLocationException ble) {
                if (LOG.isEnabledFor(Level.ERROR)) {
                    LOG.error("Caught unexpected Exception",ble);
                }
                
                return msg;
            }
            
            htmlText = getText(workingDoc);
        } else {
            htmlText = "";
        }
        
        msg.setMessage(htmlText);

        if (LOG.isEnabledFor(Level.DEBUG)) {
            LOG.debug("returning \"" + msg + "\"");
            LOG.debug("End   normalize(String, String)");
        }
        
        return msg;
    }

    private static Element getFirstElement(HTMLDocument d, HTML.Tag t) {
        if (LOG.isEnabledFor(Level.DEBUG)) {    
            LOG.debug("In getFirstElement(HTMLDocument, HTML.Tag)");
        }
        
        return getFirstElement(d.getDefaultRootElement(), t);
    }

    private static Element getFirstElement(Element e, HTML.Tag t) {
        if (LOG.isEnabledFor(Level.DEBUG)) {
            LOG.debug("Begin getFirstElement(Element, HTML.Tag)");
            LOG.debug("Element = " + e.getName());
            LOG.debug("HTML.Tag = " + t.toString());
        }
        
        Element te = null;
        Element be = null;
        
        for (int i = 0; i < e.getElementCount(); i++) {
            be = e.getElement(i);
            
            if (be.getName().equals(t.toString()) ||
                be.getName().equals(t.toString() + IMPLIED_SUFFIX)) {
                te = be;
                break;
            }
            
            if (! be.isLeaf()) {
                te = getFirstElement(be, t);
            }
        }

        if (LOG.isEnabledFor(Level.DEBUG)) {
            LOG.debug("returning " + (te != null ? te.getName() : "null"));
            LOG.debug("End   getFirstElement(Element, HTML.Tag)");
        }
        
        return te;
    }

    private static String getText(Document d) {
        if (LOG.isEnabledFor(Level.DEBUG)) {
            LOG.debug("Begin getText(Document)");
        }
        
        Writer w = new StringWriter();
        HTMLEditorKit ek = new HTMLEditorKit();

        try {
            ek.write(w, d, 0, d.getLength());
        } catch (IOException ioe) {
            if (LOG.isEnabledFor(Level.ERROR)) {
                LOG.error("Caught unexpected Exception", ioe);
            }
        } catch (BadLocationException ble) {
            if (LOG.isEnabledFor(Level.ERROR)) {
                LOG.error("Caught unexpected Exception", ble);
            }
        }

        if (LOG.isEnabledFor(Level.DEBUG)) {
            LOG.debug("End   getText(Document)");
        }
        
        return w != null ? w.toString() : null;
    }
}

⌨️ 快捷键说明

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