Java Code Examples for com.helger.commons.state.ESuccess#SUCCESS

The following examples show how to use com.helger.commons.state.ESuccess#SUCCESS . 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: StreamHelper.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Close the passed object, without trying to call flush on it.
 *
 * @param aCloseable
 *        The object to be closed. May be <code>null</code>.
 * @return {@link ESuccess#SUCCESS} if the object was successfully closed.
 */
@Nonnull
public static ESuccess closeWithoutFlush (@Nullable @WillClose final AutoCloseable aCloseable)
{
  if (aCloseable != null)
  {
    try
    {
      // close stream
      aCloseable.close ();
      return ESuccess.SUCCESS;
    }
    catch (final Exception ex)
    {
      if (!isKnownEOFException (ex))
        LOGGER.error ("Failed to close object " + aCloseable.getClass ().getName (), _propagate (ex));
    }
  }
  return ESuccess.FAILURE;
}
 
Example 2
Source File: PDTConfig.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Set the default date time zone to use. This effects all objects created via
 * {@link PDTFactory} as well as the default JDK TimeZone.
 *
 * @param sDateTimeZoneID
 *        Must be a valid, non-<code>null</code> time zone.
 * @return {@link ESuccess}
 */
@Nonnull
public static ESuccess setDefaultDateTimeZoneID (@Nonnull @Nonempty final String sDateTimeZoneID)
{
  ValueEnforcer.notEmpty (sDateTimeZoneID, "DateTimeZoneID");

  try
  {
    // Try to resolve ID -> throws exception if unknown
    final ZoneId aDefaultZoneId = ZoneId.of (sDateTimeZoneID);

    // getTimeZone falls back to GMT if unknown
    final TimeZone aDefaultTimeZone = TimeZone.getTimeZone (aDefaultZoneId);

    s_aDefaultZoneId = aDefaultZoneId;
    TimeZone.setDefault (aDefaultTimeZone);
    return ESuccess.SUCCESS;
  }
  catch (final DateTimeException ex)
  {
    // time zone ID is unknown
    LOGGER.warn ("Unsupported ZoneId '" + sDateTimeZoneID + "'", ex);
    return ESuccess.FAILURE;
  }
}
 
Example 3
Source File: ThreadHelper.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Sleep the current thread for a certain amount of time
 *
 * @param nMilliseconds
 *        The milliseconds to sleep. Must be &ge; 0.
 * @return {@link ESuccess#SUCCESS} if sleeping was not interrupted,
 *         {@link ESuccess#FAILURE} if sleeping was interrupted
 */
@Nonnull
public static ESuccess sleep (@Nonnegative final long nMilliseconds)
{
  ValueEnforcer.isGE0 (nMilliseconds, "MilliSeconds");

  try
  {
    Thread.sleep (nMilliseconds);
    return ESuccess.SUCCESS;
  }
  catch (final InterruptedException ex)
  {
    Thread.currentThread ().interrupt ();
    return ESuccess.FAILURE;
  }
}
 
Example 4
Source File: ObjectPool.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Nonnull
public ESuccess returnObject (@Nonnull final DATATYPE aItem)
{
  m_aLock.lock ();
  try
  {
    for (int i = 0; i < m_aItems.length; ++i)
      if (m_aUsed[i] && aItem == m_aItems[i])
      {
        m_aUsed[i] = false;

        // Okay, we have one more unused item
        m_aAvailable.release ();
        return ESuccess.SUCCESS;
      }
    if (!isSilentMode ())
      LOGGER.warn ("Object " + aItem + " is not pooled!");
    return ESuccess.FAILURE;
  }
  finally
  {
    m_aLock.unlock ();
  }
}
 
Example 5
Source File: JMXHelper.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static ESuccess exposeMBean (@Nonnull final Object aObject, @Nonnull final ObjectName aObjectName)
{
  ValueEnforcer.notNull (aObject, "Object");
  ValueEnforcer.notNull (aObjectName, "ObjectName");

  try
  {
    ManagementFactory.getPlatformMBeanServer ().registerMBean (aObject, aObjectName);
    return ESuccess.SUCCESS;
  }
  catch (final JMException ex)
  {
    LOGGER.error ("Error registering MBean with name " + aObjectName, ex);
    return ESuccess.FAILURE;
  }
}
 
Example 6
Source File: BasicTreeItemWithID.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Nonnull
public final ESuccess changeParent (@Nonnull final ITEMTYPE aNewParent)
{
  ValueEnforcer.notNull (aNewParent, "NewParent");

  // no change so far
  if (getParent () == aNewParent)
    return ESuccess.SUCCESS;

  // cannot make a child of this, this' new parent.
  final ITEMTYPE aThis = _asT (this);
  if (aNewParent.isSameOrChildOf (aThis))
    return ESuccess.FAILURE;

  // add this to the new parent
  if (m_aParent.removeChild (getID ()).isUnchanged ())
    throw new IllegalStateException ("Failed to remove this from parent!");

  // Remember new parent!
  m_aParent = aNewParent;
  return ESuccess.valueOfChange (aNewParent.internalAddChild (getID (), aThis, false));
}
 
Example 7
Source File: BasicTreeItem.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Nonnull
public final ESuccess changeParent (@Nonnull final ITEMTYPE aNewParent)
{
  ValueEnforcer.notNull (aNewParent, "NewParent");

  // no change so far
  if (getParent () == aNewParent)
    return ESuccess.SUCCESS;

  // cannot make a child of this, this' new parent.
  final ITEMTYPE aThis = thisAsT ();
  if (aNewParent.isSameOrChildOf (aThis))
    return ESuccess.FAILURE;

  // add this to the new parent
  if (getParent ().removeChild (aThis).isUnchanged ())
    throw new IllegalStateException ("Failed to remove this from parent!");

  // Remember new parent!
  m_aParent = aNewParent;
  return ESuccess.valueOfChange (aNewParent.internalAddChild (aThis));
}
 
Example 8
Source File: GenericJAXBMarshaller.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Nonnull
public final ESuccess write (@Nonnull final JAXBTYPE aObject,
                             @Nonnull final IJAXBMarshaller <JAXBTYPE> aMarshallerFunc)
{
  ValueEnforcer.notNull (aObject, "Object");
  ValueEnforcer.notNull (aMarshallerFunc, "MarshallerFunc");

  try
  {
    final Marshaller aMarshaller = _createMarshaller (getClassLoader ());
    customizeMarshaller (aMarshaller);

    final JAXBElement <JAXBTYPE> aJAXBElement = m_aJAXBElementWrapper.apply (aObject);
    aMarshallerFunc.doMarshal (aMarshaller, aJAXBElement);
    return ESuccess.SUCCESS;
  }
  catch (final JAXBException ex)
  {
    m_aWriteExceptionCallbacks.forEach (x -> x.onException (ex));
  }
  return ESuccess.FAILURE;
}
 
Example 9
Source File: StreamHelper.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Write bytes to an {@link OutputStream}.
 *
 * @param aOS
 *        The output stream to write to. May not be <code>null</code>. Is
 *        closed independent of error or success.
 * @param aBuf
 *        The byte array from which is to be written. May not be
 *        <code>null</code>.
 * @param nOfs
 *        The 0-based index to the first byte in the array to be written. May
 *        not be &lt; 0.
 * @param nLen
 *        The non-negative amount of bytes to be written. May not be &lt; 0.
 * @return {@link ESuccess}
 */
@Nonnull
public static ESuccess writeStream (@WillClose @Nonnull final OutputStream aOS,
                                    @Nonnull final byte [] aBuf,
                                    @Nonnegative final int nOfs,
                                    @Nonnegative final int nLen)
{
  try
  {
    ValueEnforcer.notNull (aOS, "OutputStream");
    ValueEnforcer.isArrayOfsLen (aBuf, nOfs, nLen);

    aOS.write (aBuf, nOfs, nLen);
    aOS.flush ();
    return ESuccess.SUCCESS;
  }
  catch (final IOException ex)
  {
    LOGGER.error ("Failed to write to output stream", _propagate (ex));
    return ESuccess.FAILURE;
  }
  finally
  {
    close (aOS);
  }
}
 
Example 10
Source File: MicroWriter.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Write a Micro Node to a {@link Writer}.
 *
 * @param aNode
 *        The node to be serialized. May be any kind of node (incl.
 *        documents). May not be <code>null</code>.
 * @param aWriter
 *        The writer to write to. May not be <code>null</code>. The writer is
 *        closed anyway directly after the operation finishes (on success and
 *        on error).
 * @param aSettings
 *        The settings to be used for the creation. May not be
 *        <code>null</code>.
 * @return {@link ESuccess}
 */
@Nonnull
public static ESuccess writeToWriter (@Nonnull final IMicroNode aNode,
                                      @Nonnull @WillClose final Writer aWriter,
                                      @Nonnull final IXMLWriterSettings aSettings)
{
  ValueEnforcer.notNull (aNode, "Node");
  ValueEnforcer.notNull (aWriter, "Writer");
  ValueEnforcer.notNull (aSettings, "Settings");

  try
  {
    final MicroSerializer aSerializer = new MicroSerializer (aSettings);
    aSerializer.write (aNode, aWriter);
    return ESuccess.SUCCESS;
  }
  finally
  {
    StreamHelper.close (aWriter);
  }
}
 
Example 11
Source File: MicroWriter.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Write a Micro Node to an {@link OutputStream}.
 *
 * @param aNode
 *        The node to be serialized. May be any kind of node (incl.
 *        documents). May not be <code>null</code>.
 * @param aOS
 *        The output stream to write to. May not be <code>null</code>. The
 *        output stream is closed anyway directly after the operation finishes
 *        (on success and on error).
 * @param aSettings
 *        The settings to be used for the creation. May not be
 *        <code>null</code>.
 * @return {@link ESuccess}
 */
@Nonnull
public static ESuccess writeToStream (@Nonnull final IMicroNode aNode,
                                      @Nonnull @WillClose final OutputStream aOS,
                                      @Nonnull final IXMLWriterSettings aSettings)
{
  ValueEnforcer.notNull (aNode, "Node");
  ValueEnforcer.notNull (aOS, "OutputStream");
  ValueEnforcer.notNull (aSettings, "Settings");

  try
  {
    final MicroSerializer aSerializer = new MicroSerializer (aSettings);
    aSerializer.write (aNode, aOS);
    return ESuccess.SUCCESS;
  }
  finally
  {
    StreamHelper.close (aOS);
  }
}
 
Example 12
Source File: ChannelHelper.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static ESuccess release (@Nullable final FileLock aFileLock)
{
  if (aFileLock != null)
  {
    try
    {
      aFileLock.release ();
      return ESuccess.SUCCESS;
    }
    catch (final IOException ex)
    {
      if (LOGGER.isErrorEnabled ())
        LOGGER.error ("Failed to release object " + aFileLock, ex instanceof IMockException ? null : ex);
    }
  }

  return ESuccess.FAILURE;
}
 
Example 13
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 14
Source File: XMLListHandler.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static ESuccess readList (@Nonnull final IMicroElement aParentElement,
                                 @Nonnull final Collection <String> aTargetList)
{
  ValueEnforcer.notNull (aParentElement, "ParentElement");
  ValueEnforcer.notNull (aTargetList, "TargetList");

  try
  {
    // and insert all elements
    for (final IMicroElement eItem : aParentElement.getAllChildElements (ELEMENT_ITEM))
    {
      final String sValue = eItem.getAttributeValue (ATTR_VALUE);
      if (sValue == null)
        LOGGER.warn ("Ignoring list item because value is null");
      else
        if (!aTargetList.add (sValue))
        {
          if (LOGGER.isWarnEnabled ())
            LOGGER.warn ("Ignoring list item '" + sValue + "' because value is already contained");
        }
    }
    return ESuccess.SUCCESS;
  }
  catch (final Exception ex)
  {
    LOGGER.warn ("Failed to read list document", ex);
  }
  return ESuccess.FAILURE;
}
 
Example 15
Source File: SettingsPersistenceProperties.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
public ESuccess writeSettings (@Nonnull final ISettings aSettings, @Nonnull @WillClose final OutputStream aOS)
{
  ValueEnforcer.notNull (aOS, "OutputStream");

  try
  {
    final NonBlockingProperties aProps = new NonBlockingProperties ();
    // Must not be sorted, as Properties sorts them as it wishes...
    for (final Map.Entry <String, Object> aEntry : aSettings.entrySet ())
    {
      final String sName = aEntry.getKey ();
      final Object aValue = aEntry.getValue ();
      if (aValue instanceof ISettings)
        throw new IllegalArgumentException ("When saving settings to a Properties object, it may not contained nested settings! Now the key '" +
                                            sName +
                                            "' is mapped to a nested ISettings object!");
      final String sValue = TypeConverter.convert (aValue, String.class);
      aProps.put (sName, sValue);
    }
    // Does not close the output stream!
    aProps.store (aOS, aSettings.getName ());
    return ESuccess.SUCCESS;
  }
  catch (final IOException ex)
  {
    LOGGER.error ("Failed to write settings to properties file", ex);
    return ESuccess.FAILURE;
  }
  finally
  {
    StreamHelper.close (aOS);
  }
}
 
Example 16
Source File: SettingsPersistenceJson.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
public ESuccess writeSettings (@Nonnull final ISettings aSettings, @Nonnull @WillClose final OutputStream aOS)
{
  ValueEnforcer.notNull (aOS, "OutputStream");

  try
  {
    final IJsonObject aProps = new JsonObject ();
    for (final Map.Entry <String, Object> aEntry : CollectionHelper.getSorted (aSettings.entrySet (),
                                                                               Comparator.comparing (Map.Entry::getKey)))
    {
      final String sName = aEntry.getKey ();
      final Object aValue = aEntry.getValue ();
      final String sValue = TypeConverter.convert (aValue, String.class);
      aProps.add (sName, sValue);
    }

    final JsonWriterSettings aJWS = new JsonWriterSettings ();
    aJWS.setIndentEnabled (true);
    aJWS.setQuoteNames (false);

    // Does not close the output stream!
    new JsonWriter (aJWS).writeToWriterAndClose (aProps, StreamHelper.createWriter (aOS, m_aCharset));
    return ESuccess.SUCCESS;
  }
  catch (final IOException ex)
  {
    LOGGER.error ("Failed to write settings to JSON file", ex);
    return ESuccess.FAILURE;
  }
  finally
  {
    StreamHelper.close (aOS);
  }
}
 
Example 17
Source File: ConcurrentCollectorMultiple.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Internal method to invoke the performed for the passed list of objects.
 *
 * @param aObjectsToPerform
 *        List of objects to be passed to the performer. Never
 *        <code>null</code>. The length is at last
 *        {@link #getMaxPerformCount()}.
 * @return {@link ESuccess}
 */
@Nonnull
private ESuccess _perform (@Nonnull final List <DATATYPE> aObjectsToPerform)
{
  if (!aObjectsToPerform.isEmpty ())
  {
    try
    {
      // Perform the action on the objects, regardless of whether a
      // "stop queue message" was received or not
      m_aPerformer.runAsync (aObjectsToPerform);
    }
    catch (final Exception ex)
    {
      LOGGER.error ("Failed to perform actions on " +
                    aObjectsToPerform.size () +
                    " objects with performer " +
                    m_aPerformer +
                    " - objects are lost!",
                    ex);
      return ESuccess.FAILURE;
    }

    // clear perform-list anyway
    aObjectsToPerform.clear ();
  }

  return ESuccess.SUCCESS;
}
 
Example 18
Source File: FileOperations.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
/**
 * Copy the content of the source file to the destination file using
 * {@link FileChannel}. This version seems to fail with UNC paths.
 *
 * @param aSrcFile
 *        Source file. May not be <code>null</code>.
 * @param aDestFile
 *        Destination file. May not be <code>null</code>.
 * @return {@link ESuccess}
 */
@Nonnull
private static ESuccess _copyFileViaChannel (@Nonnull final File aSrcFile, @Nonnull final File aDestFile)
{
  final FileChannel aSrcChannel = FileChannelHelper.getFileReadChannel (aSrcFile);
  if (aSrcChannel == null)
    return ESuccess.FAILURE;

  try
  {
    final FileChannel aDstChannel = FileChannelHelper.getFileWriteChannel (aDestFile, EAppend.TRUNCATE);
    if (aDstChannel == null)
      return ESuccess.FAILURE;

    try
    {
      FileLock aSrcLock = null;
      FileLock aDestLock = null;
      try
      {
        final long nBytesToRead = aSrcChannel.size ();

        // Shared read lock and exclusive write lock
        aSrcLock = aSrcChannel.lock (0, nBytesToRead, true);
        aDestLock = aDstChannel.lock ();

        // Main copying - the loop version is much quicker than then
        // transferTo with full size!
        long nBytesWritten = 0;
        final long nChunkSize = 1L * CGlobal.BYTES_PER_MEGABYTE;
        while (nBytesWritten < nBytesToRead)
          nBytesWritten += aSrcChannel.transferTo (nBytesWritten, nChunkSize, aDstChannel);

        if (nBytesToRead != nBytesWritten)
        {
          if (LOGGER.isErrorEnabled ())
            LOGGER.error ("Failed to copy file. Meant to read " + nBytesToRead + " bytes but wrote " + nBytesWritten);
          return ESuccess.FAILURE;
        }
        return ESuccess.SUCCESS;
      }
      catch (final IOException ex)
      {
        throw new IllegalStateException ("Failed to copy from " + aSrcFile + " to " + aDestFile, ex);
      }
      finally
      {
        // Unlock
        ChannelHelper.release (aDestLock);
        ChannelHelper.release (aSrcLock);
      }
    }
    finally
    {
      ChannelHelper.close (aDstChannel);
    }
  }
  finally
  {
    ChannelHelper.close (aSrcChannel);
  }
}
 
Example 19
Source File: StreamHelper.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
/**
 * Pass the content of the given input stream to the given output stream. The
 * input stream is automatically closed, whereas the output stream stays open!
 *
 * @param aIS
 *        The input stream to read from. May be <code>null</code>.
 * @param bCloseIS
 *        <code>true</code> to close the InputStream, <code>false</code> to
 *        leave it open.
 * @param aOS
 *        The output stream to write to. May be <code>null</code>.
 * @param bCloseOS
 *        <code>true</code> to close the OutputStream, <code>false</code> to
 *        leave it open.
 * @param aBuffer
 *        The buffer to use. May not be <code>null</code>.
 * @param aLimit
 *        An optional maximum number of bytes to copied from the input stream
 *        to the output stream. May be <code>null</code> to indicate no limit,
 *        meaning all bytes are copied.
 * @param aExceptionCallback
 *        The Exception callback to be invoked, if an exception occurs. May
 *        not be <code>null</code>.
 * @param aCopyByteCount
 *        An optional mutable long object that will receive the total number
 *        of copied bytes. Note: and optional old value is overwritten. Note:
 *        this is only called, if copying was successful, and not in case of
 *        an exception.
 * @return <code>{@link ESuccess#SUCCESS}</code> if copying took place, <code>
 *         {@link ESuccess#FAILURE}</code> otherwise
 * @since 9.3.6
 */
@Nonnull
public static ESuccess copyInputStreamToOutputStream (@Nullable final InputStream aIS,
                                                      final boolean bCloseIS,
                                                      @Nullable final OutputStream aOS,
                                                      final boolean bCloseOS,
                                                      @Nonnull @Nonempty final byte [] aBuffer,
                                                      @Nullable final Long aLimit,
                                                      @Nullable final IExceptionCallback <IOException> aExceptionCallback,
                                                      @Nullable final MutableLong aCopyByteCount)
{
  try
  {
    ValueEnforcer.notEmpty (aBuffer, "Buffer");
    ValueEnforcer.isTrue (aLimit == null || aLimit.longValue () >= 0, () -> "Limit may not be negative: " + aLimit);

    if (aIS != null && aOS != null)
    {
      // both streams are not null
      final long nTotalBytesCopied;
      if (aLimit == null)
        nTotalBytesCopied = _copyInputStreamToOutputStream (aIS, aOS, aBuffer);
      else
        nTotalBytesCopied = _copyInputStreamToOutputStreamWithLimit (aIS, aOS, aBuffer, aLimit.longValue ());

      // Add to statistics
      s_aByteSizeHdl.addSize (nTotalBytesCopied);

      // Remember copied bytes?
      if (aCopyByteCount != null)
        aCopyByteCount.set (nTotalBytesCopied);
      return ESuccess.SUCCESS;
    }
  }
  catch (final IOException ex)
  {
    if (aExceptionCallback != null)
      aExceptionCallback.onException (ex);
    else
      if (!isKnownEOFException (ex))
        LOGGER.error ("Failed to copy from InputStream to OutputStream", _propagate (ex));
  }
  finally
  {
    // Ensure streams are closed under all circumstances
    if (bCloseIS)
      close (aIS);
    if (bCloseOS)
      close (aOS);
  }
  return ESuccess.FAILURE;
}
 
Example 20
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;
  }
}