All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.jboss.maven.shared.xml.dom4j.DocumentLoader Maven / Gradle / Ivy

The newest version!
/*
 * Copyright (c) 2007, Red Hat Middleware, LLC. All rights reserved.
 *
 * This copyrighted material is made available to anyone wishing to use, modify,
 * copy, or redistribute it subject to the terms and conditions of the GNU
 * Lesser General Public License, v. 2.1. This program is distributed in the
 * hope that it will be useful, but WITHOUT A WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details. You should have received a
 * copy of the GNU Lesser General Public License, v.2.1 along with this
 * distribution; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * Red Hat Author(s): Steve Ebersole
 */
package org.jboss.maven.shared.xml.dom4j;

import java.io.File;
import java.util.List;
import java.util.ArrayList;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugin.MojoExecutionException;

/**
 * A helper for loading dom4j {@link Document documents}.
 *
 * @author Steve Ebersole
 */
public class DocumentLoader {
	private final Log log;

	public DocumentLoader(Log log) {
		this.log = log;
	}

	public Document loadDocument(File file) throws MojoExecutionException {
		String location = file.getAbsolutePath();
		try {
			List errors = new ArrayList();
			SAXReader saxReader = new SAXReader();
			saxReader.setErrorHandler( new ErrorLogger( location, errors, log ) );
			saxReader.setMergeAdjacentText( true );

			Document doc = saxReader.read( file );
			if ( errors.size() != 0 ) {
				throw new MojoExecutionException( "errors loading file [" + location + "]", ( Throwable ) errors.get( 0 ) );
			}
			return doc;
		}
		catch ( DocumentException e) {
			throw new MojoExecutionException( "errors loading file [" + location + "]", e );
		}
	}

	public static class ErrorLogger implements ErrorHandler {
		private final String file;
		private final List errors;
		private final Log log;

		public ErrorLogger(String file, List errors, Log log) {
			this.file = file;
			this.errors = errors;
			this.log = log;
		}

		public void error(SAXParseException error) {
			log.error( "Error parsing XML: " + file + '(' + error.getLineNumber() + ") " + error.getMessage() );
			errors.add(error);
		}

		public void fatalError(SAXParseException error) {
			error(error);
		}

		public void warning(SAXParseException warn) {
			log.warn( "Warning parsing XML: " + file + '(' + warn.getLineNumber() + ") " + warn.getMessage() );
		}

	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy