Search in sources :

Example 1 with FileSystemResource

use of com.helger.commons.io.resource.FileSystemResource in project ph-schematron by phax.

the class Schematron2XSLTMojo method execute.

public void execute() throws MojoExecutionException, MojoFailureException {
    StaticLoggerBinder.getSingleton().setMavenLog(getLog());
    if (m_aSchematronDirectory == null)
        throw new MojoExecutionException("No Schematron directory specified!");
    if (m_aSchematronDirectory.exists() && !m_aSchematronDirectory.isDirectory())
        throw new MojoExecutionException("The specified Schematron directory " + m_aSchematronDirectory + " is not a directory!");
    if (StringHelper.hasNoText(m_sSchematronPattern))
        throw new MojoExecutionException("No Schematron pattern specified!");
    if (m_aXsltDirectory == null)
        throw new MojoExecutionException("No XSLT directory specified!");
    if (m_aXsltDirectory.exists() && !m_aXsltDirectory.isDirectory())
        throw new MojoExecutionException("The specified XSLT directory " + m_aXsltDirectory + " is not a directory!");
    if (StringHelper.hasNoText(m_sXsltExtension) || !m_sXsltExtension.startsWith("."))
        throw new MojoExecutionException("The XSLT extension '" + m_sXsltExtension + "' is invalid!");
    if (!m_aXsltDirectory.exists() && !m_aXsltDirectory.mkdirs())
        throw new MojoExecutionException("Failed to create the XSLT directory " + m_aXsltDirectory);
    // for all Schematron files that match the pattern
    final DirectoryScanner aScanner = new DirectoryScanner();
    aScanner.setBasedir(m_aSchematronDirectory);
    aScanner.setIncludes(new String[] { m_sSchematronPattern });
    aScanner.setCaseSensitive(true);
    aScanner.scan();
    final String[] aFilenames = aScanner.getIncludedFiles();
    if (aFilenames != null) {
        for (final String sFilename : aFilenames) {
            final File aFile = new File(m_aSchematronDirectory, sFilename);
            // 1. build XSLT file name (outputdir + localpath with new extension)
            final File aXSLTFile = new File(m_aXsltDirectory, FilenameHelper.getWithoutExtension(sFilename) + m_sXsltExtension);
            getLog().info("Converting Schematron file '" + aFile.getPath() + "' to XSLT file '" + aXSLTFile.getPath() + "'");
            // 2. The Schematron resource
            final IReadableResource aSchematronResource = new FileSystemResource(aFile);
            // 3. Check if the XSLT file already exists
            if (aXSLTFile.exists() && !m_bOverwriteWithoutNotice) {
                // 3.1 Not overwriting the existing file
                getLog().debug("Skipping XSLT file '" + aXSLTFile.getPath() + "' because it already exists!");
            } else {
                // 3.2 Create the directory, if necessary
                final File aXsltFileDirectory = aXSLTFile.getParentFile();
                if (aXsltFileDirectory != null && !aXsltFileDirectory.exists()) {
                    getLog().debug("Creating directory '" + aXsltFileDirectory.getPath() + "'");
                    if (!aXsltFileDirectory.mkdirs()) {
                        final String message = "Failed to convert '" + aFile.getPath() + "' because directory '" + aXsltFileDirectory.getPath() + "' could not be created";
                        getLog().error(message);
                        throw new MojoFailureException(message);
                    }
                }
                // 3.3 Okay, write the XSLT file
                try {
                    buildContext.removeMessages(aFile);
                    // Custom error listener to log to the Mojo logger
                    final ErrorListener aMojoErrorListener = new PluginErrorListener(aFile);
                    // Custom error listener
                    // No custom URI resolver
                    // Specified phase - default = null
                    // Specified language code - default = null
                    final SCHTransformerCustomizer aCustomizer = new SCHTransformerCustomizer().setErrorListener(aMojoErrorListener).setPhase(m_sPhaseName).setLanguageCode(m_sLanguageCode).setParameters(m_aCustomParameters);
                    final ISchematronXSLTBasedProvider aXsltProvider = SchematronResourceSCHCache.createSchematronXSLTProvider(aSchematronResource, aCustomizer);
                    if (aXsltProvider != null) {
                        // Write the resulting XSLT file to disk
                        final MapBasedNamespaceContext aNSContext = new MapBasedNamespaceContext().addMapping("svrl", CSVRL.SVRL_NAMESPACE_URI);
                        // Add all namespaces from XSLT document root
                        final String sNSPrefix = XMLConstants.XMLNS_ATTRIBUTE + ":";
                        XMLHelper.forAllAttributes(aXsltProvider.getXSLTDocument().getDocumentElement(), (sAttrName, sAttrValue) -> {
                            if (sAttrName.startsWith(sNSPrefix))
                                aNSContext.addMapping(sAttrName.substring(sNSPrefix.length()), sAttrValue);
                        });
                        final XMLWriterSettings aXWS = new XMLWriterSettings();
                        aXWS.setNamespaceContext(aNSContext).setPutNamespaceContextPrefixesInRoot(true);
                        final OutputStream aOS = FileHelper.getOutputStream(aXSLTFile);
                        if (aOS == null)
                            throw new IllegalStateException("Failed to open output stream for file " + aXSLTFile.getAbsolutePath());
                        XMLWriter.writeToStream(aXsltProvider.getXSLTDocument(), aOS, aXWS);
                        getLog().debug("Finished creating XSLT file '" + aXSLTFile.getPath() + "'");
                        buildContext.refresh(aXsltFileDirectory);
                    } else {
                        final String message = "Failed to convert '" + aFile.getPath() + "': the Schematron resource is invalid";
                        getLog().error(message);
                        throw new MojoFailureException(message);
                    }
                } catch (final MojoFailureException up) {
                    throw up;
                } catch (final Exception ex) {
                    final String sMessage = "Failed to convert '" + aFile.getPath() + "' to XSLT file '" + aXSLTFile.getPath() + "'";
                    getLog().error(sMessage, ex);
                    throw new MojoExecutionException(sMessage, ex);
                }
            }
        }
    }
}
Also used : XMLWriterSettings(com.helger.xml.serialize.write.XMLWriterSettings) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) OutputStream(java.io.OutputStream) IReadableResource(com.helger.commons.io.resource.IReadableResource) MojoFailureException(org.apache.maven.plugin.MojoFailureException) SCHTransformerCustomizer(com.helger.schematron.xslt.SCHTransformerCustomizer) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) ErrorListener(javax.xml.transform.ErrorListener) AbstractTransformErrorListener(com.helger.xml.transform.AbstractTransformErrorListener) MapBasedNamespaceContext(com.helger.xml.namespace.MapBasedNamespaceContext) DirectoryScanner(org.codehaus.plexus.util.DirectoryScanner) File(java.io.File) ISchematronXSLTBasedProvider(com.helger.schematron.xslt.ISchematronXSLTBasedProvider)

