com.helger.xml.microdom.IMicroDocument Java Examples

The following examples show how to use com.helger.xml.microdom.IMicroDocument. 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: MicroSerializer.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings ("deprecation")
private void _writeDocument (@Nonnull final XMLEmitter aXMLWriter, final IMicroDocument aDocument)
{
  if (m_aSettings.getSerializeXMLDeclaration ().isEmit ())
  {
    aXMLWriter.onXMLDeclaration (m_aSettings.getXMLVersion (),
                                 m_aSettings.getCharset ().name (),
                                 m_aSettings.getSerializeXMLDeclaration ()
                                            .isEmitStandalone () ? aDocument.getStandalone () : ETriState.UNDEFINED,
                                 m_aSettings.getSerializeXMLDeclaration ()
                                            .isWithNewLine () && m_aSettings.isNewLineAfterXMLDeclaration ());
  }

  if (aDocument.hasChildren ())
    _writeNodeList (aXMLWriter, aDocument, aDocument.getAllChildren ());
}
 
Example #2
Source File: XMLListHandler.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Write the passed collection to the passed output stream using the
 * predefined XML layout.
 *
 * @param aCollection
 *        The map to be written. May not be <code>null</code>.
 * @param aOS
 *        The output stream to write to. The stream is closed independent of
 *        success or failure. May not be <code>null</code>.
 * @return {@link ESuccess#SUCCESS} when everything went well,
 *         {@link ESuccess#FAILURE} otherwise.
 */
@Nonnull
public static ESuccess writeList (@Nonnull final Collection <String> aCollection,
                                  @Nonnull @WillClose final OutputStream aOS)
{
  ValueEnforcer.notNull (aCollection, "Collection");
  ValueEnforcer.notNull (aOS, "OutputStream");

  try
  {
    final IMicroDocument aDoc = createListDocument (aCollection);
    return MicroWriter.writeToStream (aDoc, aOS, XMLWriterSettings.DEFAULT_XML_SETTINGS);
  }
  finally
  {
    StreamHelper.close (aOS);
  }
}
 
Example #3
Source File: MicroReader.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Nullable
public static IMicroDocument readMicroXML (@WillClose @Nullable final Reader aReader,
                                           @Nullable final ISAXReaderSettings aSettings)
{
  if (aReader == null)
    return null;

  try
  {
    return readMicroXML (InputSourceFactory.create (aReader), aSettings);
  }
  finally
  {
    StreamHelper.close (aReader);
  }
}
 
Example #4
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 #5
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 #6
Source File: PSReader.java    From ph-schematron with Apache License 2.0 6 votes vote down vote up
/**
 * Read the schema from the resource supplied in the constructor. First all
 * includes are resolved and than {@link #readSchemaFromXML(IMicroElement)} is
 * called.
 *
 * @return The read {@link PSSchema}.
 * @throws SchematronReadException
 *         If reading fails
 */
@Nonnull
public PSSchema readSchema () throws SchematronReadException
{
  // Resolve all includes as the first action
  final SAXReaderSettings aSettings = new SAXReaderSettings ().setEntityResolver (m_aEntityResolver);

  final IMicroDocument aDoc = SchematronHelper.getWithResolvedSchematronIncludes (m_aResource,
                                                                                  aSettings,
                                                                                  m_aErrorHandler,
                                                                                  m_bLenient);
  if (aDoc == null || aDoc.getDocumentElement () == null)
    throw new SchematronReadException (m_aResource,
                                       "Failed to resolve includes in Schematron resource " + m_aResource);

  if (SchematronDebug.isShowResolvedSourceSchematron ())
    LOGGER.info ("Resolved source Schematron:\n" + MicroWriter.getNodeAsString (aDoc));

  return readSchemaFromXML (aDoc.getDocumentElement ());
}
 
Example #7
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 #8
Source File: ChildrenProviderElementWithNameTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasic ()
{
  final IMicroDocument aDoc = _buildTestDoc ();
  final IMicroElement aDocElement = aDoc.getDocumentElement ();

  ChildrenProviderElementWithName x = new ChildrenProviderElementWithName ("any");

  assertTrue (x.hasChildren (aDocElement));
  assertEquals (2, x.getChildCount (aDocElement));
  assertEquals (2, x.getAllChildren (aDocElement).size ());

  x = new ChildrenProviderElementWithName ("namespace", "any");

  assertTrue (x.hasChildren (aDocElement));
  assertEquals (1, x.getChildCount (aDocElement));
  assertEquals (1, x.getAllChildren (aDocElement).size ());
}
 
Example #9
Source File: MainCreateJAXBBinding22.java    From ph-ubl with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static IMicroDocument _createBaseDoc ()
{
  final IMicroDocument eDoc = new MicroDocument ();
  final IMicroElement eRoot = eDoc.appendElement (JAXB_NS_URI, "bindings");
  eRoot.setAttribute (XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI,
                      "schemaLocation",
                      JAXB_NS_URI + " http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd");
  // This is the JAXB version, not the UBL version :)
  eRoot.setAttribute ("version", "2.1");

  final IMicroElement eGlobal = eRoot.appendElement (JAXB_NS_URI, "globalBindings");
  eGlobal.setAttribute ("typesafeEnumMaxMembers", "2000");
  eGlobal.setAttribute ("typesafeEnumMemberName", "generateError");
  return eDoc;
}
 
Example #10
Source File: AbstractWALDAO.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Modify the created document by e.g. adding some comment or digital
 * signature or whatsoever.
 *
 * @param aDoc
 *        The created non-<code>null</code> document.
 */
@OverrideOnDemand
@MustBeLocked (ELockType.WRITE)
protected void modifyWriteData (@Nonnull final IMicroDocument aDoc)
{
  final IMicroComment aComment = new MicroComment ("This file was generated automatically - do NOT modify!\n" +
                                                   "Written at " +
                                                   PDTToString.getAsString (ZonedDateTime.now (Clock.systemUTC ()),
                                                                            Locale.US));
  final IMicroElement eRoot = aDoc.getDocumentElement ();
  // Add a small comment
  if (eRoot != null)
    aDoc.insertBefore (aComment, eRoot);
  else
    aDoc.appendChild (aComment);
}
 
Example #11
Source File: MicroReaderTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testSpecialXMLAttrs ()
{
  final String s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                   "<root xml:lang=\"en\" xml:space=\"preserve\" xml:base=\"baseuri\" xml:id=\"4711\">" +
                   "Bla" +
                   "</root>";
  final IMicroDocument aDoc = MicroReader.readMicroXML (s);
  assertNotNull (aDoc);
  final IMicroElement eRoot = aDoc.getDocumentElement ();
  assertEquals ("en", eRoot.getAttributeValue (XMLConstants.XML_NS_URI, "lang"));
  assertNull (eRoot.getAttributeValue ("lang"));
  assertEquals ("preserve", eRoot.getAttributeValue (XMLConstants.XML_NS_URI, "space"));
  assertEquals ("baseuri", eRoot.getAttributeValue (XMLConstants.XML_NS_URI, "base"));
  assertEquals ("4711", eRoot.getAttributeValue (XMLConstants.XML_NS_URI, "id"));

  // Ensure they are written as well
  assertEquals (s, MicroWriter.getNodeAsString (aDoc, new XMLWriterSettings ().setIndent (EXMLSerializeIndent.NONE)));
}
 
Example #12
Source File: MicroHelperTest.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetPath ()
{
  final IMicroDocument aDoc = new MicroDocument ();
  assertEquals ("#document", MicroHelper.getPath (aDoc, "/"));
  final IMicroElement eRoot = aDoc.appendElement ("root");
  assertEquals ("#document/root", MicroHelper.getPath (eRoot, "/"));
  final IMicroElement eChild = eRoot.appendElement ("child");
  assertEquals ("#document/root/child", MicroHelper.getPath (eChild, "/"));
  assertEquals ("", MicroHelper.getPath (null, "/"));
  try
  {
    MicroHelper.getPath (eChild, null);
    fail ();
  }
  catch (final NullPointerException ex)
  {}
}
 
Example #13
Source File: AbstractMapBasedWALDAO.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Override
@Nonnull
protected EChange onRead (@Nonnull final IMicroDocument aDoc)
{
  // Read all child elements independent of the name - soft migration
  final Class <IMPLTYPE> aDataTypeClass = getDataTypeClass ();
  final Wrapper <EChange> aChange = new Wrapper <> (EChange.UNCHANGED);

  aDoc.getDocumentElement ().forAllChildElements (m_aReadElementFilter, eItem -> {
    final IMPLTYPE aItem = MicroTypeConverter.convertToNative (eItem, aDataTypeClass);
    _addItem (aItem, EDAOActionType.CREATE);
    if (aItem instanceof IDAOReadChangeAware)
      if (((IDAOReadChangeAware) aItem).isReadChanged ())
      {
        // Remember that something was changed while reading
        aChange.set (EChange.CHANGED);
      }
  });
  return aChange.get ();
}
 
Example #14
Source File: PSPreprocessorTest.java    From ph-schematron with Apache License 2.0 6 votes vote down vote up
@Test
public void testIssue51 () throws SchematronException
{
  final PSPreprocessor aPreprocessor = new PSPreprocessor (PSXPathQueryBinding.getInstance ()).setKeepTitles (true)
                                                                                              .setKeepDiagnostics (true);
  final IReadableResource aRes = new FileSystemResource ("src/test/resources/issues/github51/test51.sch");
  final IMicroDocument aDoc = SchematronHelper.getWithResolvedSchematronIncludes (aRes, true);
  final PSReader aReader = new PSReader (aRes).setLenient (true);
  final PSSchema aSchema = aReader.readSchemaFromXML (aDoc.getDocumentElement ());
  final PSSchema aPreprocessedSchema = aPreprocessor.getAsPreprocessedSchema (aSchema);
  assertNotNull (aPreprocessedSchema);
  assertTrue (aPreprocessedSchema.isValid (new DoNothingPSErrorHandler ()));

  final PSWriterSettings aPWS = new PSWriterSettings ();
  aPWS.setXMLWriterSettings (new XMLWriterSettings ().setIndent (EXMLSerializeIndent.INDENT_AND_ALIGN)
                                                     .setPutNamespaceContextPrefixesInRoot (true)
                                                     .setNamespaceContext (PSWriterSettings.createNamespaceMapping (aPreprocessedSchema)));
  LOGGER.info ("Preprocessed:\n" + new PSWriter (aPWS).getXMLString (aPreprocessedSchema));
}
 
Example #15
Source File: MicroReaderTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Test: declare all namespaces in the root element and use them in nested
 * elements
 */
@Test
public void testNamespaces3 ()
{
  final XMLWriterSettings xs = new XMLWriterSettings ();
  xs.setIndent (EXMLSerializeIndent.NONE);
  xs.setUseDoubleQuotesForAttributes (false);

  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);

  final NonBlockingByteArrayOutputStream baos = new NonBlockingByteArrayOutputStream ();
  new MicroSerializer (xs).write (aDoc, baos);
  final String sXML = baos.getAsString (StandardCharsets.UTF_8);
  assertEquals ("<?xml version='1.0' encoding='UTF-8'?>" +
                "<verrryoot xmlns='uri1'>" +
                "<root>" +
                "<ns0:child xmlns:ns0='uri2'>" +
                "<ns0:child2>Value text - no entities!</ns0:child2>" +
                "</ns0:child>" +
                "</root>" +
                "</verrryoot>",
                sXML);
}
 
Example #16
Source File: XMLMapHandler.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static IMicroDocument createMapDocument (@Nonnull final Map <String, String> aMap)
{
  ValueEnforcer.notNull (aMap, "Map");

  final IMicroDocument aDoc = new MicroDocument ();
  final IMicroElement eRoot = aDoc.appendElement (ELEMENT_MAPPING);
  for (final Map.Entry <String, String> aEntry : aMap.entrySet ())
  {
    final IMicroElement eMap = eRoot.appendElement (ELEMENT_MAP);
    eMap.setAttribute (ATTR_KEY, aEntry.getKey ());
    eMap.setAttribute (ATTR_VALUE, aEntry.getValue ());
  }
  return aDoc;
}
 
Example #17
Source File: MicroReaderTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Test: use namespaces all over the place and mix them quite complex
 */
@Test
public void testNamespaces ()
{
  final XMLWriterSettings xs = new XMLWriterSettings ();
  xs.setIndent (EXMLSerializeIndent.NONE);

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

  final NonBlockingByteArrayOutputStream baos = new NonBlockingByteArrayOutputStream ();
  new MicroSerializer (xs).write (aDoc, baos);
  final String sXML = baos.getAsString (StandardCharsets.UTF_8);
  assertEquals ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<verrryoot>" +
                "<root xmlns=\"myuri\">" +
                "<ns0:child xmlns:ns0=\"\">" +
                "<ns1:child2 xmlns:ns1=\"foo\">Value text - no entities!</ns1:child2>" +
                "</ns0:child>" +
                "</root>" +
                "</verrryoot>",
                sXML);
}
 
