Search in sources :

Example 1 with IReadableResource

use of com.helger.commons.io.resource.IReadableResource 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 IReadableResource

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

the class SchematronResourcePureTest method testBasic.

@Test
public void testBasic() throws Exception {
    for (final IReadableResource aRes : SchematronTestHelper.getAllValidSchematronFiles()) {
        // The validity is tested in another test case!
        // Parse them
        final SchematronResourcePure aResPure = new SchematronResourcePure(aRes);
        assertTrue(aRes.getPath(), aResPure.isValidSchematron());
    }
}
Also used : IReadableResource(com.helger.commons.io.resource.IReadableResource) Test(org.junit.Test)

Example 3 with IReadableResource

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

the class MainBenchmarkIsValidSchematron method main.

public static void main(final String[] args) {
    logSystemInfo();
    final ICommonsList<IReadableResource> aValidSchematrons = new CommonsArrayList<>();
    for (final IReadableResource aRes : SchematronTestHelper.getAllValidSchematronFiles()) if (!aRes.getPath().endsWith("/BIICORE-UBL-T01.sch") && !aRes.getPath().endsWith("/BIICORE-UBL-T10.sch") && !aRes.getPath().endsWith("/BIICORE-UBL-T14.sch") && !aRes.getPath().endsWith("/BIICORE-UBL-T15.sch") && !aRes.getPath().endsWith("/CellarBook.sch") && !aRes.getPath().endsWith("/pattern-example-with-includes.sch") && !aRes.getPath().endsWith("/pattern-example.sch") && !aRes.getPath().endsWith("/schematron-svrl.sch"))
        aValidSchematrons.add(aRes);
    s_aLogger.info("Starting");
    final double dTime1 = benchmarkTask(new ValidSchematronPure(aValidSchematrons));
    s_aLogger.info("Time pure: " + BigDecimal.valueOf(dTime1).toString() + " us");
    final double dTime2 = benchmarkTask(new ValidSchematronSCH(aValidSchematrons));
    s_aLogger.info("Time XSLT: " + BigDecimal.valueOf(dTime2).toString() + " us");
    s_aLogger.info("Time1 is " + BigDecimal.valueOf(dTime1 / dTime2 * 100).toString() + "% of time2");
}
Also used : IReadableResource(com.helger.commons.io.resource.IReadableResource) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList)

Example 4 with IReadableResource

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

the class PSXPathBoundSchemaTest method testBindAllInvalidSchematrons.

@Test
public void testBindAllInvalidSchematrons() {
    for (final IReadableResource aRes : SchematronTestHelper.getAllInvalidSchematronFiles()) {
        System.out.println(aRes);
        try {
            // Parse the schema
            final PSSchema aSchema = new PSReader(aRes).readSchema();
            final CollectingPSErrorHandler aCEH = new CollectingPSErrorHandler();
            PSXPathQueryBinding.getInstance().bind(aSchema, null, aCEH);
            // Either an ERROR was collected or an exception was thrown
            assertTrue(aCEH.getErrorList().getMostSevereErrorLevel().isGE(EErrorLevel.ERROR));
        } catch (final SchematronException ex) {
            System.out.println("  " + ex.getMessage());
        }
    }
}
Also used : SchematronException(com.helger.schematron.SchematronException) IReadableResource(com.helger.commons.io.resource.IReadableResource) PSReader(com.helger.schematron.pure.exchange.PSReader) PSSchema(com.helger.schematron.pure.model.PSSchema) CollectingPSErrorHandler(com.helger.schematron.pure.errorhandler.CollectingPSErrorHandler) Test(org.junit.Test)

Example 5 with IReadableResource

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

the class PSXPathBoundSchemaTest method testSchematronValidation.

@Test
public void testSchematronValidation() throws SAXException, SchematronException {
    for (int i = 0; i < SCH.length; ++i) {
        final IReadableResource aSchRes = new ClassPathResource("test-sch/" + SCH[i]);
        final IReadableResource aXmlRes = new ClassPathResource("test-xml/" + XML[i]);
        // Resolve all includes
        final IMicroDocument aDoc = SchematronHelper.getWithResolvedSchematronIncludes(aSchRes);
        assertNotNull(aDoc);
        // Read to domain object
        final PSReader aReader = new PSReader(aSchRes);
        final PSSchema aSchema = aReader.readSchemaFromXML(aDoc.getDocumentElement());
        assertNotNull(aSchema);
        // Create a compiled schema
        final String sPhaseID = null;
        final IPSErrorHandler aErrorHandler = null;
        final IPSBoundSchema aBoundSchema = PSXPathQueryBinding.getInstance().bind(aSchema, sPhaseID, aErrorHandler);
        // Validate completely
        final SchematronOutputType aSVRL = aBoundSchema.validateComplete(DOMReader.readXMLDOM(aXmlRes), aXmlRes.getAsURL().toExternalForm());
        assertNotNull(aSVRL);
        if (false)
            System.out.println(new SVRLMarshaller().getAsString(aSVRL));
    }
}
Also used : IPSErrorHandler(com.helger.schematron.pure.errorhandler.IPSErrorHandler) SchematronOutputType(org.oclc.purl.dsdl.svrl.SchematronOutputType) IPSBoundSchema(com.helger.schematron.pure.bound.IPSBoundSchema) IReadableResource(com.helger.commons.io.resource.IReadableResource) SVRLMarshaller(com.helger.schematron.svrl.SVRLMarshaller) IMicroDocument(com.helger.xml.microdom.IMicroDocument) PSReader(com.helger.schematron.pure.exchange.PSReader) PSSchema(com.helger.schematron.pure.model.PSSchema) ClassPathResource(com.helger.commons.io.resource.ClassPathResource) Test(org.junit.Test)

Aggregations

IReadableResource (com.helger.commons.io.resource.IReadableResource)37 Test (org.junit.Test)25 ClassPathResource (com.helger.commons.io.resource.ClassPathResource)18 CascadingStyleSheet (com.helger.css.decl.CascadingStyleSheet)12 LoggingCSSParseErrorHandler (com.helger.css.reader.errorhandler.LoggingCSSParseErrorHandler)12 SchematronOutputType (org.oclc.purl.dsdl.svrl.SchematronOutputType)11 SchematronResourcePure (com.helger.schematron.pure.SchematronResourcePure)9 FileSystemResource (com.helger.commons.io.resource.FileSystemResource)8 CSSWriter (com.helger.css.writer.CSSWriter)8 PSSchema (com.helger.schematron.pure.model.PSSchema)7 SVRLMarshaller (com.helger.schematron.svrl.SVRLMarshaller)7 CSSReaderSettings (com.helger.css.reader.CSSReaderSettings)6 AbstractSchematronResource (com.helger.schematron.AbstractSchematronResource)6 IMicroDocument (com.helger.xml.microdom.IMicroDocument)6 CollectingPSErrorHandler (com.helger.schematron.pure.errorhandler.CollectingPSErrorHandler)5 PSReader (com.helger.schematron.pure.exchange.PSReader)5 IPSErrorHandler (com.helger.schematron.pure.errorhandler.IPSErrorHandler)4 IMicroElement (com.helger.xml.microdom.IMicroElement)3 File (java.io.File)3 Nonnull (javax.annotation.Nonnull)3