devdaily home | apple | java | perl | unix | directory | blog

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

package wiki;

import java.util.Stack;

import org.stringtree.factory.AbstractStringFetcher;
import org.stringtree.juicer.string.SplitLinesStringFilter;
import org.stringtree.juicer.string.StringFilter;
import org.stringtree.juicer.string.StringStringSource;
import org.stringtree.regex.Matcher;
import org.stringtree.regex.Pattern;
import org.stringtree.util.StringUtils;

class LineTransformContext 
	extends Stack
{
	public String getType()
	{
		return (isEmpty())
			? null
			: StringUtils.stringValue(peek());
	}

	public void endList(StringBuffer buf)
	{
		if (!isEmpty())
		{
			String type = StringUtils.stringValue(pop());
			buf.append("</");
			buf.append(type);
			buf.append(">\n");
		}
	}

	public void startList(String type, StringBuffer buf)
	{
		push(type);
		buf.append("<");
		buf.append(type);
		buf.append(">\n");
	}

	public void endAll(StringBuffer buf)
	{
		while (!isEmpty())
		{
			endList(buf);
		}
	}

	public void ensureType(StringBuffer buf, String type, int indent)
	{
		while (!isEmpty() && size() > indent)
		{
			endList(buf);
		}
		while (size() < indent)
		{
			startList(type, buf);
		}

		if (!type.equals(getType()))
		{
			endList(buf);
			startList(type, buf);
		}
	}
}

public class ListRow
	extends AbstractStringFetcher
{
	private static Pattern pattern = Pattern.compile("^(\t+)(\\*|[1234567890]+)\\.?\\s*(.+)$");
	 
	public Object getObject(String content)
	{
		LineTransformContext context = new LineTransformContext();
		StringBuffer buf = new StringBuffer();

		StringFilter rows = new SplitLinesStringFilter();
		rows.connectSource(new StringStringSource(content));
		
		for (String row = rows.nextString(); row != null; row = rows.nextString())
		{
			Matcher matcher = pattern.matcher(row);

			if (matcher.find() && matcher.groupCount() >= 3)
			{
				int indent = matcher.group(1).length();
				String type = ("*".equals(matcher.group(2))) ? "ul" : "ol";
				String text = matcher.group(3);

				context.ensureType(buf, type, indent);
				buf.append("<li>");
				buf.append(text);
				buf.append("</li>\n");
			}
			else
			{
				buf.append(row);
				buf.append("\n");
			}
		}
		context.endAll(buf);

		String ret = buf.toString();
		return ret;
	}
}




Copyright 1998-2008 Alvin Alexander
All Rights Reserved.
 
devdaily.com is based in louisville, kentucky, and this web site is hosted by godaddy.com