com.greenpepper.html.BulletListFilter Maven / Gradle / Ivy
The newest version!
/*
* Copyright (c) 2006 Pyxis Technologies inc.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This software 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 for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA,
* or see the FSF site: http://www.fsf.org.
*/
package com.greenpepper.html;
import com.greenpepper.util.StringUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.String.format;
/**
* BulletListFilter class.
*
* @author oaouattara
* @version $Id: $Id
*/
public class BulletListFilter implements HtmlContentFilter
{
private static final String ELEMENT_BOUNDARY = "(?s)<\\s*(.*?)\\s*.*?>(.*?)<\\s*/\\s*\\1\\s*>";
private List requiredInnerTags = new ArrayList();
BulletListFilter(String ... requiredInnerTags) {
for (String requiredInnerTag : requiredInnerTags) {
this.requiredInnerTags.add(Pattern.compile(
format("<%1$s\\s*?.*?>.*?", requiredInnerTag), Pattern.CASE_INSENSITIVE
));
}
}
/** {@inheritDoc} */
public boolean handles(String tag)
{
return tag.equalsIgnoreCase( "li" );
}
/** {@inheritDoc} */
public String process(String content)
{
// We will breakdown the inner elements with spans only if required
if (shouldBreakTheContentDown(content)) {
Matcher matcher = Pattern.compile(ELEMENT_BOUNDARY, Pattern.CASE_INSENSITIVE).matcher(content);
StringBuilder sb = new StringBuilder();
int startIndex, matchIndex;
for (startIndex = 0; matcher.find(); startIndex = matcher.end()) {
matchIndex = matcher.start();
String preMatch = content.substring(startIndex, matchIndex);
if (!StringUtil.isBlank(preMatch)) sb.append(span(preMatch));
if (!StringUtil.isBlank(matcher.group(2))) sb.append(matcher.group());
}
String postMatch = content.substring(startIndex, content.length());
if (!StringUtil.isBlank(postMatch)) sb.append(span(postMatch));
return sb.toString();
}
return span(content);
}
private boolean shouldBreakTheContentDown(String content) {
if (requiredInnerTags.isEmpty()) return true;
for (Pattern requiredInnerTagPattern : requiredInnerTags) {
if (requiredInnerTagPattern.matcher(content).find()) {
return true;
}
}
return false;
}
private String span(String content)
{
return format( "%s", content );
}
}