Example #18
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 #19
Source File: MicroDOMInputStreamProviderTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimple ()
{
  final IMicroDocument aDoc = new MicroDocument ();
  aDoc.appendElement ("test");
  assertNotNull (new MicroDOMInputStreamProvider (aDoc, XMLWriterSettings.DEFAULT_XML_CHARSET_OBJ).getInputStream ());
}
 
Example #20
Source File: MicroHelperTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetDocumentRootElementTagName ()
{
  assertNull (MicroHelper.getDocumentRootElementTagName (null));
  final IMicroDocument aDoc = new MicroDocument ();
  assertNull (MicroHelper.getDocumentRootElementTagName (aDoc));
  aDoc.appendElement ("root");
  assertEquals ("root", MicroHelper.getDocumentRootElementTagName (aDoc));
}
 
Example #21
Source File: SimpleDAOFuncTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
protected IMicroDocument createWriteData ()
{
  final MicroDocument aDoc = new MicroDocument ();
  return aDoc;
}
 
Example #22
Source File: MicroWriterTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testXMLVersion ()
{
  for (final EXMLSerializeVersion eVersion : EXMLSerializeVersion.values ())
  {
    final IMicroDocument aDoc = MicroReader.readMicroXML (TEST_XML);
    final XMLWriterSettings aSettings = new XMLWriterSettings ();
    aSettings.setSerializeVersion (eVersion);
    final String sXML = MicroWriter.getNodeAsString (aDoc, aSettings);
    assertNotNull (sXML);
    assertTrue (sXML.contains ("version=\"" +
                               eVersion.getXMLVersionOrDefault (EXMLVersion.XML_10).getVersion () +
                               "\""));
  }
}
 
