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

The following examples show how to use com.helger.xml.microdom.serialize.MicroWriter. 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: SettingsPersistenceXML.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Nonnull
public ESuccess writeSettings (@Nonnull final ISettings aSettings, @Nonnull @WillClose final OutputStream aOS)
{
  ValueEnforcer.notNull (aSettings, "Settings");
  ValueEnforcer.notNull (aOS, "OutputStream");

  try
  {
    // Inside try so that OS is closed
    ValueEnforcer.notNull (aSettings, "Settings");

    // No event manager invocation on writing
    final SettingsMicroDocumentConverter <T> aConverter = new SettingsMicroDocumentConverter <> (m_aSettingsFactory);
    final IMicroDocument aDoc = new MicroDocument ();
    aDoc.appendChild (aConverter.convertToMicroElement (GenericReflection.uncheckedCast (aSettings),
                                                        getWriteNamespaceURI (),
                                                        getWriteElementName ()));

    // auto-closes the stream
    return MicroWriter.writeToStream (aDoc, aOS, m_aXWS);
  }
  finally
  {
    StreamHelper.close (aOS);
  }
}
 
Example #2
Source File: XMLMapHandler.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Write the passed map to the passed output stream using the predefined XML
 * layout.
 *
 * @param aMap
 *        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 writeMap (@Nonnull final Map <String, String> aMap, @Nonnull @WillClose final OutputStream aOS)
{
  ValueEnforcer.notNull (aMap, "Map");
  ValueEnforcer.notNull (aOS, "OutputStream");

  try
  {
    final IMicroDocument aDoc = createMapDocument (aMap);
    return MicroWriter.writeToStream (aDoc, aOS, XMLWriterSettings.DEFAULT_XML_SETTINGS);
  }
  finally
  {
    StreamHelper.close (aOS);
  }
}
 
Example #3
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 #4
Source File: PSBoundSchemaCacheKey.java    From ph-schematron with Apache License 2.0 6 votes vote down vote up
/**
 * Pre-process the read schema, using the determined query binding.
 *
 * @param aSchema
 *        The read schema. Never <code>null</code>.
 * @param aQueryBinding
 *        The determined query binding. Never <code>null</code>.
 * @return The pre-processed schema and never <code>null</code>.
 * @throws SchematronException
 *         In case pre-processing fails
 */
@Nonnull
@OverrideOnDemand
public PSSchema createPreprocessedSchema (@Nonnull final PSSchema aSchema,
                                          @Nonnull final IPSQueryBinding aQueryBinding) throws SchematronException
{
  final PSPreprocessor aPreprocessor = createPreprocessor (aQueryBinding);
  final PSSchema aPreprocessedSchema = aPreprocessor.getAsPreprocessedSchema (aSchema);
  if (aPreprocessedSchema == null)
    throw new SchematronPreprocessException ("Failed to preprocess schema " +
                                             aSchema +
                                             " with query binding " +
                                             aQueryBinding);
  if (SchematronDebug.isShowPreprocessedSchematron ())
    LOGGER.info ("Preprocessed Schematron:\n" +
                 MicroWriter.getNodeAsString (aPreprocessedSchema.getAsMicroElement ()));
  return aPreprocessedSchema;
}
 
Example #5
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 #6
Source File: Issue16Test.java    From ph-schematron with Apache License 2.0 5 votes vote down vote up
public static boolean readModifyAndWrite (@Nonnull final File aSchematronFile) throws Exception
{
  final PSSchema aSchema = new PSReader (new FileSystemResource (aSchematronFile)).readSchema ();
  final PSTitle aTitle = new PSTitle ();
  aTitle.addText ("Created by ph-schematron");
  aSchema.setTitle (aTitle);
  return MicroWriter.writeToFile (aSchema.getAsMicroElement (), aSchematronFile).isSuccess ();
}
 