Example 2 with FileSystemResource

use of com.helger.commons.io.resource.FileSystemResource in project ph-schematron by phax.

the class Schematron method execute.

@Override
public void execute() throws BuildException {
    boolean bCanRun = false;
    if (m_aSchematronFile == null)
        _error("No Schematron file specified!");
    else if (m_aSchematronFile.exists() && !m_aSchematronFile.isFile())
        _error("The specified Schematron file " + m_aSchematronFile + " is not a file!");
    else if (m_eSchematronProcessingEngine == null)
        _error("An invalid Schematron processing instance is specified! Only one of the following values is allowed: " + StringHelper.getImplodedMapped(", ", ESchematronMode.values(), x -> "'" + x.getID() + "'"));
    else if (m_aResCollections.isEmpty())
        _error("No XML resources to be validated specified! Add e.g. a <fileset> element.");
    else if (m_aSvrlDirectory != null && !m_aSvrlDirectory.exists() && !m_aSvrlDirectory.mkdirs())
        _error("Failed to create the SVRL directory " + m_aSvrlDirectory);
    else
        bCanRun = true;
    if (bCanRun) {
        // 1. Parse Schematron file
        final Locale aDisplayLocale = Locale.US;
        ISchematronResource aSch = null;
        IErrorList aSCHErrors = null;
        switch(m_eSchematronProcessingEngine) {
            case PURE:
                {
                    // pure
                    final CollectingPSErrorHandler aErrorHdl = new CollectingPSErrorHandler();
                    final SchematronResourcePure aRealSCH = new SchematronResourcePure(new FileSystemResource(m_aSchematronFile));
                    aRealSCH.setPhase(m_sPhaseName);
                    aRealSCH.setErrorHandler(aErrorHdl);
                    aRealSCH.setEntityResolver(getEntityResolver());
                    aRealSCH.validateCompletely();
                    aSch = aRealSCH;
                    aSCHErrors = aErrorHdl.getAllErrors();
                    break;
                }
            case SCHEMATRON:
                {
                    // SCH
                    final CollectingTransformErrorListener aErrorHdl = new CollectingTransformErrorListener();
                    final SchematronResourceSCH aRealSCH = new SchematronResourceSCH(new FileSystemResource(m_aSchematronFile));
                    aRealSCH.setPhase(m_sPhaseName);
                    aRealSCH.setLanguageCode(m_sLanguageCode);
                    aRealSCH.setErrorListener(aErrorHdl);
                    aRealSCH.setURIResolver(getURIResolver());
                    aRealSCH.setEntityResolver(getEntityResolver());
                    aRealSCH.isValidSchematron();
                    aSch = aRealSCH;
                    aSCHErrors = aErrorHdl.getErrorList();
                    break;
                }
            case XSLT:
                {
                    // SCH
                    final CollectingTransformErrorListener aErrorHdl = new CollectingTransformErrorListener();
                    final SchematronResourceXSLT aRealSCH = new SchematronResourceXSLT(new FileSystemResource(m_aSchematronFile));
                    // phase and language are ignored because this was decided when the
                    // XSLT
                    // was created
                    aRealSCH.setErrorListener(aErrorHdl);
                    aRealSCH.setURIResolver(getURIResolver());
                    aRealSCH.setEntityResolver(getEntityResolver());
                    aRealSCH.isValidSchematron();
                    aSch = aRealSCH;
                    aSCHErrors = aErrorHdl.getErrorList();
                    break;
                }
            default:
                _error("No handler for processing engine '" + m_eSchematronProcessingEngine + "'");
                break;
        }
        if (aSCHErrors != null) {
            // Error validating the Schematrons!!
            boolean bAnyParsingError = false;
            for (final IError aError : aSCHErrors) if (aError.getErrorLevel().isGE(EErrorLevel.ERROR)) {
                log("Error in Schematron: " + aError.getAsString(aDisplayLocale), Project.MSG_ERR);
                bAnyParsingError = true;
            } else if (aError.getErrorLevel().isGE(EErrorLevel.WARN))
                log("Warning in Schematron: " + aError.getAsString(aDisplayLocale), Project.MSG_WARN);
            if (bAnyParsingError)
                _error("The provided Schematron file contains errors. See log for details.");
            else {
                log("Successfully parsed Schematron file '" + m_aSchematronFile.getPath() + "'", Project.MSG_INFO);
                // 2. for all XML files that match the pattern
                _performValidation(aSch, m_aResCollections, m_aSvrlDirectory, m_bExpectSuccess);
            }
        }
    }
}
Also used : OverrideOnDemand(com.helger.commons.annotation.OverrideOnDemand) Task(org.apache.tools.ant.Task) IError(com.helger.commons.error.IError) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) URIResolver(javax.xml.transform.URIResolver) ResourceCollection(org.apache.tools.ant.types.ResourceCollection) FileResource(org.apache.tools.ant.types.resources.FileResource) SchematronResourceXSLT(com.helger.schematron.xslt.SchematronResourceXSLT) AbstractSVRLMessage(com.helger.schematron.svrl.AbstractSVRLMessage) SVRLHelper(com.helger.schematron.svrl.SVRLHelper) ESchematronMode(com.helger.schematron.ESchematronMode) Locale(java.util.Locale) Project(org.apache.tools.ant.Project) CollectingTransformErrorListener(com.helger.xml.transform.CollectingTransformErrorListener) Nonnull(javax.annotation.Nonnull) TransformSourceFactory(com.helger.xml.transform.TransformSourceFactory) Nullable(javax.annotation.Nullable) EntityResolver(org.xml.sax.EntityResolver) ErrorTextProvider(com.helger.commons.error.ErrorTextProvider) Resource(org.apache.tools.ant.types.Resource) EErrorLevel(com.helger.commons.error.level.EErrorLevel) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) StringHelper(com.helger.commons.string.StringHelper) SVRLMarshaller(com.helger.schematron.svrl.SVRLMarshaller) CollectingPSErrorHandler(com.helger.schematron.pure.errorhandler.CollectingPSErrorHandler) BuildException(org.apache.tools.ant.BuildException) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) File(java.io.File) SchematronOutputType(org.oclc.purl.dsdl.svrl.SchematronOutputType) XMLCatalog(org.apache.tools.ant.types.XMLCatalog) ISchematronResource(com.helger.schematron.ISchematronResource) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) ICommonsList(com.helger.commons.collection.impl.ICommonsList) SchematronResourceSCH(com.helger.schematron.xslt.SchematronResourceSCH) FileProvider(org.apache.tools.ant.types.resources.FileProvider) ICommonsMap(com.helger.commons.collection.impl.ICommonsMap) SchematronResourcePure(com.helger.schematron.pure.SchematronResourcePure) IErrorList(com.helger.commons.error.list.IErrorList) ResourceUtils(org.apache.tools.ant.util.ResourceUtils) Locale(java.util.Locale) SchematronResourceXSLT(com.helger.schematron.xslt.SchematronResourceXSLT) ISchematronResource(com.helger.schematron.ISchematronResource) SchematronResourceSCH(com.helger.schematron.xslt.SchematronResourceSCH) IErrorList(com.helger.commons.error.list.IErrorList) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) CollectingTransformErrorListener(com.helger.xml.transform.CollectingTransformErrorListener) IError(com.helger.commons.error.IError) SchematronResourcePure(com.helger.schematron.pure.SchematronResourcePure) CollectingPSErrorHandler(com.helger.schematron.pure.errorhandler.CollectingPSErrorHandler)

