com.helger.xml.namespace.MapBasedNamespaceContext Java Examples

The following examples show how to use com.helger.xml.namespace.MapBasedNamespaceContext. 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: 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 #2
Source File: UBL21NamespaceContextTest.java    From ph-ubl with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore ("Fails")
public void testIssue25v2 ()
{
  try
  {
    // Get the original
    final UBL21NamespaceContext aNSCtx0 = UBL21NamespaceContext.getInstance ();
    // Clone
    final MapBasedNamespaceContext aNSCtx = UBL21NamespaceContext.getInstance ().getClone ();
    // Remove in original
    assertSame (EChange.CHANGED, aNSCtx0.removeMapping ("cec"));
    assertSame (EChange.UNCHANGED, aNSCtx0.removeMapping ("cec"));
    // Remove in clone
    assertSame (EChange.CHANGED, aNSCtx.removeMapping ("cec"));
    assertSame (EChange.UNCHANGED, aNSCtx.removeMapping ("cec"));
  }
  finally
  {
    UBL21NamespaceContext.getInstance ().addMapping ("cec", CUBL21.XML_SCHEMA_CEC_NAMESPACE_URL);
  }
}
 
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: 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 #5
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 #6
Source File: DianUBLWriterBuilder.java    From ph-ubl with Apache License 2.0 5 votes vote down vote up
public DianUBLWriterBuilder (@Nonnull final EDianUBLDocumentType eDocType)
{
  super (eDocType);

  // Create a special namespace context for the passed document type
  final MapBasedNamespaceContext aNSContext = new MapBasedNamespaceContext ();
  aNSContext.addMappings (new DianUBLNamespaceContext ());
  aNSContext.addDefaultNamespaceURI (m_aDocType.getNamespaceURI ());
  setNamespaceContext (aNSContext);
}
 
Example #7
Source File: UBL21WriterBuilder.java    From ph-ubl with Apache License 2.0 5 votes vote down vote up
public UBL21WriterBuilder (@Nonnull final EUBL21DocumentType eDocType)
{
  super (eDocType);

  // Create a special namespace context for the passed document type
  final MapBasedNamespaceContext aNSContext = UBL21NamespaceContext.getInstance ().getClone ();
  aNSContext.addDefaultNamespaceURI (m_aDocType.getNamespaceURI ());
  setNamespaceContext (aNSContext);
}
 
Example #8
Source File: UBL22WriterBuilder.java    From ph-ubl with Apache License 2.0 5 votes vote down vote up
public UBL22WriterBuilder (@Nonnull final EUBL22DocumentType eDocType)
{
  super (eDocType);

  // Create a special namespace context for the passed document type
  final MapBasedNamespaceContext aNSContext = UBL22NamespaceContext.getInstance ().getClone ();
  aNSContext.addDefaultNamespaceURI (m_aDocType.getNamespaceURI ());
  setNamespaceContext (aNSContext);
}
 
Example #9
Source File: UBL21NamespaceContextTest.java    From ph-ubl with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue25 ()
{
  final MapBasedNamespaceContext aNSCtx = UBL21NamespaceContext.getInstance ().getClone ();
  assertSame (EChange.CHANGED, aNSCtx.removeMapping ("cec"));
  assertSame (EChange.UNCHANGED, aNSCtx.removeMapping ("cec"));
}
 
Example #10
Source File: UBLTRWriterBuilder.java    From ph-ubl with Apache License 2.0 5 votes vote down vote up
public UBLTRWriterBuilder (@Nonnull final EUBLTRDocumentType eDocType)
{
  super (eDocType);

  // Create a special namespace context for the passed document type
  final MapBasedNamespaceContext aNSContext = new MapBasedNamespaceContext ();
  aNSContext.addMappings (new UBLTRNamespaceContext ());
  aNSContext.addDefaultNamespaceURI (m_aDocType.getNamespaceURI ());
  setNamespaceContext (aNSContext);
}
 