Example #23
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 #24
Source File: XMLListHandler.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static IMicroDocument createListDocument (@Nonnull final Collection <String> aCollection)
{
  ValueEnforcer.notNull (aCollection, "Collection");

  final IMicroDocument aDoc = new MicroDocument ();
  final IMicroElement eRoot = aDoc.appendElement (ELEMENT_LIST);
  for (final String sItem : aCollection)
  {
    final IMicroElement eItem = eRoot.appendElement (ELEMENT_ITEM);
    eItem.setAttribute (ATTR_VALUE, sItem);
  }
  return aDoc;
}
 
Example #25
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 #26
Source File: AbstractMapBasedWALDAO.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
@MustBeLocked (ELockType.READ)
protected IMicroDocument createWriteData ()
{
  final IMicroDocument aDoc = new MicroDocument ();
  final IMicroElement eRoot = aDoc.appendElement (ELEMENT_ROOT);
  for (final IMPLTYPE aItem : internalGetAllSortedByKey ())
    eRoot.appendChild (MicroTypeConverter.convertToMicroElement (aItem, ELEMENT_ITEM));
  return aDoc;
}
 
Example #27
Source File: PSPreprocessorTest.java    From ph-schematron with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasic () throws Exception
{
  final PSPreprocessor aPreprocessor = new PSPreprocessor (PSXPathQueryBinding.getInstance ());
  for (final IReadableResource aRes : SchematronTestHelper.getAllValidSchematronFiles ())
  {
    // Resolve all includes
    final IMicroDocument aDoc = SchematronHelper.getWithResolvedSchematronIncludes (aRes, false);
    assertNotNull (aDoc);

    // Read to domain object
    final PSReader aReader = new PSReader (aRes);
    final PSSchema aSchema = aReader.readSchemaFromXML (aDoc.getDocumentElement ());
    assertNotNull (aSchema);

    // Ensure the schema is valid
    final CollectingPSErrorHandler aErrHdl = new CollectingPSErrorHandler ();
    assertTrue (aRes.getPath (), aSchema.isValid (aErrHdl));
    assertTrue (aErrHdl.isEmpty ());

    // Convert to minified schema if not-yet minimal
    final PSSchema aPreprocessedSchema = aPreprocessor.getAsMinimalSchema (aSchema);
    assertNotNull (aPreprocessedSchema);

    if (false)
    {
      final String sXML = MicroWriter.getNodeAsString (aPreprocessedSchema.getAsMicroElement ());
      SimpleFileIO.writeFile (new File ("test-minified",
                                        FilenameHelper.getWithoutPath (aRes.getPath ()) + ".min-pure.sch"),
                              sXML,
                              XMLWriterSettings.DEFAULT_XML_CHARSET_OBJ);
    }

    // Ensure it is still valid and minimal
    assertTrue (aRes.getPath (), aPreprocessedSchema.isValid (aErrHdl));
    assertTrue (aRes.getPath (), aPreprocessedSchema.isMinimal ());
  }
}
 
Example #28
Source File: MicroReader.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nullable
public static IMicroDocument readMicroXML (@Nullable final URL aXML, @Nullable final ISAXReaderSettings aSettings)
{
  if (aXML == null)
    return null;

  return readMicroXML (InputSourceFactory.create (aXML), aSettings);
}
 
Example #29
Source File: MicroReader.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nullable
public static IMicroDocument readMicroXML (@Nullable final URI aXML, @Nullable final ISAXReaderSettings aSettings)
{
  if (aXML == null)
    return null;

  return readMicroXML (InputSourceFactory.create (aXML), aSettings);
}
 
Example #30
Source File: MicroReader.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nullable
public static IMicroDocument readMicroXML (@Nullable final ByteBuffer aXML,
                                           @Nullable final ISAXReaderSettings aSettings)
{
  if (aXML == null)
    return null;

  return readMicroXML (InputSourceFactory.create (aXML), aSettings);
}