Example #7
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 #8
Source File: PSReaderTest.java    From ph-schematron with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadAll () throws Exception
{
  for (final IReadableResource aRes : SchematronTestHelper.getAllValidSchematronFiles ())
  {
    final PSReader aReader = new PSReader (aRes);

    // Parse the schema
    final PSSchema aSchema1 = aReader.readSchema ();
    assertNotNull (aSchema1);
    final CollectingPSErrorHandler aLogger = new CollectingPSErrorHandler ();
    assertTrue (aRes.getPath (), aSchema1.isValid (aLogger));
    assertTrue (aLogger.isEmpty ());

    // Convert back to XML
    final IMicroElement e1 = aSchema1.getAsMicroElement ();
    final String sXML1 = MicroWriter.getNodeAsString (e1);

    // Re-read the created XML and re-create it
    final PSSchema aSchema2 = aReader.readSchemaFromXML (e1);
    final IMicroElement e2 = aSchema2.getAsMicroElement ();
    final String sXML2 = MicroWriter.getNodeAsString (e2);

    // Originally created XML and re-created-written XML must match
    assertEquals (sXML1, sXML2);
  }
}
 
Example #9
Source File: DocumentationExamples.java    From ph-schematron with Apache License 2.0 5 votes vote down vote up
public static boolean readModifyAndWrite (@Nonnull final File aSchematronFile) throws Exception
{
  final PSSchema aSchema = new PSReader (new FileSystemResource (aSchematronFile)).readSchema ();
  final PSTitle aTitle = new PSTitle ();
  aTitle.addText ("Created by ph-schematron");
  aSchema.setTitle (aTitle);
  return MicroWriter.writeToFile (aSchema.getAsMicroElement (), aSchematronFile).isSuccess ();
}
 
Example #10
Source File: AbstractSimpleDAO.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Trigger the registered custom exception handlers for read errors.
 *
 * @param t
 *        Thrown exception. Never <code>null</code>.
 * @param sErrorFilename
 *        The filename tried to write to. Never <code>null</code>.
 * @param aDoc
 *        The XML content that should be written. May be <code>null</code> if
 *        the error occurred in XML creation.
 */
protected static void triggerExceptionHandlersWrite (@Nonnull final Throwable t,
                                                     @Nonnull final String sErrorFilename,
                                                     @Nullable final IMicroDocument aDoc)
{
  // Check if a custom exception handler is present
  if (exceptionHandlersWrite ().isNotEmpty ())
  {
    final IReadableResource aRes = new FileSystemResource (sErrorFilename);
    final String sXMLContent = aDoc == null ? "no XML document created" : MicroWriter.getNodeAsString (aDoc);
    exceptionHandlersWrite ().forEach (aCB -> aCB.onDAOWriteException (t, aRes, sXMLContent));
  }
}
 
Example #11
Source File: AbstractWALDAO.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
@OverrideOnDemand
protected String convertNativeToWALString (@Nonnull final DATATYPE aModifiedElement)
{
  final IMicroElement aElement = MicroTypeConverter.convertToMicroElement (aModifiedElement, "item");
  if (aElement == null)
    throw new IllegalStateException ("Failed to convert " +
                                     aModifiedElement +
                                     " of class " +
                                     aModifiedElement.getClass ().getName () +
                                     " to XML!");
  return MicroWriter.getNodeAsString (aElement, getWALXMLWriterSettings ());
}
 
Example #12
Source File: AbstractWALDAO.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Trigger the registered custom exception handlers for read errors.
 *
 * @param t
 *        Thrown exception. Never <code>null</code>.
 * @param sErrorFilename
 *        The filename tried to write to. Never <code>null</code>.
 * @param aDoc
 *        The XML content that should be written. May be <code>null</code> if
 *        the error occurred in XML creation.
 */
protected static void triggerExceptionHandlersWrite (@Nonnull final Throwable t,
                                                     @Nonnull final String sErrorFilename,
                                                     @Nullable final IMicroDocument aDoc)
{
  // Check if a custom exception handler is present
  if (exceptionHandlersWrite ().isNotEmpty ())
  {
    final IReadableResource aRes = new FileSystemResource (sErrorFilename);
    final String sXMLContent = aDoc == null ? "no XML document created" : MicroWriter.getNodeAsString (aDoc);
    exceptionHandlersWrite ().forEach (aCB -> aCB.onDAOWriteException (t, aRes, sXMLContent));
  }
}
 