Example #11
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 #12
Source File: UBL20WriterBuilder.java    From ph-ubl with Apache License 2.0 5 votes vote down vote up
public UBL20WriterBuilder (@Nonnull final EUBL20DocumentType eDocType)
{
  super (eDocType);

  // Create a special namespace context for the passed document type
  final MapBasedNamespaceContext aNSContext = UBL20NamespaceContext.getInstance ().getClone ();
  aNSContext.addDefaultNamespaceURI (m_aDocType.getNamespaceURI ());
  setNamespaceContext (aNSContext);
}
 
Example #13
Source File: UBL20BuilderFuncTest.java    From ph-ubl with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadAndWriteInvoice ()
{
  final UBL20ReaderBuilder <InvoiceType> aReader = new UBL20ReaderBuilder<> (InvoiceType.class);
  final UBL20ValidatorBuilder <InvoiceType> aValidator = new UBL20ValidatorBuilder<> (InvoiceType.class);
  final UBL20WriterBuilder <InvoiceType> aWriter = new UBL20WriterBuilder<> (InvoiceType.class).setFormattedOutput (true);
  aWriter.setNamespaceContext (new MapBasedNamespaceContext ().addMapping ("bla",
                                                                           EUBL20DocumentType.INVOICE.getNamespaceURI ()));

  final String sFilename = MockUBL20TestDocuments.getUBL20TestDocuments (EUBL20DocumentType.INVOICE).get (0);

  // Read from resource
  final InvoiceType aRead1 = aReader.read (new ClassPathResource (sFilename));
  assertNotNull (aRead1);

  // Read from byte[]
  final InvoiceType aRead2 = aReader.read (StreamHelper.getAllBytes (new ClassPathResource (sFilename)));
  assertNotNull (aRead2);
  assertEquals (aRead1, aRead2);

  // Validate
  final IErrorList aREG1 = aValidator.validate (aRead1);
  final IErrorList aREG2 = aValidator.validate (aRead2);
  assertEquals (aREG1, aREG2);

  // Write
  final String s = aWriter.getAsString (aRead1);
  System.out.println (s);
}
 
Example #14
Source File: UBLPEWriterBuilder.java    From ph-ubl with Apache License 2.0 5 votes vote down vote up
public UBLPEWriterBuilder (@Nonnull final EUBLPEDocumentType eDocType)
{
  super (eDocType);

  // Create a special namespace context for the passed document type
  final MapBasedNamespaceContext aNSContext = new MapBasedNamespaceContext ();
  aNSContext.addMappings (new UBLPENamespaceContext ());
  aNSContext.addDefaultNamespaceURI (m_aDocType.getNamespaceURI ());
  setNamespaceContext (aNSContext);
}
 
Example #15
Source File: SafeXMLStreamWriter.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
public ElementState (@Nullable final String sPrefix,
                     @Nonnull final String sLocalName,
                     @Nonnull final EXMLSerializeBracketMode eBracketMode,
                     @Nonnull final MapBasedNamespaceContext aNamespaceContext)
{
  m_sPrefix = sPrefix;
  m_sLocalName = sLocalName;
  m_eBracketMode = eBracketMode;
  m_aNamespaceContext = aNamespaceContext;
}
 
Example #16
Source File: XMLWriterSettings.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Set the namespace context to be used.
 *
 * @param aNamespaceContext
 *        The namespace context to be used. May be <code>null</code>.
 * @return this
 */
@Nonnull
public final XMLWriterSettings setNamespaceContext (@Nullable final INamespaceContext aNamespaceContext)
{
  // A namespace context must always be present, to resolve default namespaces
  m_aNamespaceContext = aNamespaceContext != null ? aNamespaceContext : new MapBasedNamespaceContext ();
  return this;
}
 
Example #17
Source File: UBL23WriterBuilder.java    From ph-ubl with Apache License 2.0 5 votes vote down vote up
public UBL23WriterBuilder (@Nonnull final EUBL23DocumentType eDocType)
{
  super (eDocType);

  // Create a special namespace context for the passed document type
  final MapBasedNamespaceContext aNSContext = UBL23NamespaceContext.getInstance ().getClone ();
  aNSContext.addDefaultNamespaceURI (m_aDocType.getNamespaceURI ());
  setNamespaceContext (aNSContext);
}
 
