001 /*
002 Licensed to the Apache Software Foundation (ASF) under one
003 or more contributor license agreements. See the NOTICE file
004 distributed with this work for additional information
005 regarding copyright ownership. The ASF licenses this file
006 to you under the Apache License, Version 2.0 (the
007 "License"); you may not use this file except in compliance
008 with the License. You may obtain a copy of the License at
009
010 http://www.apache.org/licenses/LICENSE-2.0
011
012 Unless required by applicable law or agreed to in writing,
013 software distributed under the License is distributed on an
014 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 KIND, either express or implied. See the License for the
016 specific language governing permissions and limitations
017 under the License.
018 */
019 package org.apache.wiki.render;
020
021 import java.io.IOException;
022 import java.util.Iterator;
023 import java.util.List;
024
025 import org.apache.log4j.Logger;
026 import org.jdom2.JDOMException;
027 import org.jdom2.Text;
028 import org.jdom2.xpath.XPath;
029
030 import org.apache.wiki.WikiContext;
031 import org.apache.wiki.parser.WikiDocument;
032
033 /**
034 * A simple renderer that just renders all the text() nodes
035 * from the DOM tree. This is very useful for cleaning away
036 * all of the XHTML.
037 *
038 * @since 2.4
039 */
040 public class CleanTextRenderer
041 extends WikiRenderer
042 {
043 private static final String ALL_TEXT_NODES = "//text()";
044
045 protected static final Logger log = Logger.getLogger( CleanTextRenderer.class );
046
047 /**
048 * Create a renderer.
049 *
050 * @param context {@inheritDoc}
051 * @param doc {@inheritDoc}
052 */
053 public CleanTextRenderer( WikiContext context, WikiDocument doc )
054 {
055 super( context, doc );
056 }
057
058 /**
059 * {@inheritDoc}
060 */
061 public String getString()
062 throws IOException
063 {
064 StringBuffer sb = new StringBuffer();
065
066 try
067 {
068 XPath xp = XPath.newInstance( ALL_TEXT_NODES );
069
070 List nodes = xp.selectNodes(m_document.getDocument());
071
072 for( Iterator i = nodes.iterator(); i.hasNext(); )
073 {
074 Object el = i.next();
075
076 if( el instanceof Text )
077 {
078 sb.append( ((Text)el).getValue() );
079 }
080 }
081 }
082 catch( JDOMException e )
083 {
084 log.error("Could not parse XPATH expression");
085 throw new IOException( e.getMessage() );
086 }
087
088 return sb.toString();
089 }
090 }