Example 3 with FileSystemResource

use of com.helger.commons.io.resource.FileSystemResource in project ph-schematron by phax.

the class Issue11Test method validateAndProduceSVRL.

public static void validateAndProduceSVRL(@Nonnull final File aSchematron, final File aXML) throws Exception {
    final SchematronResourcePure aSCH = SchematronResourcePure.fromFile(aSchematron);
    aSCH.setErrorHandler(new LoggingPSErrorHandler());
    assertTrue(aSCH.isValidSchematron());
    // Perform validation
    final SchematronOutputType aSVRL = aSCH.applySchematronValidationToSVRL(new FileSystemResource(aXML));
    assertNotNull(aSVRL);
    if (false)
        System.out.println(new SVRLMarshaller().getAsString(aSVRL));
}
Also used : SchematronOutputType(org.oclc.purl.dsdl.svrl.SchematronOutputType) LoggingPSErrorHandler(com.helger.schematron.pure.errorhandler.LoggingPSErrorHandler) SVRLMarshaller(com.helger.schematron.svrl.SVRLMarshaller) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) SchematronResourcePure(com.helger.schematron.pure.SchematronResourcePure)

Example 4 with FileSystemResource

use of com.helger.commons.io.resource.FileSystemResource in project ph-schematron by phax.

