Java Code Examples for com.helger.xml.serialize.read.DOMReader#readXMLDOM()

The following examples show how to use com.helger.xml.serialize.read.DOMReader#readXMLDOM() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XMLWriterTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testNumericReferencesXML10 () throws TransformerException
{
  for (int i = Character.MIN_VALUE; i <= Character.MAX_VALUE; ++i)
    if (!XMLCharHelper.isInvalidXMLTextChar (EXMLSerializeVersion.XML_10, (char) i))
    {
      final String sText = "abc" + (char) i + "def";
      final Document aDoc = XMLFactory.newDocument (EXMLVersion.XML_10);
      final Element eRoot = (Element) aDoc.appendChild (aDoc.createElement ("root"));
      eRoot.appendChild (aDoc.createTextNode (sText));

      // Use regular transformer
      final Transformer aTransformer = XMLTransformerFactory.newTransformer ();
      aTransformer.setOutputProperty (OutputKeys.ENCODING, StandardCharsets.UTF_8.name ());
      aTransformer.setOutputProperty (OutputKeys.INDENT, "yes");
      aTransformer.setOutputProperty (OutputKeys.VERSION, EXMLVersion.XML_10.getVersion ());
      final StringStreamResult aRes = new StringStreamResult ();
      aTransformer.transform (new DOMSource (aDoc), aRes);

      final String sXML = aRes.getAsString ();
      final Document aDoc2 = DOMReader.readXMLDOM (sXML);
      assertNotNull (aDoc2);
    }
}
 
Example 2
Source File: XMLWriterTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testNumericReferencesXML11 () throws TransformerException
{
  for (int i = Character.MIN_VALUE; i <= Character.MAX_VALUE; ++i)
    if (!XMLCharHelper.isInvalidXMLTextChar (EXMLSerializeVersion.XML_11, (char) i))
    {
      final String sText = "abc" + (char) i + "def";
      final Document aDoc = XMLFactory.newDocument (EXMLVersion.XML_11);
      final Element eRoot = (Element) aDoc.appendChild (aDoc.createElement ("root"));
      eRoot.appendChild (aDoc.createTextNode (sText));

      final Transformer aTransformer = XMLTransformerFactory.newTransformer ();
      aTransformer.setOutputProperty (OutputKeys.ENCODING, StandardCharsets.UTF_8.name ());
      aTransformer.setOutputProperty (OutputKeys.INDENT, "no");
      aTransformer.setOutputProperty (OutputKeys.VERSION, EXMLVersion.XML_11.getVersion ());
      final StringStreamResult aRes = new StringStreamResult ();
      aTransformer.transform (new DOMSource (aDoc), aRes);

      final String sXML = aRes.getAsString ();
      final Document aDoc2 = DOMReader.readXMLDOM (sXML);
      assertNotNull (aDoc2);
    }
}
 
Example 3
Source File: XMLWriterTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
private static void _testC14 (final String sSrc, final String sDst)
{
  final Document aDoc = DOMReader.readXMLDOM (sSrc, new DOMReaderSettings ().setEntityResolver ( (x, y) -> {
    return "world.txt".equals (new File (y).getName ()) ? new StringSAXInputSource ("world")
                                                        : new StringSAXInputSource ("");
  }));
  assertNotNull (aDoc);

  final MapBasedNamespaceContext aCtx = new MapBasedNamespaceContext ();
  aCtx.addMapping ("a", "http://www.w3.org");
  aCtx.addMapping ("b", "http://www.ietf.org");
  final String sC14 = XMLWriter.getNodeAsString (aDoc,
                                                 XMLWriterSettings.createForCanonicalization ()
                                                                  .setIndentationString ("   ")
                                                                  .setNamespaceContext (aCtx)
                                                                  .setSerializeComments (EXMLSerializeComments.IGNORE));
  assertEquals (sDst, sC14);
}
 
Example 4
Source File: MicroHelperTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testConvertToMicroElementWithNS ()
{
  final String sNS = "<root xmlns='blafoo'><ns2:element xmlns:ns2='ns2:uri' ns2:attr='value'>content</ns2:element></root>";
  final Document aDoc = DOMReader.readXMLDOM (sNS);
  assertNotNull (aDoc);
  final IMicroDocument aMicroDoc = (IMicroDocument) MicroHelper.convertToMicroNode (aDoc);
  assertNotNull (aMicroDoc);
  final IMicroElement eRoot = aMicroDoc.getDocumentElement ();
  assertNotNull (eRoot);
  assertEquals ("blafoo", eRoot.getNamespaceURI ());
  assertEquals ("root", eRoot.getLocalName ());
  assertEquals ("root", eRoot.getTagName ());
  assertEquals (0, eRoot.getAttributeCount ());
  assertEquals (1, eRoot.getChildElementCount ());
  final IMicroElement eElement = eRoot.getFirstChildElement ();
  assertEquals ("ns2:uri", eElement.getNamespaceURI ());
  assertEquals ("element", eElement.getLocalName ());
  assertEquals ("element", eElement.getTagName ());
}
 
Example 5
Source File: SchematronProviderXSLTPrebuild.java    From ph-schematron with Apache License 2.0 6 votes vote down vote up
public SchematronProviderXSLTPrebuild (@Nullable final IReadableResource aXSLTResource,
                                       @Nullable final ErrorListener aCustomErrorListener,
                                       @Nullable final URIResolver aCustomURIResolver)
{
  try
  {
    // Read XSLT file as XML
    m_aSchematronXSLTDoc = DOMReader.readXMLDOM (aXSLTResource);

    // compile result of read file
    final TransformerFactory aTF = SchematronTransformerFactory.createTransformerFactorySaxonFirst (SchematronProviderXSLTPrebuild.class.getClassLoader (),
                                                                                                    aCustomErrorListener,
                                                                                                    new DefaultTransformURIResolver (aCustomURIResolver));
    m_aSchematronXSLTTemplates = aTF.newTemplates (TransformSourceFactory.create (m_aSchematronXSLTDoc));
  }
  catch (final Exception ex)
  {
    LOGGER.error ("XSLT read/compilation error for " + aXSLTResource, ex);
  }
}
 
Example 6
Source File: DocumentationExamples.java    From ph-schematron with Apache License 2.0 6 votes vote down vote up
public static boolean validateXMLViaPureSchematron2 (@Nonnull final File aSchematronFile,
                                                     @Nonnull final File aXMLFile) throws Exception
{
  // Read the schematron from file
  final PSSchema aSchema = new PSReader (new FileSystemResource (aSchematronFile)).readSchema ();
  if (!aSchema.isValid (new DoNothingPSErrorHandler ()))
    throw new IllegalArgumentException ("Invalid Schematron!");
  // Resolve the query binding to use
  final IPSQueryBinding aQueryBinding = PSQueryBindingRegistry.getQueryBindingOfNameOrThrow (aSchema.getQueryBinding ());
  // Pre-process schema
  final PSPreprocessor aPreprocessor = new PSPreprocessor (aQueryBinding);
  aPreprocessor.setKeepTitles (true);
  final PSSchema aPreprocessedSchema = aPreprocessor.getAsPreprocessedSchema (aSchema);
  // Bind the pre-processed schema
  final IPSBoundSchema aBoundSchema = aQueryBinding.bind (aPreprocessedSchema);
  // Read the XML file
  final Document aXMLNode = DOMReader.readXMLDOM (aXMLFile);
  if (aXMLNode == null)
    return false;
  // Perform the validation
  return aBoundSchema.validatePartially (aXMLNode, FileHelper.getAsURLString (aXMLFile)).isValid ();
}
 
Example 7
Source File: Issue16Test.java    From ph-schematron with Apache License 2.0 6 votes vote down vote up
public static boolean validateXMLViaPureSchematron2 (@Nonnull final File aSchematronFile,
                                                     @Nonnull final File aXMLFile) throws Exception
{
  // Read the schematron from file
  final PSSchema aSchema = new PSReader (new FileSystemResource (aSchematronFile)).readSchema ();
  if (!aSchema.isValid (new DoNothingPSErrorHandler ()))
    throw new IllegalArgumentException ("Invalid Schematron!");
  // Resolve the query binding to use
  final IPSQueryBinding aQueryBinding = PSQueryBindingRegistry.getQueryBindingOfNameOrThrow (aSchema.getQueryBinding ());
  // Pre-process schema
  final PSPreprocessor aPreprocessor = new PSPreprocessor (aQueryBinding);
  aPreprocessor.setKeepTitles (true);
  final PSSchema aPreprocessedSchema = aPreprocessor.getAsPreprocessedSchema (aSchema);
  // Bind the pre-processed schema
  final IPSBoundSchema aBoundSchema = aQueryBinding.bind (aPreprocessedSchema);
  // Read the XML file
  final Document aXMLNode = DOMReader.readXMLDOM (aXMLFile);
  if (aXMLNode == null)
    return false;
  // Perform the validation
  return aBoundSchema.validatePartially (aXMLNode, FileHelper.getAsURLString (aXMLFile)).isValid ();
}
 
Example 8
Source File: UBL23InvoiceHelperTest.java    From ph-ubl with Apache License 2.0 5 votes vote down vote up
@Test
public void testComvertBackAndForth ()
{
  for (final String sFilename : MockUBL23TestDocuments.getUBL23TestDocuments (EUBL23DocumentType.INVOICE))
  {
    LOGGER.info (sFilename);

    // Read
    final Document aDoc = DOMReader.readXMLDOM (new ClassPathResource (sFilename),
                                                new DOMReaderSettings ().setSchema (EUBL23DocumentType.INVOICE.getSchema ()));
    assertNotNull (sFilename, aDoc);
    final InvoiceType aUBLObject = UBL23Reader.invoice ().read (aDoc);
    assertNotNull (sFilename, aUBLObject);

    // Convert Invoice to CreditNote
    final CreditNoteType aCreditNote = new CreditNoteType ();
    UBL23InvoiceHelper.cloneInvoiceToCreditNote (aUBLObject, aCreditNote);

    // Validate CreditNote
    IErrorList aErrors = UBL23Validator.creditNote ().validate (aCreditNote);
    assertNotNull (sFilename, aErrors);
    assertFalse (sFilename, aErrors.containsAtLeastOneError ());

    // Convert CreditNote back to Invoice
    final InvoiceType aInvoice2 = new InvoiceType ();
    UBL23CreditNoteHelper.cloneCreditNoteToInvoice (aCreditNote, aInvoice2);

    // Validate Invoice again
    aErrors = UBL23Validator.invoice ().validate (aInvoice2);
    assertNotNull (sFilename, aErrors);
    assertFalse (sFilename, aErrors.containsAtLeastOneError ());
  }
}
 
Example 9
Source File: UBL20InvoiceHelperTest.java    From ph-ubl with Apache License 2.0 5 votes vote down vote up
@Test
public void testComvertBackAndForth ()
{
  for (final String sFilename : MockUBL20TestDocuments.getUBL20TestDocuments (EUBL20DocumentType.INVOICE))
  {
    LOGGER.info (sFilename);

    // Read
    final Document aDoc = DOMReader.readXMLDOM (new ClassPathResource (sFilename),
                                                new DOMReaderSettings ().setSchema (EUBL20DocumentType.INVOICE.getSchema ()));
    assertNotNull (sFilename, aDoc);
    final InvoiceType aUBLObject = UBL20Reader.invoice ().read (aDoc);
    assertNotNull (sFilename, aUBLObject);

    // Convert Invoice to CreditNote
    final CreditNoteType aCreditNote = new CreditNoteType ();
    UBL20InvoiceHelper.cloneInvoiceToCreditNote (aUBLObject, aCreditNote);

    // Validate CreditNote
    IErrorList aErrors = UBL20Validator.creditNote ().validate (aCreditNote);
    assertNotNull (sFilename, aErrors);
    assertFalse (sFilename, aErrors.containsAtLeastOneError ());

    // Convert CreditNote back to Invoice
    final InvoiceType aInvoice2 = new InvoiceType ();
    UBL20CreditNoteHelper.cloneCreditNoteToInvoice (aCreditNote, aInvoice2);

    // Validate Invoice again
    aErrors = UBL20Validator.invoice ().validate (aInvoice2);
    assertNotNull (sFilename, aErrors);
    assertFalse (sFilename, aErrors.containsAtLeastOneError ());
  }
}
 
Example 10
Source File: UBL21InvoiceHelperTest.java    From ph-ubl with Apache License 2.0 5 votes vote down vote up
@Test
public void testComvertBackAndForth ()
{
  for (final String sFilename : MockUBL21TestDocuments.getUBL21TestDocuments (EUBL21DocumentType.INVOICE))
  {
    LOGGER.info (sFilename);

    // Read
    final Document aDoc = DOMReader.readXMLDOM (new ClassPathResource (sFilename),
                                                new DOMReaderSettings ().setSchema (EUBL21DocumentType.INVOICE.getSchema ()));
    assertNotNull (sFilename, aDoc);
    final InvoiceType aUBLObject = UBL21Reader.invoice ().read (aDoc);
    assertNotNull (sFilename, aUBLObject);

    // Convert Invoice to CreditNote
    final CreditNoteType aCreditNote = new CreditNoteType ();
    UBL21InvoiceHelper.cloneInvoiceToCreditNote (aUBLObject, aCreditNote);

    // Validate CreditNote
    IErrorList aErrors = UBL21Validator.creditNote ().validate (aCreditNote);
    assertNotNull (sFilename, aErrors);
    assertFalse (sFilename, aErrors.containsAtLeastOneError ());

    // Convert CreditNote back to Invoice
    final InvoiceType aInvoice2 = new InvoiceType ();
    UBL21CreditNoteHelper.cloneCreditNoteToInvoice (aCreditNote, aInvoice2);

    // Validate Invoice again
    aErrors = UBL21Validator.invoice ().validate (aInvoice2);
    assertNotNull (sFilename, aErrors);
    assertFalse (sFilename, aErrors.containsAtLeastOneError ());
  }
}
 
Example 11
Source File: UBL22InvoiceHelperTest.java    From ph-ubl with Apache License 2.0 5 votes vote down vote up
@Test
public void testComvertBackAndForth ()
{
  for (final String sFilename : MockUBL22TestDocuments.getUBL22TestDocuments (EUBL22DocumentType.INVOICE))
  {
    LOGGER.info (sFilename);

    // Read
    final Document aDoc = DOMReader.readXMLDOM (new ClassPathResource (sFilename),
                                                new DOMReaderSettings ().setSchema (EUBL22DocumentType.INVOICE.getSchema ()));
    assertNotNull (sFilename, aDoc);
    final InvoiceType aUBLObject = UBL22Reader.invoice ().read (aDoc);
    assertNotNull (sFilename, aUBLObject);

    // Convert Invoice to CreditNote
    final CreditNoteType aCreditNote = new CreditNoteType ();
    UBL22InvoiceHelper.cloneInvoiceToCreditNote (aUBLObject, aCreditNote);

    // Validate CreditNote
    IErrorList aErrors = UBL22Validator.creditNote ().validate (aCreditNote);
    assertNotNull (sFilename, aErrors);
    assertFalse (sFilename, aErrors.containsAtLeastOneError ());

    // Convert CreditNote back to Invoice
    final InvoiceType aInvoice2 = new InvoiceType ();
    UBL22CreditNoteHelper.cloneCreditNoteToInvoice (aCreditNote, aInvoice2);

    // Validate Invoice again
    aErrors = UBL22Validator.invoice ().validate (aInvoice2);
    assertNotNull (sFilename, aErrors);
    assertFalse (sFilename, aErrors.containsAtLeastOneError ());
  }
}
 
Example 12
Source File: SchematronResourcePureTest.java    From ph-schematron with Apache License 2.0 5 votes vote down vote up
@Test
public void testFunctXAreDistinctValuesWithXSD () throws Exception
{
  final String sTest = "<?xml version='1.0' encoding='iso-8859-1'?>\n" +
                       "<schema xmlns='http://purl.oclc.org/dsdl/schematron'>\n" +
                       "  <ns prefix=\"xs\" uri=\"http://www.w3.org/2001/XMLSchema\"/>\n" +
                       "  <ns prefix='fn' uri='http://www.w3.org/2005/xpath-functions' />\n" +
                       "  <ns prefix='functx' uri='http://www.functx.com' />\n" +
                       "  <pattern name='toto'>\n" +
                       "    <title>A very simple pattern with a title</title>\n" +
                       "    <rule context='chapter'>\n" +
                       "      <assert test='fn:count(fn:distinct-values(para)) = fn:count(para)'>Should have distinct values</assert>\n" +
                       "      </rule>\n" +
                       "  </pattern>\n" +
                       "</schema>";

  final MapBasedXPathFunctionResolver aFunctionResolver = new XQueryAsXPathFunctionConverter ().loadXQuery (ClassPathResource.getInputStream ("xquery/functx-1.0-nodoc-2007-01.xq"));

  final Schema aSchema = XMLSchemaCache.getInstance ()
                                       .getSchema (new ClassPathResource ("issues/20141124/chapter.xsd"));
  final Document aTestDoc = DOMReader.readXMLDOM ("<?xml version='1.0'?>" +
                                                  "<chapter>" +
                                                  " <title />" +
                                                  " <para>09</para>" +
                                                  " <para>9</para>" +
                                                  "</chapter>",
                                                  new DOMReaderSettings ().setSchema (aSchema));

  final IXPathConfig aXPathConfig = new XPathConfigBuilder ().setXPathFunctionResolver (aFunctionResolver).build ();
  final SchematronOutputType aOT = SchematronResourcePure.fromByteArray (sTest.getBytes (StandardCharsets.UTF_8))
                                                         .setXPathConfig (aXPathConfig)
                                                         .applySchematronValidationToSVRL (aTestDoc, null);
  assertNotNull (aOT);
  if (SVRLHelper.getAllFailedAssertions (aOT).isNotEmpty ())
  {
    LOGGER.info (SVRLHelper.getAllFailedAssertions (aOT).get (0).getText ());
  }
  assertTrue (SVRLHelper.getAllFailedAssertions (aOT).isEmpty ());
}
 
Example 13
Source File: AbstractSchematronResource.java    From ph-schematron with Apache License 2.0 5 votes vote down vote up
@Nullable
protected NodeAndBaseURI getAsNode (@Nonnull final IHasInputStream aXMLResource) throws Exception
{
  final StreamSource aStreamSrc = TransformSourceFactory.create (aXMLResource);
  InputStream aIS = null;
  try
  {
    aIS = aStreamSrc.getInputStream ();
  }
  catch (final IllegalStateException ex)
  {
    // Fall through
    // Happens e.g. for ResourceStreamSource with non-existing resources
  }
  if (aIS == null)
  {
    // Resource not found
    LOGGER.warn ("XML resource " + aXMLResource + " does not exist!");
    return null;
  }
  final Document aDoc = DOMReader.readXMLDOM (aIS, internalCreateDOMReaderSettings ());
  if (aDoc == null)
    throw new IllegalArgumentException ("Failed to read resource " + aXMLResource + " as XML");

  LOGGER.info ("Read XML resource " + aXMLResource);
  return new NodeAndBaseURI (aDoc, aStreamSrc.getSystemId ());
}
 
Example 14
Source File: SchematronResourcePureTest.java    From ph-schematron with Apache License 2.0 4 votes vote down vote up
@Test
public void testResolveFunctXAreDistinctValuesQueryFunctions () throws Exception
{
  final String sTest = "<?xml version='1.0' encoding='iso-8859-1'?>\n" +
                       "<iso:schema xmlns='http://purl.oclc.org/dsdl/schematron' \n" +
                       "         xmlns:iso='http://purl.oclc.org/dsdl/schematron' \n" +
                       "         xmlns:sch='http://www.ascc.net/xml/schematron'\n" +
                       "         queryBinding='xslt2'\n" +
                       "         schemaVersion='ISO19757-3'>\n" +
                       "  <iso:title>Test ISO schematron file. Introduction mode</iso:title>\n" +
                       "  <iso:ns prefix='dp' uri='http://www.dpawson.co.uk/ns#' />\n" +
                       "  <iso:ns prefix='fn' uri='http://www.w3.org/2005/xpath-functions' />\n" +
                       "  <iso:ns prefix='functx' uri='http://www.functx.com' />\n" +
                       "    <iso:pattern >\n" +
                       "    <iso:title>A very simple pattern with a title</iso:title>\n" +
                       "    <iso:rule context='chapter'>\n" +
                       "      <iso:assert test='functx:are-distinct-values(para)'>Should have distinct values</iso:assert>\n" +
                       "      </iso:rule>\n" +
                       "  </iso:pattern>\n" +
                       "</iso:schema>";

  final MapBasedXPathFunctionResolver aFunctionResolver = new XQueryAsXPathFunctionConverter ().loadXQuery (ClassPathResource.getInputStream ("xquery/functx-1.0-nodoc-2007-01.xq"));

  // Test with variable and function resolver
  final Document aTestDoc = DOMReader.readXMLDOM ("<?xml version='1.0'?>" +
                                                  "<chapter>" +
                                                  "<title />" +
                                                  "<para>100</para>" +
                                                  "<para>200</para>" +
                                                  "</chapter>");
  final CollectingPSErrorHandler aErrorHandler = new CollectingPSErrorHandler (new LoggingPSErrorHandler ());
  final IXPathConfig aXPathConfig = new XPathConfigBuilder ().setXPathFunctionResolver (aFunctionResolver).build ();
  final SchematronOutputType aOT = SchematronResourcePure.fromByteArray (sTest.getBytes (StandardCharsets.UTF_8))
                                                         .setXPathConfig (aXPathConfig)
                                                         .setErrorHandler (aErrorHandler)
                                                         .applySchematronValidationToSVRL (aTestDoc, null);
  assertNotNull (aOT);
  // XXX fails :(
  if (false)
    assertTrue (aErrorHandler.getAllErrors ().toString (), aErrorHandler.isEmpty ());
  assertEquals (0, SVRLHelper.getAllFailedAssertions (aOT).size ());
}
 
Example 15
Source File: SchematronResourcePureTest.java    From ph-schematron with Apache License 2.0 4 votes vote down vote up
@Test
public void testResolveXQueryFunctions () throws Exception
{
  final String sTest = "<?xml version='1.0' encoding='iso-8859-1'?>\n" +
                       "<iso:schema xmlns='http://purl.oclc.org/dsdl/schematron' \n" +
                       "         xmlns:iso='http://purl.oclc.org/dsdl/schematron' \n" +
                       "         xmlns:sch='http://www.ascc.net/xml/schematron'\n" +
                       "         queryBinding='xslt2'\n" +
                       "         schemaVersion='ISO19757-3'>\n" +
                       "  <iso:title>Test ISO schematron file. Introduction mode</iso:title>\n" +
                       "  <iso:ns prefix='dp' uri='http://www.dpawson.co.uk/ns#' />\n" +
                       "  <iso:ns prefix='functx' uri='http://www.functx.com' />\n" +
                       "  <iso:pattern >\n" +
                       "    <iso:title>A very simple pattern with a title</iso:title>\n" +
                       "    <iso:rule context='chapter'>\n" +
                       "      <iso:assert test='title'>Chapter should have a title</iso:assert>\n" +
                       "      <iso:report test='count(para) = 2'>\n"
                       // Custom function
                       +
                       "      Node kind: <iso:value-of select='functx:node-kind(para)'/> - end</iso:report>\n" +
                       "    </iso:rule>\n" +
                       "  </iso:pattern>\n" +
                       "\n" +
                       "</iso:schema>";

  final MapBasedXPathFunctionResolver aFunctionResolver = new XQueryAsXPathFunctionConverter ().loadXQuery (ClassPathResource.getInputStream ("xquery/functx-1.0-nodoc-2007-01.xq"));

  // Test with variable and function resolver
  final Document aTestDoc = DOMReader.readXMLDOM ("<?xml version='1.0'?>" +
                                                  "<chapter>" +
                                                  "<title />" +
                                                  "<para>First para</para>" +
                                                  "<para>Second para</para>" +
                                                  "</chapter>");
  final IXPathConfig aXPathConfig = new XPathConfigBuilder ().setXPathFunctionResolver (aFunctionResolver).build ();
  final SchematronOutputType aOT = SchematronResourcePure.fromByteArray (sTest.getBytes (StandardCharsets.UTF_8))
                                                         .setXPathConfig (aXPathConfig)
                                                         .applySchematronValidationToSVRL (aTestDoc, null);
  assertNotNull (aOT);
  assertEquals (0, SVRLHelper.getAllFailedAssertions (aOT).size ());
  assertEquals (1, SVRLHelper.getAllSuccessfulReports (aOT).size ());
  // Note: the text contains all whitespaces!
  assertEquals ("\n      Node kind: element - end".trim (),
                SVRLHelper.getAllSuccessfulReports (aOT).get (0).getText ());
}
 
Example 16
Source File: SchematronResourcePureTest.java    From ph-schematron with Apache License 2.0 4 votes vote down vote up
@Test
public void testResolveFunctions () throws SchematronException, XPathFactoryConfigurationException
{
  final String sTest = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n" +
                       "<iso:schema xmlns=\"http://purl.oclc.org/dsdl/schematron\" \n" +
                       "         xmlns:iso=\"http://purl.oclc.org/dsdl/schematron\" \n" +
                       "         xmlns:sch=\"http://www.ascc.net/xml/schematron\"\n" +
                       "         queryBinding='xslt2'\n" +
                       "         schemaVersion=\"ISO19757-3\">\n" +
                       "  <iso:title>Test ISO schematron file. Introduction mode</iso:title>\n" +
                       "  <iso:ns prefix=\"dp\" uri=\"http://www.dpawson.co.uk/ns#\" />\n" +
                       "  <iso:ns prefix=\"java\" uri=\"http://helger.com/schematron/test\" />\n" +
                       "  <iso:pattern >\n" +
                       "    <iso:title>A very simple pattern with a title</iso:title>\n" +
                       "    <iso:rule context=\"chapter\">\n" +
                       "      <iso:assert test=\"title\">Chapter should have a title</iso:assert>\n" +
                       "      <iso:report test=\"count(para) = 2\">\n"
                       // Custom function
                       +
                       "      Node details: <iso:value-of select=\"java:get-nodelist-details(para)\"/> - end</iso:report>\n" +
                       "    </iso:rule>\n" +
                       "  </iso:pattern>\n" +
                       "\n" +
                       "</iso:schema>";

  // Test with variable and function resolver
  final MapBasedXPathFunctionResolver aFunctionResolver = new MapBasedXPathFunctionResolver ();
  aFunctionResolver.addUniqueFunction ("http://helger.com/schematron/test", "get-nodelist-details", 1, args -> {
    // We expect exactly one argument
    assertEquals (1, args.size ());
    // The type of the first argument
    // itself is also a list
    final List <?> aFirstArg = (List <?>) args.get (0);
    // Ensure that the first argument
    // only contains Nodes
    final StringBuilder ret = new StringBuilder ();
    boolean bFirst = true;
    for (final Object aFirstArgItem : aFirstArg)
    {
      assertTrue (aFirstArgItem instanceof Node);
      final Node aNode = (Node) aFirstArgItem;

      if (bFirst)
        bFirst = false;
      else
        ret.append (", ");

      ret.append (aNode.getNodeName ()).append ("[").append (aNode.getTextContent ()).append ("]");
    }

    return ret;
  });

  final Document aTestDoc = DOMReader.readXMLDOM ("<?xml version='1.0'?>" +
                                                  "<chapter>" +
                                                  "<title />" +
                                                  "<para>First para</para>" +
                                                  "<para>Second para</para>" +
                                                  "</chapter>");
  final IXPathConfig aXPathConfig = new XPathConfigBuilder ().setXPathFunctionResolver (aFunctionResolver).build ();
  final SchematronOutputType aOT = SchematronResourcePure.fromByteArray (sTest.getBytes (StandardCharsets.UTF_8))
                                                         .setXPathConfig (aXPathConfig)
                                                         .applySchematronValidationToSVRL (aTestDoc, null);
  assertNotNull (aOT);
  assertEquals (0, SVRLHelper.getAllFailedAssertions (aOT).size ());
  assertEquals (1, SVRLHelper.getAllSuccessfulReports (aOT).size ());
  // Note: the text contains all whitespaces!
  assertEquals ("\n      Node details: para[First para], para[Second para] - end".trim (),
                SVRLHelper.getAllSuccessfulReports (aOT).get (0).getText ());
}
 
Example 17
Source File: SchematronResourcePureTest.java    From ph-schematron with Apache License 2.0 4 votes vote down vote up
@Test
public void testResolveVariables () throws SchematronException, XPathFactoryConfigurationException
{
  final String sTest = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n" +
                       "<iso:schema xmlns=\"http://purl.oclc.org/dsdl/schematron\" \n" +
                       "         xmlns:iso=\"http://purl.oclc.org/dsdl/schematron\" \n" +
                       "         xmlns:sch=\"http://www.ascc.net/xml/schematron\"\n" +
                       "         queryBinding='xslt2'\n" +
                       "         schemaVersion=\"ISO19757-3\">\n" +
                       "  <iso:title>Test ISO schematron file. Introduction mode</iso:title>\n" +
                       "  <iso:ns prefix=\"dp\" uri=\"http://www.dpawson.co.uk/ns#\" />\n" +
                       "  <iso:ns prefix=\"java\" uri=\"http://helger.com/schematron/test\" />\n" +
                       "  <iso:pattern >\n" +
                       "    <iso:title>A very simple pattern with a title</iso:title>\n" +
                       "    <iso:rule context=\"chapter\">\n"
                       // Custom variable
                       +
                       "      <iso:assert test=\"$title-element\">Chapter should have a title</iso:assert>\n"
                       // Custom function
                       +
                       "      <iso:report test=\"java:my-count(para) = 2\">\n"
                       // Custom function
                       +
                       "      <iso:value-of select=\"java:my-count(para)\"/> paragraphs found</iso:report>\n" +
                       "    </iso:rule>\n" +
                       "  </iso:pattern>\n" +
                       "\n" +
                       "</iso:schema>";

  // Test without variable and function resolver
  // -> an error is expected, but we don't need to log it
  assertFalse (SchematronResourcePure.fromString (sTest, StandardCharsets.UTF_8)
                                     .setErrorHandler (new DoNothingPSErrorHandler ())
                                     .isValidSchematron ());

  // Test with variable and function resolver
  final MapBasedXPathVariableResolver aVarResolver = new MapBasedXPathVariableResolver ();
  aVarResolver.addUniqueVariable ("title-element", "title");

  final MapBasedXPathFunctionResolver aFunctionResolver = new MapBasedXPathFunctionResolver ();
  aFunctionResolver.addUniqueFunction ("http://helger.com/schematron/test", "my-count", 1, args -> {
    final List <?> aArg = (List <?>) args.get (0);
    return Integer.valueOf (aArg.size ());
  });
  final IXPathConfig aXPathConfig = new XPathConfigBuilder ().setXPathVariableResolver (aVarResolver)
                                                             .setXPathFunctionResolver (aFunctionResolver)
                                                             .build ();

  final Document aTestDoc = DOMReader.readXMLDOM ("<?xml version='1.0'?><chapter><title /><para>First para</para><para>Second para</para></chapter>");
  final SchematronOutputType aOT = SchematronResourcePure.fromString (sTest, StandardCharsets.UTF_8)
                                                         .setXPathConfig (aXPathConfig)
                                                         .applySchematronValidationToSVRL (aTestDoc, null);
  assertNotNull (aOT);
  assertEquals (0, SVRLHelper.getAllFailedAssertions (aOT).size ());
  assertEquals (1, SVRLHelper.getAllSuccessfulReports (aOT).size ());
  // Note: the text contains all whitespaces!
  assertEquals ("\n      2 paragraphs found".trim (), SVRLHelper.getAllSuccessfulReports (aOT).get (0).getText ());
}
 
Example 18
Source File: XMLTransformerFactoryTest.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Test
public void testSpecialChars () throws Exception
{
  final EXMLVersion eXMLVersion = EXMLVersion.XML_10;
  final EXMLSerializeVersion eXMLSerializeVersion = EXMLSerializeVersion.getFromXMLVersionOrThrow (eXMLVersion);
  final StringBuilder aAttrVal = new StringBuilder ();
  final StringBuilder aText = new StringBuilder ();
  for (char i = 0; i < 256; ++i)
  {
    if (!XMLCharHelper.isInvalidXMLAttributeValueChar (eXMLSerializeVersion, i))
      aAttrVal.append (i);
    if (!XMLCharHelper.isInvalidXMLTextChar (eXMLSerializeVersion, i))
      aText.append (i);
  }

  final Document aDoc = XMLFactory.newDocument (eXMLVersion);
  final Element eRoot = (Element) aDoc.appendChild (aDoc.createElement ("root"));
  eRoot.setAttribute ("test", aAttrVal.toString ());

  final Element e1 = (Element) eRoot.appendChild (aDoc.createElement ("a"));
  e1.appendChild (aDoc.createTextNode (aText.toString ()));

  final Element e2 = (Element) eRoot.appendChild (aDoc.createElement ("b"));
  e2.appendChild (aDoc.createCDATASection ("aaaaaaaaaaa]]>bbbbbbbbbbb]]>ccccccccc"));

  final Element e3 = (Element) eRoot.appendChild (aDoc.createElement ("c"));
  e3.appendChild (aDoc.createCDATASection ("]]>"));

  if (false)
    e3.appendChild (aDoc.createComment ("<!--"));
  e3.appendChild (aDoc.createTextNode ("abc"));
  if (false)
    e3.appendChild (aDoc.createComment ("-->"));

  final NonBlockingStringWriter aSW = new NonBlockingStringWriter ();
  XMLTransformerFactory.newTransformer ().transform (new DOMSource (aDoc), new StreamResult (aSW));
  final String sTransform = aSW.getAsString ();

  final Document aDoc2 = DOMReader.readXMLDOM (sTransform);
  final Node e3a = aDoc2.getDocumentElement ().getChildNodes ().item (2);
  aSW.reset ();
  XMLTransformerFactory.newTransformer ().transform (new DOMSource (e3a), new StreamResult (aSW));

  final String sXML = XMLWriter.getNodeAsString (aDoc,
                                                 new XMLWriterSettings ().setIncorrectCharacterHandling (EXMLIncorrectCharacterHandling.WRITE_TO_FILE_NO_LOG)
                                                                         .setIndent (EXMLSerializeIndent.NONE));
  assertNotNull (sXML);

  assertNotNull ("Failed to read: " + sXML, DOMReader.readXMLDOM (sXML));
}