Example #18
Source File: MockMarshallerExternal.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
public MockMarshallerExternal ()
{
  // No XSD available
  super (com.helger.jaxb.mock.external.MockJAXBArchive.class,
         null,
         x -> new JAXBElement <> (new QName ("urn:test:external", "any"),
                                  com.helger.jaxb.mock.external.MockJAXBArchive.class,
                                  x));
  setFormattedOutput (true);
  setNamespaceContext (new MapBasedNamespaceContext ().addMapping ("def", "urn:test:external"));
}
 
Example #19
Source File: MainCreateJAXBBinding23.java    From ph-ubl with Apache License 2.0 4 votes vote down vote up
public static void main (final String [] args)
{
  // UBL 2.3
  {
    System.out.println ("UBL 2.3");
    final IMicroDocument eDoc = _createBaseDoc ();
    final ICommonsSet <String> aNamespaces = new CommonsHashSet <> ();
    for (final String sPart : new String [] { "common", "maindoc" })
    {
      final String sBasePath = BASE_XSD_PATH + sPart;
      for (final File aFile : _getFileList ("src/main" + sBasePath))
      {
        // Each namespace should handled only once
        final IMicroDocument aDoc = MicroReader.readMicroXML (new FileSystemResource (aFile));
        final String sTargetNamespace = _getTargetNamespace (aDoc);
        if (!aNamespaces.add (sTargetNamespace))
        {
          System.out.println ("Ignored namespace URI " + sTargetNamespace + " in " + aFile.getName ());
          continue;
        }
        String sPackageName = _convertToPackage (sTargetNamespace);
        if (sPackageName.endsWith ("_2"))
        {
          // Change "_2" to "_23"
          sPackageName += "3";
        }
        // schemaLocation must be relative to bindings file!
        final IMicroElement eBindings = eDoc.getDocumentElement ()
                                            .appendElement (JAXB_NS_URI, "bindings")
                                            .setAttribute ("schemaLocation",
                                                           ".." + sBasePath + "/" + aFile.getName ())
                                            .setAttribute ("node", "/xsd:schema");
        eBindings.appendElement (JAXB_NS_URI, "schemaBindings")
                 .appendElement (JAXB_NS_URI, "package")
                 .setAttribute ("name", sPackageName);
      }
    }
    MicroWriter.writeToFile (eDoc,
                             new File (DEFAULT_BINDING_FILE),
                             new XMLWriterSettings ().setIncorrectCharacterHandling (EXMLIncorrectCharacterHandling.DO_NOT_WRITE_LOG_WARNING)
                                                     .setNamespaceContext (new MapBasedNamespaceContext ().addMapping (XMLConstants.DEFAULT_NS_PREFIX,
                                                                                                                       JAXB_NS_URI)
                                                                                                          .addMapping ("xsd",
                                                                                                                       XMLConstants.W3C_XML_SCHEMA_NS_URI)
                                                                                                          .addMapping ("xsi",
                                                                                                                       XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI))
                                                     .setPutNamespaceContextPrefixesInRoot (true));
  }

  System.out.println ("Done");
}
 
