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

com.crabshue.commons.xml.schema.XmlSchemaUtils Maven / Gradle / Ivy

There is a newer version: 1.1.0
Show newest version
package com.crabshue.commons.xml.schema;

import java.io.File;
import java.net.URL;

import org.xml.sax.InputSource;

import com.crabshue.commons.xml.inputsource.InputSourceBuilder;
import com.crabshue.commons.xml.sax.SaxParsingExecutor;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;

/**
 * Utility class for XML schema operations.
 */
@Slf4j
public class XmlSchemaUtils {

    protected XmlSchemaUtils() {

    }

    /**
     * Parse an {@link File XML file} and extract its schema location ({@code xsi:schemaLocation} or {@code xsi:noNamespaceSchemaLocation}).
     *
     * @param xmlFile the XML file
     * @return the URL of the schema location
     */
    public static URL extractSchemaUrl(@NonNull final File xmlFile) {

        final File parentFolder = xmlFile.getParentFile();
        return extractSchemaUrl(xmlFile, parentFolder);
    }

    /**
     * Parse an {@link File XML file} and extract its schema location ({@code xsi:schemaLocation} or {@code xsi:noNamespaceSchemaLocation}).
     *
     * @param xmlFile      the XML file
     * @param schemaFolder the base folder containing the schemas (in case schema is located on file system)
     * @return the URL of the schema location
     */
    public static URL extractSchemaUrl(@NonNull final File xmlFile,
                                       @NonNull final File schemaFolder) {

        final URL ret = extractSchemaUrl(InputSourceBuilder.newInputSource(xmlFile), schemaFolder);
        logger.info("Schema of XML file [{}] is located at [{}]", xmlFile, ret);
        return ret;
    }

    public static URL extractSchemaUrl(@NonNull final InputSource xmlInputSource,
                                       @NonNull final File schemaFolder) {

        final SchemaLocationSaxHandler schemaLocationHandler = new SchemaLocationSaxHandler(schemaFolder);
        SaxParsingExecutor.parseXmlFile(xmlInputSource, schemaLocationHandler);
        final URL ret = schemaLocationHandler.getSchemaUrl();
        logger.info("Schema of XML file is located at [{}]", ret);
        return ret;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy