Java Code Examples for com.helger.xml.namespace.MapBasedNamespaceContext#addMapping()

The following examples show how to use com.helger.xml.namespace.MapBasedNamespaceContext#addMapping() . 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
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 2
Source File: MicroWriterTest.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 IMicroDocument aDoc = MicroReader.readMicroXML (sSrc,
                                                        new SAXReaderSettings ().setEntityResolver ( (x,
                                                                                                      y) -> "world.txt".equals (y) ? 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 = MicroWriter.getNodeAsString (aDoc,
                                                   XMLWriterSettings.createForCanonicalization ()
                                                                    .setIndentationString ("   ")
                                                                    .setNamespaceContext (aCtx)
                                                                    .setSerializeComments (EXMLSerializeComments.IGNORE));
  assertEquals (sDst, sC14);
}
 
Example 3
Source File: PSWriterTest.java    From ph-schematron with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteWithNamespacePrefix () throws SchematronReadException
{
  final IReadableResource aRes = SchematronTestHelper.getAllValidSchematronFiles ().getFirst ();
  // Read existing Schematron
  final PSSchema aSchema = new PSReader (aRes).readSchema ();

  // Create the XML namespace context
  final MapBasedNamespaceContext aNSCtx = PSWriterSettings.createNamespaceMapping (aSchema);
  aNSCtx.removeMapping (XMLConstants.DEFAULT_NS_PREFIX);
  aNSCtx.addMapping ("sch", CSchematron.NAMESPACE_SCHEMATRON);

  // Create the PSWriter settings
  final PSWriterSettings aPSWS = new PSWriterSettings ();
  aPSWS.setXMLWriterSettings (new XMLWriterSettings ().setNamespaceContext (aNSCtx)
                                                      .setPutNamespaceContextPrefixesInRoot (true));

  // Write the Schematron
  new PSWriter (aPSWS).writeToFile (aSchema, new File ("target/test-with-nsprefix.xml"));
}
 
Example 4
Source File: PSWriterSettings.java    From ph-schematron with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method to extract the namespace mapping from the provided
 * Schematron.
 *
 * @param aSchema
 *        The schema to extract the namespace context from. May not be
 *        <code>null</code>.
 * @return A non-<code>null</code> but maybe empty namespace context
 */
@Nonnull
@ReturnsMutableCopy
public static MapBasedNamespaceContext createNamespaceMapping (@Nonnull final PSSchema aSchema)
{
  final MapBasedNamespaceContext ret = new MapBasedNamespaceContext ();
  ret.addDefaultNamespaceURI (CSchematron.NAMESPACE_SCHEMATRON);
  ret.addMapping ("xsl", CSchematron.NAMESPACE_URI_XSL);
  for (final PSNS aItem : aSchema.getAllNSs ())
    ret.addMapping (aItem.getPrefix (), aItem.getUri ());
  return ret;
}
 
Example 5
Source File: PSSchema.java    From ph-schematron with Apache License 2.0 5 votes vote down vote up
/**
 * @return All contained namespaces as a single namespace context
 */
@Nonnull
@ReturnsMutableCopy
public MapBasedNamespaceContext getAsNamespaceContext ()
{
  final MapBasedNamespaceContext ret = new MapBasedNamespaceContext ();
  for (final PSNS aNS : m_aNSs)
    ret.addMapping (aNS.getPrefix (), aNS.getUri ());
  return ret;
}
 
Example 6
Source File: XMLWriterTest.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Test
public void testWithNamespaceContext ()
{
  final Document aDoc = XMLFactory.newDocument ();
  final Element eRoot = (Element) aDoc.appendChild (aDoc.createElementNS ("ns1url", "root"));
  eRoot.appendChild (aDoc.createElementNS ("ns2url", "child1"));
  eRoot.appendChild (aDoc.createElementNS ("ns2url", "child2"));

  final XMLWriterSettings aSettings = new XMLWriterSettings ().setCharset (StandardCharsets.ISO_8859_1)
                                                              .setIndent (EXMLSerializeIndent.NONE);
  String s = XMLWriter.getNodeAsString (aDoc, aSettings);
  assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>" +
                "<root xmlns=\"ns1url\">" +
                "<ns0:child1 xmlns:ns0=\"ns2url\" />" +
                "<ns0:child2 xmlns:ns0=\"ns2url\" />" +
                "</root>",
                s);

  final MapBasedNamespaceContext aCtx = new MapBasedNamespaceContext ();
  aCtx.addMapping ("a", "ns1url");
  aSettings.setNamespaceContext (aCtx);
  s = XMLWriter.getNodeAsString (aDoc, aSettings);
  assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>" +
                "<a:root xmlns:a=\"ns1url\">" +
                "<ns0:child1 xmlns:ns0=\"ns2url\" />" +
                "<ns0:child2 xmlns:ns0=\"ns2url\" />" +
                "</a:root>",
                s);

  aCtx.addMapping ("xy", "ns2url");
  s = XMLWriter.getNodeAsString (aDoc, aSettings);
  assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>" +
                "<a:root xmlns:a=\"ns1url\">" +
                "<xy:child1 xmlns:xy=\"ns2url\" />" +
                "<xy:child2 xmlns:xy=\"ns2url\" />" +
                "</a:root>",
                s);

  aSettings.setUseDoubleQuotesForAttributes (false);
  s = XMLWriter.getNodeAsString (aDoc, aSettings);
  assertEquals ("<?xml version='1.0' encoding='ISO-8859-1' standalone='no'?>" +
                "<a:root xmlns:a='ns1url'>" +
                "<xy:child1 xmlns:xy='ns2url' />" +
                "<xy:child2 xmlns:xy='ns2url' />" +
                "</a:root>",
                s);

  aSettings.setSpaceOnSelfClosedElement (false);
  s = XMLWriter.getNodeAsString (aDoc, aSettings);
  assertEquals ("<?xml version='1.0' encoding='ISO-8859-1' standalone='no'?>" +
                "<a:root xmlns:a='ns1url'>" +
                "<xy:child1 xmlns:xy='ns2url'/>" +
                "<xy:child2 xmlns:xy='ns2url'/>" +
                "</a:root>",
                s);

  aSettings.setPutNamespaceContextPrefixesInRoot (true);
  s = XMLWriter.getNodeAsString (aDoc, aSettings);
  assertEquals ("<?xml version='1.0' encoding='ISO-8859-1' standalone='no'?>" +
                "<a:root xmlns:a='ns1url' xmlns:xy='ns2url'>" +
                "<xy:child1/>" +
                "<xy:child2/>" +
                "</a:root>",
                s);

  eRoot.appendChild (aDoc.createElementNS ("ns3url", "zz"));
  s = XMLWriter.getNodeAsString (aDoc, aSettings);
  assertEquals ("<?xml version='1.0' encoding='ISO-8859-1' standalone='no'?>" +
                "<a:root xmlns:a='ns1url' xmlns:xy='ns2url'>" +
                "<xy:child1/>" +
                "<xy:child2/>" +
                "<ns0:zz xmlns:ns0='ns3url'/>" +
                "</a:root>",
                s);
}
 
Example 7
Source File: MicroWriterTest.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Test
public void testWithNamespaceContext ()
{
  final XMLWriterSettings aSettings = new XMLWriterSettings ().setIndent (EXMLSerializeIndent.NONE)
                                                              .setCharset (StandardCharsets.ISO_8859_1);
  final IMicroDocument aDoc = new MicroDocument ();
  final IMicroElement eRoot = aDoc.appendElement ("ns1url", "root");
  eRoot.appendElement ("ns2url", "child1");
  eRoot.appendElement ("ns2url", "child2").setAttribute ("attr1", "a");
  eRoot.appendElement ("ns3url", "child3").setAttribute ("ns3url", "attr1", "a");
  eRoot.appendElement ("ns3url", "child4").setAttribute ("ns4url", "attr1", "a");

  String s = MicroWriter.getNodeAsString (aDoc, aSettings);
  assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" +
                "<root xmlns=\"ns1url\">" +
                "<ns0:child1 xmlns:ns0=\"ns2url\" />" +
                "<ns0:child2 xmlns:ns0=\"ns2url\" attr1=\"a\" />" +
                "<ns0:child3 xmlns:ns0=\"ns3url\" ns0:attr1=\"a\" />" +
                "<ns0:child4 xmlns:ns0=\"ns3url\" xmlns:ns1=\"ns4url\" ns1:attr1=\"a\" />" +
                "</root>",
                s);

  final MapBasedNamespaceContext aCtx = new MapBasedNamespaceContext ();
  aCtx.addMapping ("a", "ns1url");
  aSettings.setNamespaceContext (aCtx);
  s = MicroWriter.getNodeAsString (aDoc, aSettings);
  assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" +
                "<a:root xmlns:a=\"ns1url\">" +
                "<ns0:child1 xmlns:ns0=\"ns2url\" />" +
                "<ns0:child2 xmlns:ns0=\"ns2url\" attr1=\"a\" />" +
                "<ns0:child3 xmlns:ns0=\"ns3url\" ns0:attr1=\"a\" />" +
                "<ns0:child4 xmlns:ns0=\"ns3url\" xmlns:ns1=\"ns4url\" ns1:attr1=\"a\" />" +
                "</a:root>",
                s);

  // Add mapping to namespace context
  aCtx.addMapping ("xy", "ns2url");
  s = MicroWriter.getNodeAsString (aDoc, aSettings);
  assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" +
                "<a:root xmlns:a=\"ns1url\">" +
                "<xy:child1 xmlns:xy=\"ns2url\" />" +
                "<xy:child2 xmlns:xy=\"ns2url\" attr1=\"a\" />" +
                "<ns0:child3 xmlns:ns0=\"ns3url\" ns0:attr1=\"a\" />" +
                "<ns0:child4 xmlns:ns0=\"ns3url\" xmlns:ns1=\"ns4url\" ns1:attr1=\"a\" />" +
                "</a:root>",
                s);

  // Put namespace context mappings in root
  aSettings.setPutNamespaceContextPrefixesInRoot (true);
  s = MicroWriter.getNodeAsString (aDoc, aSettings);
  assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" +
                "<a:root xmlns:a=\"ns1url\" xmlns:xy=\"ns2url\">" +
                "<xy:child1 />" +
                "<xy:child2 attr1=\"a\" />" +
                "<ns0:child3 xmlns:ns0=\"ns3url\" ns0:attr1=\"a\" />" +
                "<ns0:child4 xmlns:ns0=\"ns3url\" xmlns:ns1=\"ns4url\" ns1:attr1=\"a\" />" +
                "</a:root>",
                s);

  eRoot.appendElement ("ns3url", "zz");
  s = MicroWriter.getNodeAsString (aDoc, aSettings);
  assertEquals ("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" +
                "<a:root xmlns:a=\"ns1url\" xmlns:xy=\"ns2url\">" +
                "<xy:child1 />" +
                "<xy:child2 attr1=\"a\" />" +
                "<ns0:child3 xmlns:ns0=\"ns3url\" ns0:attr1=\"a\" />" +
                "<ns0:child4 xmlns:ns0=\"ns3url\" xmlns:ns1=\"ns4url\" ns1:attr1=\"a\" />" +
                "<ns0:zz xmlns:ns0=\"ns3url\" />" +
                "</a:root>",
                s);
}
 