Example #20
Source File: MainCreateJAXBBinding20.java    From ph-ubl with Apache License 2.0 4 votes vote down vote up
public static void main (final String [] args)
{
  // UBL 2.0
  {
    System.out.println ("UBL 2.0");
    final IMicroDocument eDoc = _createBaseDoc ();
    final ICommonsSet <String> aNamespaces = new CommonsHashSet <> ();
    for (final String sPart : new String [] { "common", "maindoc" })
    {
      final String sBasePath = "/resources/schemas/ubl20/" + sPart;
      for (final File aFile : _getFileList ("src/main" + sBasePath))
      {
        // Each namespace should handled only once
        final IMicroDocument aDoc = MicroReader.readMicroXML (new FileSystemResource (aFile));
        final String sTargetNamespace = _getTargetNamespace (aDoc);
        if (!aNamespaces.add (sTargetNamespace))
        {
          System.out.println ("Ignored " + sTargetNamespace + " in " + aFile.getName ());
          continue;
        }
        final String sPackageName = _convertToPackage (sTargetNamespace);
        // schemaLocation must be relative to bindings file!
        final IMicroElement eBindings = eDoc.getDocumentElement ()
                                            .appendElement (JAXB_NS_URI, "bindings")
                                            .setAttribute ("schemaLocation",
                                                           ".." + sBasePath + "/" + aFile.getName ())
                                            .setAttribute ("node", "/xsd:schema");

        eBindings.appendElement (JAXB_NS_URI, "schemaBindings")
                 .appendElement (JAXB_NS_URI, "package")
                 .setAttribute ("name", sPackageName);

        if (aFile.getName ().equals ("CodeList_UnitCode_UNECE_7_04.xsd") ||
            aFile.getName ().equals ("CodeList_LanguageCode_ISO_7_04.xsd"))
        {
          _generateExplicitEnumMapping (aDoc, aFile.getName (), eBindings);
        }
      }
    }
    MicroWriter.writeToFile (eDoc,
                             new File ("src/main/jaxb/bindings20.xjb"),
                             new XMLWriterSettings ().setIncorrectCharacterHandling (EXMLIncorrectCharacterHandling.DO_NOT_WRITE_LOG_WARNING)
                                                     .setNamespaceContext (new MapBasedNamespaceContext ().addMapping (XMLConstants.DEFAULT_NS_PREFIX,
                                                                                                                       JAXB_NS_URI)
                                                                                                          .addMapping ("xsd",
                                                                                                                       XMLConstants.W3C_XML_SCHEMA_NS_URI)
                                                                                                          .addMapping ("xsi",
                                                                                                                       XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI))
                                                     .setPutNamespaceContextPrefixesInRoot (true));
  }

  System.out.println ("Done");
}
 
Example #21
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 ());
  }
}
 
Example #22
Source File: MainCreateJAXBBinding21.java    From ph-ubl with Apache License 2.0 4 votes vote down vote up
public static void main (final String [] args)
{
  // UBL 2.1
  {
    System.out.println ("UBL 2.1");
    final IMicroDocument eDoc = _createBaseDoc ();
    final ICommonsSet <String> aNamespaces = new CommonsHashSet <> ();
    for (final String sPart : new String [] { "common", "maindoc" })
    {
      final String sBasePath = BASE_XSD_PATH + sPart;
      for (final File aFile : _getFileList ("src/main" + sBasePath))
      {
        // Each namespace should handled only once
        final IMicroDocument aDoc = MicroReader.readMicroXML (new FileSystemResource (aFile));
        final String sTargetNamespace = _getTargetNamespace (aDoc);
        if (!aNamespaces.add (sTargetNamespace))
        {
          System.out.println ("Ignored " + sTargetNamespace + " in " + aFile.getName ());
          continue;
        }
        String sPackageName = _convertToPackage (sTargetNamespace);
        if (sPackageName.endsWith ("_2"))
        {
          // Change "_2" to "_21"
          sPackageName += "1";
        }
        // schemaLocation must be relative to bindings file!
        final IMicroElement eBindings = eDoc.getDocumentElement ()
                                            .appendElement (JAXB_NS_URI, "bindings")
                                            .setAttribute ("schemaLocation",
                                                           ".." + sBasePath + "/" + aFile.getName ())
                                            .setAttribute ("node", "/xsd:schema");
        eBindings.appendElement (JAXB_NS_URI, "schemaBindings")
                 .appendElement (JAXB_NS_URI, "package")
                 .setAttribute ("name", sPackageName);
      }
    }
    MicroWriter.writeToFile (eDoc,
                             new File (DEFAULT_BINDING_FILE),
                             new XMLWriterSettings ().setIncorrectCharacterHandling (EXMLIncorrectCharacterHandling.DO_NOT_WRITE_LOG_WARNING)
                                                     .setNamespaceContext (new MapBasedNamespaceContext ().addMapping (XMLConstants.DEFAULT_NS_PREFIX,
                                                                                                                       JAXB_NS_URI)
                                                                                                          .addMapping ("xsd",
                                                                                                                       XMLConstants.W3C_XML_SCHEMA_NS_URI)
                                                                                                          .addMapping ("xsi",
                                                                                                                       XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI))
                                                     .setPutNamespaceContextPrefixesInRoot (true));
  }

  System.out.println ("Done");
}
 