the class Issue36Test method testNestedExtends.

@Test
public void testNestedExtends() throws Exception {
    final SchematronResourcePure aResPure = SchematronResourcePure.fromFile("src/test/resources/issues/github36/test2.sch");
    aResPure.setErrorHandler(new LoggingPSErrorHandler());
    final SchematronOutputType aSOT = aResPure.applySchematronValidationToSVRL(new FileSystemResource("src/test/resources/issues/github36/test.xml"));
    assertNotNull(aSOT);
    assertFalse(SVRLHelper.getAllFailedAssertions(aSOT).isEmpty());
}
Also used : SchematronOutputType(org.oclc.purl.dsdl.svrl.SchematronOutputType) LoggingPSErrorHandler(com.helger.schematron.pure.errorhandler.LoggingPSErrorHandler) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) SchematronResourcePure(com.helger.schematron.pure.SchematronResourcePure) Test(org.junit.Test)

Example 5 with FileSystemResource

use of com.helger.commons.io.resource.FileSystemResource in project ph-schematron by phax.

the class Issue36Test method test.

@Test
public void test() throws Exception {
    final SchematronResourcePure aResPure = SchematronResourcePure.fromFile("src/test/resources/issues/github36/test.sch");
    aResPure.setErrorHandler(new LoggingPSErrorHandler());
    final SchematronOutputType aSOT = aResPure.applySchematronValidationToSVRL(new FileSystemResource("src/test/resources/issues/github36/test.xml"));
    assertNotNull(aSOT);
    assertFalse(SVRLHelper.getAllFailedAssertions(aSOT).isEmpty());
}
Also used : SchematronOutputType(org.oclc.purl.dsdl.svrl.SchematronOutputType) LoggingPSErrorHandler(com.helger.schematron.pure.errorhandler.LoggingPSErrorHandler) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) SchematronResourcePure(com.helger.schematron.pure.SchematronResourcePure) Test(org.junit.Test)

Aggregations

FileSystemResource (com.helger.commons.io.resource.FileSystemResource)25 SchematronOutputType (org.oclc.purl.dsdl.svrl.SchematronOutputType)18 SVRLMarshaller (com.helger.schematron.svrl.SVRLMarshaller)14 SchematronResourcePure (com.helger.schematron.pure.SchematronResourcePure)13 IReadableResource (com.helger.commons.io.resource.IReadableResource)8 AbstractSchematronResource (com.helger.schematron.AbstractSchematronResource)6 SchematronResourceSCH (com.helger.schematron.xslt.SchematronResourceSCH)6 LoggingPSErrorHandler (com.helger.schematron.pure.errorhandler.LoggingPSErrorHandler)5 ISchematronResource (com.helger.schematron.ISchematronResource)4 PSReader (com.helger.schematron.pure.exchange.PSReader)4 PSSchema (com.helger.schematron.pure.model.PSSchema)4 File (java.io.File)4 Test (org.junit.Test)4 PSPreprocessor (com.helger.schematron.pure.preprocess.PSPreprocessor)3 XMLWriterSettings (com.helger.xml.serialize.write.XMLWriterSettings)3 ICommonsList (com.helger.commons.collection.impl.ICommonsList)2 IError (com.helger.commons.error.IError)2 EErrorLevel (com.helger.commons.error.level.EErrorLevel)2 IErrorList (com.helger.commons.error.list.IErrorList)2 StringHelper (com.helger.commons.string.StringHelper)2