Example #13
Source File: XMLResourceBundleTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testAll ()
{
  final File aFile = new File ("target/test-classes/unittest-xml-props.xml");
  try
  {
    // Create dummy properties file
    final NonBlockingProperties p = new NonBlockingProperties ();
    p.setProperty ("prop1", "Value 1");
    p.setProperty ("prop2", "äöü");
    MicroWriter.writeToFile (XMLResourceBundle.getAsPropertiesXML (p), aFile);

    // Read again
    final XMLResourceBundle aRB = XMLResourceBundle.getXMLBundle ("unittest-xml-props");
    assertNotNull (aRB);
    assertEquals ("Value 1", aRB.getString ("prop1"));
    assertEquals ("äöü", aRB.getString ("prop2"));
    try
    {
      aRB.getObject ("prop3");
      fail ();
    }
    catch (final MissingResourceException ex)
    {
      // expected
    }
  }
  finally
  {
    FileOperations.deleteFile (aFile);
  }
}
 
Example #14
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 #15
Source File: ReadWriteXML11FuncTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
private static void _generateXmlFile (final String sFilename, @Nonnegative final int nElementCount)
{
  final IMicroDocument aDoc = new MicroDocument ();
  final IMicroElement eMain = aDoc.appendElement ("main_tag");
  for (int i = 0; i < nElementCount; ++i)
    eMain.appendElement ("test").appendText (StringHelper.getLeadingZero (i, 4));

  assertTrue (MicroWriter.writeToFile (aDoc, new File (sFilename), XWS_11).isSuccess ());
}
 