Example #23
Source File: MainCreateJAXBBinding22.java    From ph-ubl with Apache License 2.0 4 votes vote down vote up
public static void main (final String [] args)
{
  // UBL 2.2
  {
    System.out.println ("UBL 2.2");
    final IMicroDocument eDoc = _createBaseDoc ();
    final ICommonsSet <String> aNamespaces = new CommonsHashSet <> ();
    for (final String sPart : new String [] { "common", "maindoc" })
    {
      final String sBasePath = BASE_XSD_PATH + sPart;
      for (final File aFile : _getFileList ("src/main" + sBasePath))
      {
        // Each namespace should handled only once
        final IMicroDocument aDoc = MicroReader.readMicroXML (new FileSystemResource (aFile));
        final String sTargetNamespace = _getTargetNamespace (aDoc);
        if (!aNamespaces.add (sTargetNamespace))
        {
          System.out.println ("Ignored namespace URI " + sTargetNamespace + " in " + aFile.getName ());
          continue;
        }
        String sPackageName = _convertToPackage (sTargetNamespace);
        if (sPackageName.endsWith ("_2"))
        {
          // Change "_2" to "_22"
          sPackageName += "2";
        }
        // schemaLocation must be relative to bindings file!
        final IMicroElement eBindings = eDoc.getDocumentElement ()
                                            .appendElement (JAXB_NS_URI, "bindings")
                                            .setAttribute ("schemaLocation",
                                                           ".." + sBasePath + "/" + aFile.getName ())
                                            .setAttribute ("node", "/xsd:schema");
        eBindings.appendElement (JAXB_NS_URI, "schemaBindings")
                 .appendElement (JAXB_NS_URI, "package")
                 .setAttribute ("name", sPackageName);
      }
    }
    MicroWriter.writeToFile (eDoc,
                             new File (DEFAULT_BINDING_FILE),
                             new XMLWriterSettings ().setIncorrectCharacterHandling (EXMLIncorrectCharacterHandling.DO_NOT_WRITE_LOG_WARNING)
                                                     .setNamespaceContext (new MapBasedNamespaceContext ().addMapping (XMLConstants.DEFAULT_NS_PREFIX,
                                                                                                                       JAXB_NS_URI)
                                                                                                          .addMapping ("xsd",
                                                                                                                       XMLConstants.W3C_XML_SCHEMA_NS_URI)
                                                                                                          .addMapping ("xsi",
                                                                                                                       XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI))
                                                     .setPutNamespaceContextPrefixesInRoot (true));
  }

  System.out.println ("Done");
}
 
Example #24
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 #25
Source File: SaxonNamespaceContext.java    From ph-schematron with Apache License 2.0 4 votes vote down vote up
public SaxonNamespaceContext (@Nonnull final MapBasedNamespaceContext aCtx)
{
  m_aCtx = ValueEnforcer.notNull (aCtx, "Ctx");
}
 
Example #26
Source File: PSXPathBoundSchema.java    From ph-schematron with Apache License 2.0 4 votes vote down vote up
@Nonnull
private XPath _createXPathContext ()
{
  final MapBasedNamespaceContext aNamespaceContext = getNamespaceContext ();
  final XPath aXPathContext = XPathHelper.createNewXPath (m_aXPathConfig.getXPathFactory (),
                                                          m_aXPathConfig.getXPathVariableResolver (),
                                                          m_aXPathConfig.getXPathFunctionResolver (),
                                                          aNamespaceContext);

  if ("net.sf.saxon.xpath.XPathEvaluator".equals (aXPathContext.getClass ().getName ()))
  {
    // Saxon implementation special handling
    final XPathEvaluator aSaxonXPath = (XPathEvaluator) aXPathContext;

    // Since 9.7.0-4 it must implement NamespaceResolver
    aSaxonXPath.setNamespaceContext (new SaxonNamespaceContext (aNamespaceContext));

    // Wrap the PSErrorHandler to a ErrorListener
    final Function <Configuration, ? extends ErrorReporter> factory = cfg -> {
      final IPSErrorHandler aErrHdl = getErrorHandler ();
      return (final XmlProcessingError error) -> {
        final ILocation aLocation = error.getLocation () == null ? null
                                                                 : new SimpleLocation (error.getLocation ()
                                                                                            .getSystemId (),
                                                                                       error.getLocation ()
                                                                                            .getLineNumber (),
                                                                                       error.getLocation ()
                                                                                            .getColumnNumber ());
        aErrHdl.handleError (SingleError.builder ()
                                        .setErrorLevel (error.isWarning () ? EErrorLevel.WARN : EErrorLevel.ERROR)
                                        .setErrorID (error.getErrorCode () != null ? error.getErrorCode ().toString ()
                                                                                   : null)
                                        .setErrorLocation (aLocation)
                                        .setErrorText (error.getMessage ())
                                        .setLinkedException (error.getCause ())
                                        .build ());
      };
    };
    aSaxonXPath.getConfiguration ().setErrorReporterFactory (factory);
  }
  return aXPathContext;
}
 
Example #27
Source File: AbstractPSBoundSchema.java    From ph-schematron with Apache License 2.0 4 votes vote down vote up
@Nonnull
public final MapBasedNamespaceContext getNamespaceContext ()
{
  return m_aNamespaceContext;
}
 
Example #28
Source File: MicroReaderTest.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
/**
 * Test: same as namespace3 test but with a namespace context map
 */
@Test
public void testNamespaces3a ()
{
  final XMLWriterSettings xs = new XMLWriterSettings ();
  xs.setIndent (EXMLSerializeIndent.NONE);
  xs.setUseDoubleQuotesForAttributes (false);
  xs.setNamespaceContext (new MapBasedNamespaceContext ().addMapping ("a1", "uri1").addMapping ("a2", "uri2"));

  final String s = "<?xml version=\"1.0\"?>" +
                   "<verrryoot xmlns='uri1' xmlns:a='uri2'>" +
                   "<root>" +
                   "<a:child>" +
                   "<a:child2>Value text - no entities!</a:child2>" +
                   "</a:child>" +
                   "</root>" +
                   "</verrryoot>";
  final IMicroDocument aDoc = MicroReader.readMicroXML (s);
  assertNotNull (aDoc);

  String sXML = MicroWriter.getNodeAsString (aDoc, xs);
  assertEquals ("<?xml version='1.0' encoding='UTF-8'?>" +
                "<a1:verrryoot xmlns:a1='uri1'>" +
                "<a1:root>" +
                "<a2:child xmlns:a2='uri2'>" +
                "<a2:child2>Value text - no entities!</a2:child2>" +
                "</a2:child>" +
                "</a1:root>" +
                "</a1:verrryoot>",
                sXML);

  xs.setPutNamespaceContextPrefixesInRoot (true);
  sXML = MicroWriter.getNodeAsString (aDoc, xs);
  assertEquals ("<?xml version='1.0' encoding='UTF-8'?>" +
                "<a1:verrryoot xmlns:a1='uri1' xmlns:a2='uri2'>" +
                "<a1:root>" +
                "<a2:child>" +
                "<a2:child2>Value text - no entities!</a2:child2>" +
                "</a2:child>" +
                "</a1:root>" +
                "</a1:verrryoot>",
                sXML);
}
 
Example #29
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 #30
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);
}