Example 8
Source File: SchematronPreprocessMojo.java    From ph-schematron with Apache License 2.0 4 votes vote down vote up
public void execute () throws MojoExecutionException, MojoFailureException
{
  StaticLoggerBinder.getSingleton ().setMavenLog (getLog ());
  if (m_aSourceFile == null)
    throw new MojoExecutionException ("No Source file specified!");
  if (m_aSourceFile.exists () && !m_aSourceFile.isFile ())
    throw new MojoExecutionException ("The specified Source file " + m_aSourceFile + " is not a file!");

  if (m_aTargetFile == null)
    throw new MojoExecutionException ("No Target file specified!");
  if (m_aTargetFile.exists ())
  {
    if (!m_bOverwriteWithoutNotice)
    {
      // 3.1 Not overwriting the existing file
      getLog ().debug ("Skipping Target file '" + m_aTargetFile.getPath () + "' because it already exists!");
    }
    else
    {
      if (!m_aTargetFile.isFile ())
        throw new MojoExecutionException ("The specified Target file " + m_aTargetFile + " is not a file!");
    }
  }

  try
  {
    final PSSchema aSchema = new PSReader (new FileSystemResource (m_aSourceFile), null, null).readSchema ();
    final IPSQueryBinding aQueryBinding = PSQueryBindingRegistry.getQueryBindingOfNameOrThrow (aSchema.getQueryBinding ());

    final PSPreprocessor aPreprocessor = new PSPreprocessor (aQueryBinding);
    aPreprocessor.setKeepTitles (m_bKeepTitles);
    aPreprocessor.setKeepDiagnostics (m_bKeepDiagnostics);
    aPreprocessor.setKeepReports (m_bKeepReports);
    aPreprocessor.setKeepEmptyPatterns (m_bKeepEmptyPatterns);

    // Pre-process
    final PSSchema aPreprocessedSchema = aPreprocessor.getForcedPreprocessedSchema (aSchema);
    if (aPreprocessedSchema == null)
      throw new SchematronPreprocessException ("Failed to preprocess schema " +
                                               aSchema +
                                               " with query binding " +
                                               aQueryBinding);

    // Convert to XML string
    final MapBasedNamespaceContext aNSCtx = new MapBasedNamespaceContext ();
    aNSCtx.addDefaultNamespaceURI (CSchematron.NAMESPACE_SCHEMATRON);
    aNSCtx.addMapping ("xsl", CSchematron.NAMESPACE_URI_XSL);
    aNSCtx.addMapping ("svrl", CSVRL.SVRL_NAMESPACE_URI);

    // Add all <ns> elements from schema as NS context
    for (final PSNS aItem : aSchema.getAllNSs ())
      aNSCtx.setMapping (aItem.getPrefix (), aItem.getUri ());

    final IXMLWriterSettings XWS = new XMLWriterSettings ().setIndent (EXMLSerializeIndent.INDENT_AND_ALIGN)
                                                           .setNamespaceContext (aNSCtx);
    final IMicroDocument aDoc = new MicroDocument ();
    aDoc.appendChild (aPreprocessedSchema.getAsMicroElement ());
    if (MicroWriter.writeToFile (aDoc, m_aTargetFile, XWS).isSuccess ())
      getLog ().info ("Successfully wrote preprocessed Schematron file '" + m_aTargetFile.getPath () + "'");
    else
      getLog ().error ("Error writing preprocessed Schematron file to '" + m_aTargetFile.getPath () + "'");
  }
  catch (final SchematronException ex)
  {
    throw new MojoExecutionException ("Error preprocessing Schematron file '" + m_aSourceFile + "'", ex);
  }
}
 