Example #16
Source File: XMLTestHelper.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Test if the {@link MicroTypeConverter} is OK. It converts it to XML and
 * back and than uses
 * {@link CommonsTestHelper#testDefaultImplementationWithEqualContentObject(Object, Object)}
 * to check for equality.
 *
 * @param <T>
 *        The data type to be used and returned
 * @param aObj
 *        The object to test
 * @return The object read after conversion
 */
public static <T> T testMicroTypeConversion (@Nonnull final T aObj)
{
  assertNotNull (aObj);

  // Write to XML
  final IMicroElement e = MicroTypeConverter.convertToMicroElement (aObj, "test");
  assertNotNull (e);

  // Read from XML
  final Object aObj2 = MicroTypeConverter.convertToNative (e, aObj.getClass ());
  assertNotNull (aObj2);

  // Write to XML again
  final IMicroElement e2 = MicroTypeConverter.convertToMicroElement (aObj2, "test");
  assertNotNull (e2);

  // Ensure XML representation is identical
  final String sXML1 = MicroWriter.getNodeAsString (e);
  final String sXML2 = MicroWriter.getNodeAsString (e2);
  CommonsTestHelper._assertEquals ("XML representation must be identical", sXML1, sXML2);

  // Ensure they are equals
  CommonsTestHelper.testDefaultImplementationWithEqualContentObject (aObj, aObj2);

  return GenericReflection.uncheckedCast (aObj2);
}
 
Example #17
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 #18
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 #19
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 #20
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 #21
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 #22
Source File: SettingsMicroDocumentConverterTest.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
@Test
public void testConversionWithTypes () throws UnsupportedEncodingException
{
  final Settings aSrc = new Settings ("myName");
  aSrc.putIn ("field1a", BigInteger.valueOf (1234));
  aSrc.putIn ("field1b", BigInteger.valueOf (-23423424));
  aSrc.putIn ("field2a", BigDecimal.valueOf (12.34));
  aSrc.putIn ("field2b", BigDecimal.valueOf (-2342.334599424));
  aSrc.putIn ("field3a", "My wonderbra string\n(incl newline)");
  aSrc.putIn ("field3b", "");
  aSrc.putIn ("field9a", Boolean.TRUE);
  aSrc.putIn ("field9b", StringParser.parseByteObj ("5"));
  aSrc.putIn ("field9c", Character.valueOf ('ä'));
  aSrc.putIn ("fieldxa", PDTFactory.getCurrentLocalDate ());
  aSrc.putIn ("fieldxb", PDTFactory.getCurrentLocalTime ());
  aSrc.putIn ("fieldxc", PDTFactory.getCurrentLocalDateTime ());
  aSrc.putIn ("fieldxd", PDTFactory.getCurrentZonedDateTime ());
  aSrc.putIn ("fieldxe", Duration.ofHours (5));
  aSrc.putIn ("fieldxf", Period.ofDays (3));
  aSrc.putIn ("fieldxg", "Any byte ärräy".getBytes (StandardCharsets.UTF_8.name ()));

  final Settings aNestedSettings = new Settings ("nestedSettings");
  aNestedSettings.putIn ("a", "b");
  aNestedSettings.putIn ("c", "d");
  aNestedSettings.putIn ("e", Clock.systemDefaultZone ().millis ());
  aSrc.putIn ("fieldxh", aNestedSettings);

  // null value
  aSrc.putIn ("fieldnull", null);

  // To XML
  final IMicroElement eSrcElement = MicroTypeConverter.convertToMicroElement (aSrc, "root");
  assertNotNull (eSrcElement);
  if (false)
    LOGGER.info (MicroWriter.getNodeAsString (eSrcElement));

  // From XML
  final ISettings aDst = MicroTypeConverter.convertToNative (eSrcElement, Settings.class);
  assertNotNull (aDst);

  // No longer true, because now all values are String
  if (false)
  {
    assertEquals (aSrc, aDst);

    // Compare list
    assertEquals (BigInteger.valueOf (1234), aDst.getValue ("field1a"));
  }
  else
  {
    assertEquals ("1234", aDst.getValue ("field1a"));
  }

  final ISettings aDst2 = new Settings (aDst.getName ());
  aDst2.putAllIn (aDst);
  assertEquals (aDst, aDst2);
  assertTrue (aDst2.putIn ("field3b", "doch was").isChanged ());
  assertFalse (aDst.equals (aDst2));
}
 
Example #23
Source File: AbstractSimpleDAO.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
/**
 * The main method for writing the new data to a file. This method may only be
 * called within a write lock!
 *
 * @return {@link ESuccess} and never <code>null</code>.
 */
@Nonnull
@SuppressFBWarnings ("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE")
@MustBeLocked (ELockType.WRITE)
private ESuccess _writeToFile ()
{
  // Build the filename to write to
  final String sFilename = m_aFilenameProvider.get ();
  if (sFilename == null)
  {
    // We're not operating on a file! Required for testing
    if (!isSilentMode ())
      if (LOGGER.isInfoEnabled ())
        LOGGER.info ("The DAO of class " + getClass ().getName () + " cannot write to a file");
    return ESuccess.FAILURE;
  }

  // Check for a filename change before writing
  if (!sFilename.equals (m_sPreviousFilename))
  {
    onFilenameChange (m_sPreviousFilename, sFilename);
    m_sPreviousFilename = sFilename;
  }

  if (!isSilentMode ())
    if (LOGGER.isInfoEnabled ())
      LOGGER.info ("Trying to write DAO file '" + sFilename + "'");

  File aFile = null;
  IMicroDocument aDoc = null;
  try
  {
    // Get the file handle
    aFile = getSafeFile (sFilename, EMode.WRITE);

    m_aStatsCounterWriteTotal.increment ();
    final StopWatch aSW = StopWatch.createdStarted ();

    // Create XML document to write
    aDoc = createWriteData ();
    if (aDoc == null)
      throw new DAOException ("Failed to create data to write to file");

    // Generic modification
    modifyWriteData (aDoc);

    // Perform optional stuff like backup etc. Must be done BEFORE the output
    // stream is opened!
    beforeWriteToFile (sFilename, aFile);

    // Get the output stream
    final OutputStream aOS = FileHelper.getOutputStream (aFile);
    if (aOS == null)
    {
      // Happens, when another application has the file open!
      // Logger warning already emitted
      throw new DAOException ("Failed to open output stream");
    }

    // Write to file (closes the OS)
    final IXMLWriterSettings aXWS = getXMLWriterSettings ();
    if (MicroWriter.writeToStream (aDoc, aOS, aXWS).isFailure ())
      throw new DAOException ("Failed to write DAO XML data to file");

    m_aStatsCounterWriteTimer.addTime (aSW.stopAndGetMillis ());
    m_aStatsCounterWriteSuccess.increment ();
    m_nWriteCount++;
    m_aLastWriteDT = PDTFactory.getCurrentLocalDateTime ();
    return ESuccess.SUCCESS;
  }
  catch (final Exception ex)
  {
    final String sErrorFilename = aFile != null ? aFile.getAbsolutePath () : sFilename;

    if (LOGGER.isErrorEnabled ())
      LOGGER.error ("The DAO of class " +
                    getClass ().getName () +
                    " failed to write the DAO data to '" +
                    sErrorFilename +
                    "'",
                    ex);

    triggerExceptionHandlersWrite (ex, sErrorFilename, aDoc);
    m_aStatsCounterWriteExceptions.increment ();
    return ESuccess.FAILURE;
  }
}
 
Example #24
Source File: SchematronValidator.java    From ph-schematron with Apache License 2.0 3 votes vote down vote up
/**
 * Check if the passed micro node is a valid schematron instance.
 *
 * @param aNode
 *        The micro node to check. May be <code>null</code>.
 * @return <code>true</code> if the schematron is valid, <code>false</code>
 *         otherwise.
 */
public static boolean isValidSchematron (@Nullable final IMicroNode aNode)
{
  if (aNode == null)
    return false;

  return isValidSchematron (TransformSourceFactory.create (MicroWriter.getNodeAsString (aNode)));
}
 
Example #25
Source File: PSWriter.java    From ph-schematron with Apache License 2.0 3 votes vote down vote up
/**
 * Get the passed Schematron element as a String
 *
 * @param aPSElement
 *        The schematron element to convert to a string. May not be
 *        <code>null</code>.
 * @return The passed element as a string or <code>null</code> if
 *         serialization failed.
 */
@Nullable
public String getXMLString (@Nonnull final IPSElement aPSElement)
{
  ValueEnforcer.notNull (aPSElement, "PSElement");
  final IMicroElement eXML = aPSElement.getAsMicroElement ();
  return MicroWriter.getNodeAsString (getAsDocument (eXML), m_aWriterSettings.getXMLWriterSettings ());
}
 
Example #26
Source File: PSWriter.java    From ph-schematron with Apache License 2.0 3 votes vote down vote up
/**
 * Write the passed Schematron element to the passed writer.
 *
 * @param aPSElement
 *        The schematron element to write. May not be <code>null</code>.
 * @param aWriter
 *        The writer to write things to. May not be <code>null</code>. The
 *        writer is automatically closed.
 * @return {@link ESuccess}.
 */
@Nonnull
public ESuccess writeToWriter (@Nonnull final IPSElement aPSElement, @Nonnull @WillClose final Writer aWriter)
{
  ValueEnforcer.notNull (aPSElement, "PSElement");
  final IMicroElement eXML = aPSElement.getAsMicroElement ();
  return MicroWriter.writeToWriter (getAsDocument (eXML), aWriter, m_aWriterSettings.getXMLWriterSettings ());
}
 
Example #27
Source File: PSWriter.java    From ph-schematron with Apache License 2.0 3 votes vote down vote up
/**
 * Write the passed Schematron element to the passed output stream.
 *
 * @param aPSElement
 *        The schematron element to write. May not be <code>null</code>.
 * @param aOS
 *        The output stream to write things to. May not be <code>null</code>.
 *        The stream is automatically closed.
 * @return {@link ESuccess}.
 */
@Nonnull
public ESuccess writeToStream (@Nonnull final IPSElement aPSElement, @Nonnull @WillClose final OutputStream aOS)
{
  ValueEnforcer.notNull (aPSElement, "PSElement");
  final IMicroElement eXML = aPSElement.getAsMicroElement ();
  return MicroWriter.writeToStream (getAsDocument (eXML), aOS, m_aWriterSettings.getXMLWriterSettings ());
}
 
Example #28
Source File: PSWriter.java    From ph-schematron with Apache License 2.0 3 votes vote down vote up
/**
 * Write the passed Schematron element to the passed file.
 *
 * @param aPSElement
 *        The schematron element to write. May not be <code>null</code>.
 * @param aFile
 *        The file to write things to. May not be <code>null</code>.
 * @return {@link ESuccess}.
 */
@Nonnull
public ESuccess writeToFile (@Nonnull final IPSElement aPSElement, @Nonnull final File aFile)
{
  ValueEnforcer.notNull (aPSElement, "PSElement");
  final IMicroElement eXML = aPSElement.getAsMicroElement ();
  return MicroWriter.writeToFile (getAsDocument (eXML), aFile, m_aWriterSettings.getXMLWriterSettings ());
}