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 */ 019package org.apache.wiki.render; 020 021import org.apache.log4j.Logger; 022import org.apache.wiki.WikiContext; 023import org.apache.wiki.parser.WikiDocument; 024import org.jdom2.Text; 025import org.jdom2.xpath.XPathFactory; 026 027import java.io.IOException; 028import java.util.List; 029 030 031/** 032 * A simple renderer that just renders all the text() nodes from the DOM tree. 033 * This is very useful for cleaning away all of the XHTML. 034 * 035 * @since 2.4 036 */ 037public class CleanTextRenderer extends WikiRenderer { 038 039 private static final String ALL_TEXT_NODES = "//text()"; 040 private static final Logger log = Logger.getLogger( CleanTextRenderer.class ); 041 042 /** 043 * Create a renderer. 044 * 045 * @param context A WikiContext in which the rendering will take place. 046 * @param doc The WikiDocument which shall be rendered. 047 */ 048 public CleanTextRenderer( final WikiContext context, final WikiDocument doc ) { 049 super( context, doc ); 050 } 051 052 /** 053 * {@inheritDoc} 054 */ 055 public String getString() throws IOException { 056 final StringBuilder sb = new StringBuilder(); 057 try { 058 final List< ? > nodes = XPathFactory.instance().compile( ALL_TEXT_NODES ).evaluate( m_document.getDocument() ); 059 for( final Object el : nodes ) { 060 if( el instanceof Text ) { 061 sb.append( ( ( Text )el ).getValue() ); 062 } 063 } 064 } catch( final IllegalStateException e ) { 065 log.error("Could not parse XPATH expression"); 066 throw new IOException( e.getMessage(), e ); 067 } 068 069 return sb.toString(); 070 } 071 072}