Example 9
Source File: CreateInvoiceFromScratchFuncTest.java    From ph-ubl with Apache License 2.0 4 votes vote down vote up
/**
 * This is an example that creates an XML schema compliant invoice <b>AND</b>
 * adds an extension as requested in issue #10
 */
@Test
public void testCreateInvoiceFromScratchWithExtension ()
{
  final String sCurrency = "EUR";

  // Create domain object
  final InvoiceType aInvoice = new InvoiceType ();

  // Fill it
  aInvoice.setID ("Dummy Invoice number");
  aInvoice.setIssueDate (PDTXMLConverter.getXMLCalendarDateNow ());

  final SupplierPartyType aSupplier = new SupplierPartyType ();
  aInvoice.setAccountingSupplierParty (aSupplier);

  final CustomerPartyType aCustomer = new CustomerPartyType ();
  aInvoice.setAccountingCustomerParty (aCustomer);

  final MonetaryTotalType aMT = new MonetaryTotalType ();
  aMT.setPayableAmount (BigDecimal.TEN).setCurrencyID (sCurrency);
  aInvoice.setLegalMonetaryTotal (aMT);

  final InvoiceLineType aLine = new InvoiceLineType ();
  aLine.setID ("1");

  final ItemType aItem = new ItemType ();
  aLine.setItem (aItem);

  aLine.setLineExtensionAmount (BigDecimal.TEN).setCurrencyID (sCurrency);

  aInvoice.addInvoiceLine (aLine);

  // Example extension content from issue #10:
  /**
   * <pre>
     <aife:FactureExtension xmlns:aife="urn:AIFE:Facture:Extension">
       <aife:CategoryCode>XX</aife:CategoryCode>
     </aife:FactureExtension>
   * </pre>
   */
  final Document aDoc = XMLFactory.newDocument ();
  final String sNamespaceURI = "urn:AIFE:Facture:Extension";
  final Node eRoot = aDoc.appendChild (aDoc.createElementNS (sNamespaceURI, "FactureExtension"));
  final Node eCategoryCode = eRoot.appendChild (aDoc.createElementNS (sNamespaceURI, "CategoryCode"));
  eCategoryCode.appendChild (aDoc.createTextNode ("XX"));

  // Now add the extension
  final UBLExtensionsType aExtensions = new UBLExtensionsType ();
  final UBLExtensionType aExtension = new UBLExtensionType ();
  final ExtensionContentType aExtensionContent = new ExtensionContentType ();
  // Add the root element - NEVER use the whole document!
  aExtensionContent.setAny (aDoc.getDocumentElement ());
  aExtension.setExtensionContent (aExtensionContent);
  aExtensions.addUBLExtension (aExtension);
  aInvoice.setUBLExtensions (aExtensions);

  // Write to disk ("as is")
  ESuccess eSuccess = UBL21Writer.invoice ().write (aInvoice, new File ("target/dummy-invoice-with-extension.xml"));
  assertTrue (eSuccess.isSuccess ());

  // doesn't work as expected yet
  if (false)
  {
    // Write to disk with a custom namespace prefix mapping
    final UBL21WriterBuilder <InvoiceType> aBuilder = UBL21Writer.invoice ();
    final MapBasedNamespaceContext aCtx = (MapBasedNamespaceContext) aBuilder.getNamespaceContext ();
    aCtx.addMapping ("aife", sNamespaceURI);
    eSuccess = aBuilder.write (aInvoice, new File ("target/dummy-invoice-with-extension-and-ns.xml"));
    assertTrue (eSuccess.isSuccess ());
  }
}