Markup.java
/***************************************************************************
Copyright 2014 Emily Estes
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
***************************************************************************/
package net.metanotion.contentstore.markup;
import java.io.StringReader;
import java.util.ArrayList;
import net.metanotion.contentstore.markup.parser.ParseException;
import net.metanotion.web.html.Html;
import net.metanotion.web.html.SafeString;
import net.metanotion.web.html.Tag;
/** This class parses a string into HTML suitable for injecting in a web page. */
public final class Markup {
private static final Load loader = new Load();
/** Parse a string into safe HTML content.
@param content The string to parse.
@return A safe HTML representation of the content.
*/
public static Iterable<Html> htmlize(final String content) {
try {
return loader.load(new StringReader(content));
} catch (ParseException pe) {
try {
// Downgrade to double-new-lines-as-paragraphs
final String[] para = content.split("[\\r\\n|\\n]{2,}+");
final ArrayList<Html> result = new ArrayList<>(para.length);
for(final String s: para) {
result.add(new Tag("p").add(new SafeString(s)));
}
return result;
} catch(final Exception e) {
// Well, that failed, so let's just escape it all.
final ArrayList<Html> result = new ArrayList<>(1);
result.add(new SafeString(content));
return result;
}
}
}
}