3 * Copyright © 2014 František Kučera (frantovo.cz)
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 3 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package cz.frantovo.alt2xml.out;
19 import java.io.IOException;
20 import java.util.logging.Level;
21 import java.util.logging.Logger;
22 import javax.xml.parsers.SAXParser;
23 import org.xml.sax.InputSource;
24 import org.xml.sax.SAXException;
25 import org.xml.sax.SAXNotRecognizedException;
26 import org.xml.sax.SAXNotSupportedException;
27 import org.xml.sax.ext.LexicalHandler;
28 import org.xml.sax.helpers.DefaultHandler;
31 * Recommended base class for Actions based on handlers.
33 * @author Ing. František Kučera (frantovo.cz)
35 public abstract class AbstractHandlerAction extends AbstractAction {
37 private static final Logger log = Logger.getLogger(AbstractHandlerAction.class.getName());
38 public static final String LEXICAL_HANDLER_PROPERTY = "http://xml.org/sax/properties/lexical-handler";
40 public AbstractHandlerAction(ActionContext actionContext) {
44 public abstract DefaultHandler getDefaultHandler();
47 * For e.g. comment nodes.
49 * @return may return null if this output module does not support lexical events
51 public LexicalHandler getLexicalHandler() {
56 public void run(SAXParser parser, InputSource source) throws OutputActionException {
57 DefaultHandler defaultHandler = getDefaultHandler();
58 LexicalHandler lexicalHandler = getLexicalHandler();
60 if (lexicalHandler == null) {
61 log.log(Level.FINE, "No LexicalHandler provided → no comment nodes etc. on output.");
64 parser.setProperty(LEXICAL_HANDLER_PROPERTY, lexicalHandler);
65 } catch (SAXNotRecognizedException | SAXNotSupportedException e) {
66 log.log(Level.WARNING, "LexicalHandler registration exception:", e);
67 log.log(Level.WARNING,
68 "Tried to register the handler {0} as a LexicalHandler but LexicalHandlers are not supported by the parser {1}",
69 new Object[]{lexicalHandler, parser});
74 parser.parse(source, defaultHandler);
75 } catch (IOException | SAXException e) {
76 throw new OutputActionException("Error while parsing document: " + source, e);