com.helger.xml.microdom.serialize.MicroReader Java Examples

The following examples show how to use com.helger.xml.microdom.serialize.MicroReader. 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: MimeTypeInfoManager.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Read the information from the specified resource.
 *
 * @param aRes
 *        The resource to read. May not be <code>null</code>.
 * @return this
 */
@Nonnull
public MimeTypeInfoManager read (@Nonnull final IReadableResource aRes)
{
  ValueEnforcer.notNull (aRes, "Resource");

  final IMicroDocument aDoc = MicroReader.readMicroXML (aRes);
  if (aDoc == null)
    throw new IllegalArgumentException ("Failed to read MimeTypeInfo resource " + aRes);

  aDoc.getDocumentElement ().forAllChildElements (eItem -> {
    final MimeTypeInfo aInfo = MicroTypeConverter.convertToNative (eItem, MimeTypeInfo.class);
    registerMimeType (aInfo);
  });
  return this;
}
 
Example #2
Source File: XMLMapHandler.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Read a mapping from the passed input stream.
 *
 * @param aIS
 *        The input stream to read from. May not be <code>null</code>.
 * @param aTargetMap
 *        The target map to be filled.
 * @return {@link ESuccess#SUCCESS} if the stream could be opened, if it could
 *         be read as XML and if the root element was correct.
 *         {@link ESuccess#FAILURE} otherwise.
 */
@Nonnull
public static ESuccess readMap (@Nonnull @WillClose final InputStream aIS,
                                @Nonnull final Map <String, String> aTargetMap)
{
  ValueEnforcer.notNull (aIS, "InputStream");
  ValueEnforcer.notNull (aTargetMap, "TargetMap");

  try (final InputStream aCloseMe = aIS)
  {
    // open file
    final IMicroDocument aDoc = MicroReader.readMicroXML (aIS);
    if (aDoc != null)
    {
      readMap (aDoc.getDocumentElement (), aTargetMap);
      return ESuccess.SUCCESS;
    }
  }
  catch (final Exception ex)
  {
    if (LOGGER.isWarnEnabled ())
      LOGGER.warn ("Failed to read mapping resource '" + aIS + "'", ex);
  }
  return ESuccess.FAILURE;
}
 
Example #3
Source File: SchematronHelper.java    From ph-schematron with Apache License 2.0 6 votes vote down vote up
/**
 * Resolve all Schematron includes of the passed resource.
 *
 * @param aResource
 *        The Schematron resource to read. May not be <code>null</code>.
 * @param aSettings
 *        The SAX reader settings to be used. May be <code>null</code> to use
 *        the default settings.
 * @param aErrorHandler
 *        The error handler to be used. May not be <code>null</code>.
 * @param bLenient
 *        <code>true</code> if 'old' Schematron NS is tolerated.
 * @return <code>null</code> if the passed resource could not be read as XML
 *         document
 * @since 5.4.1
 */
@Nullable
public static IMicroDocument getWithResolvedSchematronIncludes (@Nonnull final IReadableResource aResource,
                                                                @Nullable final ISAXReaderSettings aSettings,
                                                                @Nonnull final IPSErrorHandler aErrorHandler,
                                                                final boolean bLenient)
{
  final InputSource aIS = InputSourceFactory.create (aResource);
  final IMicroDocument aDoc = MicroReader.readMicroXML (aIS, aSettings);
  if (aDoc != null)
  {
    // Resolve all Schematron includes
    if (_recursiveResolveAllSchematronIncludes (aDoc.getDocumentElement (),
                                                aResource,
                                                aSettings,
                                                aErrorHandler,
                                                bLenient).isFailure ())
    {
      // Error resolving includes
      return null;
    }
  }
  return aDoc;
}
 
Example #4
Source File: SettingsPersistenceXML.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
public T readSettings (@Nonnull @WillClose final InputStream aIS)
{
  ValueEnforcer.notNull (aIS, "InputStream");

  final IMicroDocument aDoc = MicroReader.readMicroXML (aIS);
  if (aDoc == null)
    throw new IllegalArgumentException ("Passed XML document is illegal");

  // read items
  final SettingsMicroDocumentConverter <T> aConverter = new SettingsMicroDocumentConverter <> (m_aSettingsFactory);
  return aConverter.convertToNative (aDoc.getDocumentElement ());
}
 
Example #5
Source File: XMLResourceBundle.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
@ReturnsMutableCopy
public static ICommonsOrderedMap <String, String> readFromPropertiesXML (@Nonnull @WillClose final InputStream aIS)
{
  final ICommonsOrderedMap <String, String> ret = new CommonsLinkedHashMap <> ();
  final IMicroDocument aDoc = MicroReader.readMicroXML (aIS);
  if (aDoc != null)
    for (final IMicroElement eChild : aDoc.getDocumentElement ().getAllChildElements ("entry"))
      ret.put (eChild.getAttributeValue ("key"), eChild.getTextContent ());
  return ret;
}
 
Example #6
Source File: XMLListHandler.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Read a predefined XML file that contains list items.
 *
 * @param aIS
 *        The input stream to read from. May not be <code>null</code>.
 *        Automatically closed no matter whether reading succeeded or not.
 * @param aTargetList
 *        The target collection to be filled. May not be <code>null</code>.
 * @return {@link ESuccess#SUCCESS} if reading succeeded,
 *         {@link ESuccess#FAILURE} if the input stream is no valid XML or any
 *         other error occurred.
 */
@Nonnull
public static ESuccess readList (@Nonnull @WillClose final InputStream aIS,
                                 @Nonnull final Collection <String> aTargetList)
{
  ValueEnforcer.notNull (aIS, "InputStream");
  ValueEnforcer.notNull (aTargetList, "TargetList");

  try
  {
    // open file
    final IMicroDocument aDoc = MicroReader.readMicroXML (aIS,
                                                          new SAXReaderSettings ().setFeatureValues (EXMLParserFeature.AVOID_XXE_SETTINGS));
    if (aDoc != null)
    {
      readList (aDoc.getDocumentElement (), aTargetList);
      return ESuccess.SUCCESS;
    }
  }
  catch (final Exception ex)
  {
    if (LOGGER.isWarnEnabled ())
      LOGGER.warn ("Failed to read list resource '" + aIS + "'", ex);
  }
  finally
  {
    StreamHelper.close (aIS);
  }

  return ESuccess.FAILURE;
}
 
Example #7
Source File: ReadWriteXML11FuncTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadingXML11 ()
{
  final String sFilename1 = "target/xml11test.xml";
  _generateXmlFile (sFilename1, 2500);

  // Read again
  final IMicroDocument aDoc = MicroReader.readMicroXML (new File (sFilename1));
  assertNotNull (aDoc);

  // Write again
  final String sFilename2 = "target/xml11test2.xml";
  assertTrue (MicroWriter.writeToFile (aDoc, new File (sFilename2), XWS_11).isSuccess ());

  // Read again
  final IMicroDocument aDoc2 = MicroReader.readMicroXML (new File (sFilename2));
  assertNotNull (aDoc2);

  // When using JAXP with Java 1.6.0_22, 1.6.0_29 or 1.6.0_45 (tested only
  // with this
  // version) the following test fails. That's why xerces must be included!
  // The bogus XMLReader is
  // com.sun.org.apache.xerces.internal.parsers.SAXParser
  assertTrue ("Documents are different when written to XML 1.1!\nUsed SAX XML reader: " +
              SAXReaderFactory.createXMLReader ().getClass ().getName () +
              "\nJava version: " +
              SystemProperties.getJavaVersion () +
              "\n" +
              MicroWriter.getNodeAsString (aDoc) +
              "\n\n" +
              MicroWriter.getNodeAsString (aDoc2),
              aDoc.isEqualContent (aDoc2));
}
 
Example #8
Source File: TreeXMLConverterTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadWrite ()
{
  // read initial document
  final IMicroDocument aDoc1 = MicroReader.readMicroXML (new ClassPathResource ("tree/xmlconverter-valid1.xml"));
  assertNotNull (aDoc1);

  // convert document to tree
  final DefaultTreeWithGlobalUniqueID <String, MockHasName> t1 = TreeXMLConverter.getXMLAsTreeWithUniqueStringID (aDoc1.getDocumentElement (),
                                                                                                                  new MockHasNameConverter ());
  assertNotNull (t1);

  // convert tree again to document
  final IMicroElement aDoc2 = TreeXMLConverter.getTreeWithStringIDAsXML (t1, new MockHasNameConverter ());
  assertNotNull (aDoc2);

  // and convert the document again to a tree
  DefaultTreeWithGlobalUniqueID <String, MockHasName> t2 = TreeXMLConverter.getXMLAsTreeWithUniqueStringID (aDoc2,
                                                                                                            new MockHasNameConverter ());
  assertNotNull (t2);
  assertEquals (t1, t2);

  // and convert the document again to a tree
  t2 = TreeXMLConverter.getXMLAsTreeWithUniqueID (aDoc2, aID -> aID, new MockHasNameConverter ());
  assertNotNull (t2);
  assertEquals (t1, t2);

  // and convert the document again to a tree
  assertNotNull (TreeXMLConverter.getXMLAsTreeWithID (aDoc2, aID -> aID, new MockHasNameConverter ()));
}
 
Example #9
Source File: AbstractWALDAO.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used upon recovery to convert a stored object to its native
 * representation. If you overwrite this method, you should consider
 * overriding {@link #convertNativeToWALString(Serializable)} as well.
 *
 * @param sElement
 *        The string representation to be converted. Never <code>null</code>.
 * @return The native representation of the object. If the return value is
 *         <code>null</code>, the recovery will fail with an exception!
 */
@Nullable
@OverrideOnDemand
@IsLocked (ELockType.WRITE)
protected DATATYPE convertWALStringToNative (@Nonnull final String sElement)
{
  final IMicroDocument aDoc = MicroReader.readMicroXML (sElement);
  if (aDoc == null || aDoc.getDocumentElement () == null)
    return null;
  return MicroTypeConverter.convertToNative (aDoc.getDocumentElement (), m_aDataTypeClass);
}
 
Example #10
Source File: SchematronTestHelper.java    From ph-schematron with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static ICommonsList <SchematronTestFile> _readDI (@Nonnull final IReadableResource aRes)
{
  if (false)
    ClassPathHelper.getAllClassPathEntries ().forEach (x -> {
      System.out.println (x);
      if (new File (x).isDirectory ())
      {
        final FileSystemRecursiveIterator it = new FileSystemRecursiveIterator (new File (x));
        it.forEach (y -> System.out.println (StringHelper.getRepeated ("  ", it.getLevel ()) + y));
      }
    });
  ValueEnforcer.notNull (aRes, "Resource");
  ValueEnforcer.isTrue (aRes.exists (), () -> "Resource " + aRes + " does not exist!");

  final ICommonsList <SchematronTestFile> ret = new CommonsArrayList <> ();
  final IMicroDocument aDoc = MicroReader.readMicroXML (aRes);
  if (aDoc == null)
    throw new IllegalArgumentException ("Failed to open/parse " + aRes + " as XML");
  String sLastParentDirBaseName = null;
  for (final IMicroElement eItem : aDoc.getDocumentElement ().getAllChildElements ())
    if (eItem.getTagName ().equals ("directory"))
      sLastParentDirBaseName = eItem.getAttributeValue ("basename");
    else
      if (eItem.getTagName ().equals ("file"))
        ret.add (new SchematronTestFile (sLastParentDirBaseName,
                                         new ClassPathResource (eItem.getAttributeValue ("name")),
                                         eItem.getAttributeValue ("basename")));
      else
        throw new IllegalArgumentException ("Cannot handle " + eItem);
  return ret;
}
 
Example #11
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 #12
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 #13
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 #14
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");
}