Search in sources :

Example 1 with SCHTransformerCustomizer

use of com.helger.schematron.xslt.SCHTransformerCustomizer 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)

Aggregations

FileSystemResource (com.helger.commons.io.resource.FileSystemResource)1 IReadableResource (com.helger.commons.io.resource.IReadableResource)1 ISchematronXSLTBasedProvider (com.helger.schematron.xslt.ISchematronXSLTBasedProvider)1 SCHTransformerCustomizer (com.helger.schematron.xslt.SCHTransformerCustomizer)1 MapBasedNamespaceContext (com.helger.xml.namespace.MapBasedNamespaceContext)1 XMLWriterSettings (com.helger.xml.serialize.write.XMLWriterSettings)1 AbstractTransformErrorListener (com.helger.xml.transform.AbstractTransformErrorListener)1 File (java.io.File)1 OutputStream (java.io.OutputStream)1 ErrorListener (javax.xml.transform.ErrorListener)1 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)1 MojoFailureException (org.apache.maven.plugin.MojoFailureException)1 DirectoryScanner (org.codehaus.plexus.util.DirectoryScanner)1